Xinqi Bao's Git

some minor fixes regarding the new xinerama support
[dwm.git] / dwm.c
1 /* See LICENSE file for copyright and license details.
2 *
3 * dynamic window manager is designed like any other X client as well. It is
4 * driven through handling X events. In contrast to other X clients, a window
5 * manager selects for SubstructureRedirectMask on the root window, to receive
6 * events about window (dis-)appearance. Only one X connection at a time is
7 * allowed to select for this event mask.
8 *
9 * The event handlers of dwm are organized in an array which is accessed
10 * whenever a new event has been fetched. This allows event dispatching
11 * in O(1) time.
12 *
13 * Each child of the root window is called a client, except windows which have
14 * set the override_redirect flag. Clients are organized in a global
15 * linked client list, the focus history is remembered through a global
16 * stack list. Each client contains a bit array to indicate the tags of a
17 * client.
18 *
19 * Keys and tagging rules are organized as arrays and defined in config.h.
20 *
21 * To understand everything else, start reading main().
22 */
23 #include <errno.h>
24 #include <locale.h>
25 #include <stdarg.h>
26 #include <signal.h>
27 #include <stdio.h>
28 #include <stdlib.h>
29 #include <string.h>
30 #include <unistd.h>
31 #include <sys/types.h>
32 #include <sys/wait.h>
33 #include <X11/cursorfont.h>
34 #include <X11/keysym.h>
35 #include <X11/Xatom.h>
36 #include <X11/Xlib.h>
37 #include <X11/Xproto.h>
38 #include <X11/Xutil.h>
39 #ifdef XINERAMA
40 #include <X11/extensions/Xinerama.h>
41 #endif /* XINERAMA */
42
43 /* macros */
44 #define BUTTONMASK (ButtonPressMask|ButtonReleaseMask)
45 #define CLEANMASK(mask) (mask & ~(numlockmask|LockMask))
46 #define INRECT(X,Y,RX,RY,RW,RH) ((X) >= (RX) && (X) < (RX) + (RW) && (Y) >= (RY) && (Y) < (RY) + (RH))
47 #define ISVISIBLE(M, C) ((M) == (&mon[C->mon]) && (C->tags & tagset[M->seltags]))
48 #define LENGTH(X) (sizeof X / sizeof X[0])
49 #define MAX(a, b) ((a) > (b) ? (a) : (b))
50 #define MIN(a, b) ((a) < (b) ? (a) : (b))
51 #define MOUSEMASK (BUTTONMASK|PointerMotionMask)
52 #define WIDTH(x) ((x)->w + 2 * (x)->bw)
53 #define HEIGHT(x) ((x)->h + 2 * (x)->bw)
54 #define TAGMASK ((int)((1LL << LENGTH(tags)) - 1))
55 #define TEXTW(x) (textnw(x, strlen(x)) + dc.font.height)
56
57 /* enums */
58 enum { CurNormal, CurResize, CurMove, CurLast }; /* cursor */
59 enum { ColBorder, ColFG, ColBG, ColLast }; /* color */
60 enum { NetSupported, NetWMName, NetLast }; /* EWMH atoms */
61 enum { WMProtocols, WMDelete, WMState, WMLast }; /* default atoms */
62 enum { ClkTagBar, ClkLtSymbol, ClkStatusText, ClkWinTitle,
63 ClkClientWin, ClkRootWin, ClkLast }; /* clicks */
64
65 typedef union {
66 int i;
67 unsigned int ui;
68 float f;
69 void *v;
70 } Arg;
71
72 typedef struct {
73 unsigned int click;
74 unsigned int mask;
75 unsigned int button;
76 void (*func)(const Arg *arg);
77 const Arg arg;
78 } Button;
79
80 typedef struct Client Client;
81 struct Client {
82 char name[256];
83 float mina, maxa;
84 int x, y, w, h;
85 int basew, baseh, incw, inch, maxw, maxh, minw, minh;
86 int bw, oldbw;
87 unsigned int tags;
88 unsigned int mon;
89 Bool isfixed, isfloating, isurgent;
90 Client *next;
91 Client *snext;
92 Window win;
93 };
94
95 typedef struct {
96 int x, y, w, h;
97 unsigned long norm[ColLast];
98 unsigned long sel[ColLast];
99 Drawable drawable;
100 GC gc;
101 struct {
102 int ascent;
103 int descent;
104 int height;
105 XFontSet set;
106 XFontStruct *xfont;
107 } font;
108 } DC; /* draw context */
109
110 typedef struct {
111 unsigned int mod;
112 KeySym keysym;
113 void (*func)(const Arg *);
114 const Arg arg;
115 } Key;
116
117 typedef struct {
118 char symbol[4];
119 float mfact;
120 int by, btx; /* bar geometry */
121 int wx, wy, ww, wh; /* window area */
122 unsigned int seltags;
123 unsigned int sellt;
124 Bool showbar;
125 Bool topbar;
126 Window barwin;
127 } Monitor;
128
129 typedef struct {
130 const char *symbol;
131 void (*arrange)(Monitor *);
132 } Layout;
133
134 typedef struct {
135 const char *class;
136 const char *instance;
137 const char *title;
138 unsigned int tags;
139 Bool isfloating;
140 } Rule;
141
142 /* function declarations */
143 static void applyrules(Client *c);
144 static Bool applysizehints(Client *c, int *x, int *y, int *w, int *h);
145 static void arrange(void);
146 static void attach(Client *c);
147 static void attachstack(Client *c);
148 static void buttonpress(XEvent *e);
149 static void checkotherwm(void);
150 static void cleanup(void);
151 static void clearurgent(Client *c);
152 static void configure(Client *c);
153 static void configurenotify(XEvent *e);
154 static void configurerequest(XEvent *e);
155 static void destroynotify(XEvent *e);
156 static void detach(Client *c);
157 static void detachstack(Client *c);
158 static void die(const char *errstr, ...);
159 static void drawbar(Monitor *m);
160 static void drawbars();
161 static void drawsquare(Bool filled, Bool empty, Bool invert, unsigned long col[ColLast]);
162 static void drawtext(const char *text, unsigned long col[ColLast], Bool invert);
163 static void enternotify(XEvent *e);
164 static void expose(XEvent *e);
165 static void focus(Client *c);
166 static void focusin(XEvent *e);
167 static void focusstack(const Arg *arg);
168 static Client *getclient(Window w);
169 static unsigned long getcolor(const char *colstr);
170 static long getstate(Window w);
171 static Bool gettextprop(Window w, Atom atom, char *text, unsigned int size);
172 static void grabbuttons(Client *c, Bool focused);
173 static void grabkeys(void);
174 static void initfont(const char *fontstr);
175 static Bool isprotodel(Client *c);
176 static void keypress(XEvent *e);
177 static void killclient(const Arg *arg);
178 static void manage(Window w, XWindowAttributes *wa);
179 static void mappingnotify(XEvent *e);
180 static void maprequest(XEvent *e);
181 static void monocle(Monitor *m);
182 static void movemouse(const Arg *arg);
183 static Client *nexttiled(Monitor *m, Client *c);
184 static void propertynotify(XEvent *e);
185 static void quit(const Arg *arg);
186 static void resize(Client *c, int x, int y, int w, int h);
187 static void resizemouse(const Arg *arg);
188 static void restack(Monitor *m);
189 static void run(void);
190 static void scan(void);
191 static void setclientstate(Client *c, long state);
192 static void setlayout(const Arg *arg);
193 static void setmfact(const Arg *arg);
194 static void setup(void);
195 static void showhide(Client *c);
196 static void sigchld(int signal);
197 static void spawn(const Arg *arg);
198 static void tag(const Arg *arg);
199 static int textnw(const char *text, unsigned int len);
200 static void tile(Monitor *);
201 static void togglebar(const Arg *arg);
202 static void togglefloating(const Arg *arg);
203 static void toggletag(const Arg *arg);
204 static void toggleview(const Arg *arg);
205 static void unmanage(Client *c);
206 static void unmapnotify(XEvent *e);
207 static void updategeom(void);
208 static void updatenumlockmask(void);
209 static void updatesizehints(Client *c);
210 static void updatestatus(void);
211 static void updatetitle(Client *c);
212 static void updatewmhints(Client *c);
213 static void view(const Arg *arg);
214 static int xerror(Display *dpy, XErrorEvent *ee);
215 static int xerrordummy(Display *dpy, XErrorEvent *ee);
216 static int xerrorstart(Display *dpy, XErrorEvent *ee);
217 static void zoom(const Arg *arg);
218 #ifdef XINERAMA
219 static void focusmon(const Arg *arg);
220 static void tagmon(const Arg *arg);
221 #endif /* XINERAMA */
222
223 /* variables */
224 static char stext[256];
225 static int screen;
226 static int sx, sy, sw, sh; /* X display screen geometry x, y, width, height */
227 static int bh, blw = 0; /* bar geometry */
228 static int (*xerrorxlib)(Display *, XErrorEvent *);
229 static unsigned int numlockmask = 0;
230 static void (*handler[LASTEvent]) (XEvent *) = {
231 [ButtonPress] = buttonpress,
232 [ConfigureRequest] = configurerequest,
233 [ConfigureNotify] = configurenotify,
234 [DestroyNotify] = destroynotify,
235 [EnterNotify] = enternotify,
236 [Expose] = expose,
237 [FocusIn] = focusin,
238 [KeyPress] = keypress,
239 [MappingNotify] = mappingnotify,
240 [MapRequest] = maprequest,
241 [PropertyNotify] = propertynotify,
242 [UnmapNotify] = unmapnotify
243 };
244 static Atom wmatom[WMLast], netatom[NetLast];
245 static Bool otherwm;
246 static Bool running = True;
247 static Client *clients = NULL;
248 static Client *sel = NULL;
249 static Client *stack = NULL;
250 static Cursor cursor[CurLast];
251 static Display *dpy;
252 static DC dc;
253 static Layout *lt[] = { NULL, NULL };
254 static Monitor *mon = NULL, *selmon = NULL;
255 static unsigned int nmons = 0;
256 static Window root;
257 /* configuration, allows nested code to access above variables */
258 #include "config.h"
259
260 /* compile-time check if all tags fit into an unsigned int bit array. */
261 struct NumTags { char limitexceeded[sizeof(unsigned int) * 8 < LENGTH(tags) ? -1 : 1]; };
262
263 /* function implementations */
264 void
265 applyrules(Client *c) {
266 unsigned int i;
267 Rule *r;
268 XClassHint ch = { 0 };
269
270 /* rule matching */
271 c->isfloating = c->tags = 0;
272 if(XGetClassHint(dpy, c->win, &ch)) {
273 for(i = 0; i < LENGTH(rules); i++) {
274 r = &rules[i];
275 if((!r->title || strstr(c->name, r->title))
276 && (!r->class || (ch.res_class && strstr(ch.res_class, r->class)))
277 && (!r->instance || (ch.res_name && strstr(ch.res_name, r->instance)))) {
278 c->isfloating = r->isfloating;
279 c->tags |= r->tags;
280 }
281 }
282 if(ch.res_class)
283 XFree(ch.res_class);
284 if(ch.res_name)
285 XFree(ch.res_name);
286 }
287 c->tags = c->tags & TAGMASK ? c->tags & TAGMASK : tagset[mon[c->mon].seltags];
288 }
289
290 Bool
291 applysizehints(Client *c, int *x, int *y, int *w, int *h) {
292 Bool baseismin;
293
294 /* set minimum possible */
295 *w = MAX(1, *w);
296 *h = MAX(1, *h);
297
298 if(*x > sx + sw)
299 *x = sw - WIDTH(c);
300 if(*y > sy + sh)
301 *y = sh - HEIGHT(c);
302 if(*x + *w + 2 * c->bw < sx)
303 *x = sx;
304 if(*y + *h + 2 * c->bw < sy)
305 *y = sy;
306 if(*h < bh)
307 *h = bh;
308 if(*w < bh)
309 *w = bh;
310
311 if(resizehints || c->isfloating) {
312 /* see last two sentences in ICCCM 4.1.2.3 */
313 baseismin = c->basew == c->minw && c->baseh == c->minh;
314
315 if(!baseismin) { /* temporarily remove base dimensions */
316 *w -= c->basew;
317 *h -= c->baseh;
318 }
319
320 /* adjust for aspect limits */
321 if(c->mina > 0 && c->maxa > 0) {
322 if(c->maxa < (float)*w / *h)
323 *w = *h * c->maxa;
324 else if(c->mina < (float)*h / *w)
325 *h = *w * c->mina;
326 }
327
328 if(baseismin) { /* increment calculation requires this */
329 *w -= c->basew;
330 *h -= c->baseh;
331 }
332
333 /* adjust for increment value */
334 if(c->incw)
335 *w -= *w % c->incw;
336 if(c->inch)
337 *h -= *h % c->inch;
338
339 /* restore base dimensions */
340 *w += c->basew;
341 *h += c->baseh;
342
343 *w = MAX(*w, c->minw);
344 *h = MAX(*h, c->minh);
345
346 if(c->maxw)
347 *w = MIN(*w, c->maxw);
348
349 if(c->maxh)
350 *h = MIN(*h, c->maxh);
351 }
352 return *x != c->x || *y != c->y || *w != c->w || *h != c->h;
353 }
354
355 void
356 arrange(void) {
357 unsigned int i;
358 showhide(stack);
359 focus(NULL);
360 for(i = 0; i < nmons; i++) {
361 if(lt[mon[i].sellt]->arrange)
362 lt[mon[i].sellt]->arrange(&mon[i]);
363 restack(&mon[i]);
364 }
365 }
366
367 void
368 attach(Client *c) {
369 c->next = clients;
370 clients = c;
371 }
372
373 void
374 attachstack(Client *c) {
375 c->snext = stack;
376 stack = c;
377 }
378
379 void
380 buttonpress(XEvent *e) {
381 unsigned int i, x, click;
382 Arg arg = {0};
383 Client *c;
384 XButtonPressedEvent *ev = &e->xbutton;
385
386 click = ClkRootWin;
387 if(ev->window == selmon->barwin) {
388 i = 0;
389 x = selmon->btx;
390 do
391 x += TEXTW(tags[i]);
392 while(ev->x >= x && ++i < LENGTH(tags));
393 if(i < LENGTH(tags)) {
394 click = ClkTagBar;
395 arg.ui = 1 << i;
396 }
397 else if(ev->x < x + blw)
398 click = ClkLtSymbol;
399 else if(ev->x > selmon->wx + selmon->ww - TEXTW(stext))
400 click = ClkStatusText;
401 else
402 click = ClkWinTitle;
403 }
404 else if((c = getclient(ev->window))) {
405 focus(c);
406 click = ClkClientWin;
407 }
408
409 for(i = 0; i < LENGTH(buttons); i++)
410 if(click == buttons[i].click && buttons[i].func && buttons[i].button == ev->button
411 && CLEANMASK(buttons[i].mask) == CLEANMASK(ev->state))
412 buttons[i].func(click == ClkTagBar && buttons[i].arg.i == 0 ? &arg : &buttons[i].arg);
413 }
414
415 void
416 checkotherwm(void) {
417 otherwm = False;
418 xerrorxlib = XSetErrorHandler(xerrorstart);
419
420 /* this causes an error if some other window manager is running */
421 XSelectInput(dpy, DefaultRootWindow(dpy), SubstructureRedirectMask);
422 XSync(dpy, False);
423 if(otherwm)
424 die("dwm: another window manager is already running\n");
425 XSetErrorHandler(xerror);
426 XSync(dpy, False);
427 }
428
429 void
430 cleanup(void) {
431 unsigned int i;
432 Arg a = {.ui = ~0};
433 Layout foo = { "", NULL };
434
435 view(&a);
436 lt[selmon->sellt] = &foo;
437 while(stack)
438 unmanage(stack);
439 if(dc.font.set)
440 XFreeFontSet(dpy, dc.font.set);
441 else
442 XFreeFont(dpy, dc.font.xfont);
443 XUngrabKey(dpy, AnyKey, AnyModifier, root);
444 XFreePixmap(dpy, dc.drawable);
445 XFreeGC(dpy, dc.gc);
446 XFreeCursor(dpy, cursor[CurNormal]);
447 XFreeCursor(dpy, cursor[CurResize]);
448 XFreeCursor(dpy, cursor[CurMove]);
449 for(i = 0; i < nmons; i++)
450 XDestroyWindow(dpy, mon[i].barwin);
451 free(mon);
452 XSync(dpy, False);
453 XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime);
454 }
455
456 void
457 clearurgent(Client *c) {
458 XWMHints *wmh;
459
460 c->isurgent = False;
461 if(!(wmh = XGetWMHints(dpy, c->win)))
462 return;
463 wmh->flags &= ~XUrgencyHint;
464 XSetWMHints(dpy, c->win, wmh);
465 XFree(wmh);
466 }
467
468 void
469 configure(Client *c) {
470 XConfigureEvent ce;
471
472 ce.type = ConfigureNotify;
473 ce.display = dpy;
474 ce.event = c->win;
475 ce.window = c->win;
476 ce.x = c->x;
477 ce.y = c->y;
478 ce.width = c->w;
479 ce.height = c->h;
480 ce.border_width = c->bw;
481 ce.above = None;
482 ce.override_redirect = False;
483 XSendEvent(dpy, c->win, False, StructureNotifyMask, (XEvent *)&ce);
484 }
485
486 void
487 configurenotify(XEvent *e) {
488 unsigned int i;
489 XConfigureEvent *ev = &e->xconfigure;
490
491 if(ev->window == root && (ev->width != sw || ev->height != sh)) {
492 sw = ev->width;
493 sh = ev->height;
494 updategeom();
495 if(dc.drawable != 0)
496 XFreePixmap(dpy, dc.drawable);
497 dc.drawable = XCreatePixmap(dpy, root, sw, bh, DefaultDepth(dpy, screen));
498 for(i = 0; i < nmons; i++)
499 XMoveResizeWindow(dpy, mon[i].barwin, mon[i].wx, mon[i].by, mon[i].ww, bh);
500 arrange();
501 }
502 }
503
504 void
505 configurerequest(XEvent *e) {
506 Client *c;
507 XConfigureRequestEvent *ev = &e->xconfigurerequest;
508 XWindowChanges wc;
509
510 if((c = getclient(ev->window))) {
511 if(ev->value_mask & CWBorderWidth)
512 c->bw = ev->border_width;
513 else if(c->isfloating || !lt[selmon->sellt]->arrange) {
514 if(ev->value_mask & CWX)
515 c->x = sx + ev->x;
516 if(ev->value_mask & CWY)
517 c->y = sy + ev->y;
518 if(ev->value_mask & CWWidth)
519 c->w = ev->width;
520 if(ev->value_mask & CWHeight)
521 c->h = ev->height;
522 if((c->x - sx + c->w) > sw && c->isfloating)
523 c->x = sx + (sw / 2 - c->w / 2); /* center in x direction */
524 if((c->y - sy + c->h) > sh && c->isfloating)
525 c->y = sy + (sh / 2 - c->h / 2); /* center in y direction */
526 if((ev->value_mask & (CWX|CWY)) && !(ev->value_mask & (CWWidth|CWHeight)))
527 configure(c);
528 if(ISVISIBLE((&mon[c->mon]), c))
529 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h);
530 }
531 else
532 configure(c);
533 }
534 else {
535 wc.x = ev->x;
536 wc.y = ev->y;
537 wc.width = ev->width;
538 wc.height = ev->height;
539 wc.border_width = ev->border_width;
540 wc.sibling = ev->above;
541 wc.stack_mode = ev->detail;
542 XConfigureWindow(dpy, ev->window, ev->value_mask, &wc);
543 }
544 XSync(dpy, False);
545 }
546
547 void
548 destroynotify(XEvent *e) {
549 Client *c;
550 XDestroyWindowEvent *ev = &e->xdestroywindow;
551
552 if((c = getclient(ev->window)))
553 unmanage(c);
554 }
555
556 void
557 detach(Client *c) {
558 Client **tc;
559
560 for(tc = &clients; *tc && *tc != c; tc = &(*tc)->next);
561 *tc = c->next;
562 }
563
564 void
565 detachstack(Client *c) {
566 Client **tc;
567
568 for(tc = &stack; *tc && *tc != c; tc = &(*tc)->snext);
569 *tc = c->snext;
570 }
571
572 void
573 die(const char *errstr, ...) {
574 va_list ap;
575
576 va_start(ap, errstr);
577 vfprintf(stderr, errstr, ap);
578 va_end(ap);
579 exit(EXIT_FAILURE);
580 }
581
582 void
583 drawbar(Monitor *m) {
584 int x;
585 unsigned int i, occ = 0, urg = 0;
586 unsigned long *col;
587 Client *c;
588
589 for(c = clients; c; c = c->next) {
590 if(m == &mon[c->mon]) {
591 occ |= c->tags;
592 if(c->isurgent)
593 urg |= c->tags;
594 }
595 }
596
597 dc.x = 0;
598 #ifdef XINERAMA
599 {
600 dc.w = TEXTW(m->symbol);
601 drawtext(m->symbol, selmon == m ? dc.sel : dc.norm, False);
602 dc.x += dc.w;
603 }
604 #endif /* XINERAMA */
605 m->btx = dc.x;
606 for(i = 0; i < LENGTH(tags); i++) {
607 dc.w = TEXTW(tags[i]);
608 col = tagset[m->seltags] & 1 << i ? dc.sel : dc.norm;
609 drawtext(tags[i], col, urg & 1 << i);
610 drawsquare(m == selmon && sel && sel->tags & 1 << i,
611 occ & 1 << i, urg & 1 << i, col);
612 dc.x += dc.w;
613 }
614 if(blw > 0) {
615 dc.w = blw;
616 drawtext(lt[m->sellt]->symbol, dc.norm, False);
617 x = dc.x + dc.w;
618 }
619 else
620 x = dc.x;
621 if(m == selmon) {
622 dc.w = TEXTW(stext);
623 dc.x = m->ww - dc.w;
624 if(dc.x < x) {
625 dc.x = x;
626 dc.w = m->ww - x;
627 }
628 drawtext(stext, dc.norm, False);
629 if((dc.w = dc.x - x) > bh) {
630 dc.x = x;
631 if(sel) {
632 drawtext(sel->name, dc.sel, False);
633 drawsquare(sel->isfixed, sel->isfloating, False, dc.sel);
634 }
635 else
636 drawtext(NULL, dc.norm, False);
637 }
638 }
639 else {
640 dc.x = x;
641 dc.w = m->ww - x;
642 drawtext(NULL, dc.norm, False);
643 }
644 XCopyArea(dpy, dc.drawable, m->barwin, dc.gc, 0, 0, m->ww, bh, 0, 0);
645 XSync(dpy, False);
646 }
647
648 void
649 drawbars() {
650 unsigned int i;
651
652 for(i = 0; i < nmons; i++)
653 drawbar(&mon[i]);
654 }
655
656 void
657 drawsquare(Bool filled, Bool empty, Bool invert, unsigned long col[ColLast]) {
658 int x;
659 XGCValues gcv;
660 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
661
662 gcv.foreground = col[invert ? ColBG : ColFG];
663 XChangeGC(dpy, dc.gc, GCForeground, &gcv);
664 x = (dc.font.ascent + dc.font.descent + 2) / 4;
665 r.x = dc.x + 1;
666 r.y = dc.y + 1;
667 if(filled) {
668 r.width = r.height = x + 1;
669 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
670 }
671 else if(empty) {
672 r.width = r.height = x;
673 XDrawRectangles(dpy, dc.drawable, dc.gc, &r, 1);
674 }
675 }
676
677 void
678 drawtext(const char *text, unsigned long col[ColLast], Bool invert) {
679 char buf[256];
680 int i, x, y, h, len, olen;
681 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
682
683 XSetForeground(dpy, dc.gc, col[invert ? ColFG : ColBG]);
684 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
685 if(!text)
686 return;
687 olen = strlen(text);
688 h = dc.font.ascent + dc.font.descent;
689 y = dc.y + (dc.h / 2) - (h / 2) + dc.font.ascent;
690 x = dc.x + (h / 2);
691 /* shorten text if necessary */
692 for(len = MIN(olen, sizeof buf); len && textnw(text, len) > dc.w - h; len--);
693 if(!len)
694 return;
695 memcpy(buf, text, len);
696 if(len < olen)
697 for(i = len; i && i > len - 3; buf[--i] = '.');
698 XSetForeground(dpy, dc.gc, col[invert ? ColBG : ColFG]);
699 if(dc.font.set)
700 XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
701 else
702 XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
703 }
704
705 void
706 enternotify(XEvent *e) {
707 Client *c;
708 XCrossingEvent *ev = &e->xcrossing;
709
710 if((ev->mode != NotifyNormal || ev->detail == NotifyInferior) && ev->window != root)
711 return;
712 if((c = getclient(ev->window)))
713 focus(c);
714 else
715 focus(NULL);
716 }
717
718 void
719 expose(XEvent *e) {
720 unsigned int i;
721 XExposeEvent *ev = &e->xexpose;
722
723 if(ev->count == 0)
724 for(i = 0; i < nmons; i++)
725 if(ev->window == mon[i].barwin) {
726 drawbar(&mon[i]);
727 break;
728 }
729 }
730
731 void
732 focus(Client *c) {
733 if(!c || !ISVISIBLE((&mon[c->mon]), c))
734 for(c = stack; c && !ISVISIBLE(selmon, c); c = c->snext);
735 if(sel && sel != c) {
736 grabbuttons(sel, False);
737 XSetWindowBorder(dpy, sel->win, dc.norm[ColBorder]);
738 }
739 if(c) {
740 if(c->isurgent)
741 clearurgent(c);
742 detachstack(c);
743 attachstack(c);
744 grabbuttons(c, True);
745 XSetWindowBorder(dpy, c->win, dc.sel[ColBorder]);
746 XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
747 }
748 else
749 XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
750 sel = c;
751 if(c)
752 selmon = &mon[c->mon];
753 drawbars();
754 }
755
756 void
757 focusin(XEvent *e) { /* there are some broken focus acquiring clients */
758 XFocusChangeEvent *ev = &e->xfocus;
759
760 if(sel && ev->window != sel->win)
761 XSetInputFocus(dpy, sel->win, RevertToPointerRoot, CurrentTime);
762 }
763
764 #ifdef XINERAMA
765 void
766 focusmon(const Arg *arg) {
767 if(arg->ui >= nmons)
768 return;
769 selmon = &mon[arg->ui];
770 focus(NULL);
771 drawbars();
772 }
773 #endif /* XINERAMA */
774
775 void
776 focusstack(const Arg *arg) {
777 Client *c = NULL, *i;
778
779 if(!sel)
780 return;
781 if(arg->i > 0) {
782 for(c = sel->next; c && !ISVISIBLE(selmon, c); c = c->next);
783 if(!c)
784 for(c = clients; c && !ISVISIBLE(selmon, c); c = c->next);
785 }
786 else {
787 for(i = clients; i != sel; i = i->next)
788 if(ISVISIBLE(selmon, i))
789 c = i;
790 if(!c)
791 for(; i; i = i->next)
792 if(ISVISIBLE(selmon, i))
793 c = i;
794 }
795 if(c) {
796 focus(c);
797 restack(selmon);
798 }
799 }
800
801 Client *
802 getclient(Window w) {
803 Client *c;
804
805 for(c = clients; c && c->win != w; c = c->next);
806 return c;
807 }
808
809 unsigned long
810 getcolor(const char *colstr) {
811 Colormap cmap = DefaultColormap(dpy, screen);
812 XColor color;
813
814 if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
815 die("error, cannot allocate color '%s'\n", colstr);
816 return color.pixel;
817 }
818
819 long
820 getstate(Window w) {
821 int format, status;
822 long result = -1;
823 unsigned char *p = NULL;
824 unsigned long n, extra;
825 Atom real;
826
827 status = XGetWindowProperty(dpy, w, wmatom[WMState], 0L, 2L, False, wmatom[WMState],
828 &real, &format, &n, &extra, (unsigned char **)&p);
829 if(status != Success)
830 return -1;
831 if(n != 0)
832 result = *p;
833 XFree(p);
834 return result;
835 }
836
837 Bool
838 gettextprop(Window w, Atom atom, char *text, unsigned int size) {
839 char **list = NULL;
840 int n;
841 XTextProperty name;
842
843 if(!text || size == 0)
844 return False;
845 text[0] = '\0';
846 XGetTextProperty(dpy, w, &name, atom);
847 if(!name.nitems)
848 return False;
849 if(name.encoding == XA_STRING)
850 strncpy(text, (char *)name.value, size - 1);
851 else {
852 if(XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success
853 && n > 0 && *list) {
854 strncpy(text, *list, size - 1);
855 XFreeStringList(list);
856 }
857 }
858 text[size - 1] = '\0';
859 XFree(name.value);
860 return True;
861 }
862
863 void
864 grabbuttons(Client *c, Bool focused) {
865 updatenumlockmask();
866 {
867 unsigned int i, j;
868 unsigned int modifiers[] = { 0, LockMask, numlockmask, numlockmask|LockMask };
869 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
870 if(focused) {
871 for(i = 0; i < LENGTH(buttons); i++)
872 if(buttons[i].click == ClkClientWin)
873 for(j = 0; j < LENGTH(modifiers); j++)
874 XGrabButton(dpy, buttons[i].button,
875 buttons[i].mask | modifiers[j],
876 c->win, False, BUTTONMASK,
877 GrabModeAsync, GrabModeSync, None, None);
878 } else
879 XGrabButton(dpy, AnyButton, AnyModifier, c->win, False,
880 BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
881 }
882 }
883
884 void
885 grabkeys(void) {
886 updatenumlockmask();
887 { /* grab keys */
888 unsigned int i, j;
889 unsigned int modifiers[] = { 0, LockMask, numlockmask, numlockmask|LockMask };
890 KeyCode code;
891
892 XUngrabKey(dpy, AnyKey, AnyModifier, root);
893 for(i = 0; i < LENGTH(keys); i++) {
894 if((code = XKeysymToKeycode(dpy, keys[i].keysym)))
895 for(j = 0; j < LENGTH(modifiers); j++)
896 XGrabKey(dpy, code, keys[i].mod | modifiers[j], root,
897 True, GrabModeAsync, GrabModeAsync);
898 }
899 }
900 }
901
902 void
903 initfont(const char *fontstr) {
904 char *def, **missing;
905 int i, n;
906
907 missing = NULL;
908 dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
909 if(missing) {
910 while(n--)
911 fprintf(stderr, "dwm: missing fontset: %s\n", missing[n]);
912 XFreeStringList(missing);
913 }
914 if(dc.font.set) {
915 XFontSetExtents *font_extents;
916 XFontStruct **xfonts;
917 char **font_names;
918 dc.font.ascent = dc.font.descent = 0;
919 font_extents = XExtentsOfFontSet(dc.font.set);
920 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
921 for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
922 dc.font.ascent = MAX(dc.font.ascent, (*xfonts)->ascent);
923 dc.font.descent = MAX(dc.font.descent,(*xfonts)->descent);
924 xfonts++;
925 }
926 }
927 else {
928 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr))
929 && !(dc.font.xfont = XLoadQueryFont(dpy, "fixed")))
930 die("error, cannot load font: '%s'\n", fontstr);
931 dc.font.ascent = dc.font.xfont->ascent;
932 dc.font.descent = dc.font.xfont->descent;
933 }
934 dc.font.height = dc.font.ascent + dc.font.descent;
935 }
936
937 Bool
938 isprotodel(Client *c) {
939 int i, n;
940 Atom *protocols;
941 Bool ret = False;
942
943 if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
944 for(i = 0; !ret && i < n; i++)
945 if(protocols[i] == wmatom[WMDelete])
946 ret = True;
947 XFree(protocols);
948 }
949 return ret;
950 }
951
952 void
953 keypress(XEvent *e) {
954 unsigned int i;
955 KeySym keysym;
956 XKeyEvent *ev;
957
958 ev = &e->xkey;
959 keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
960 for(i = 0; i < LENGTH(keys); i++)
961 if(keysym == keys[i].keysym
962 && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state)
963 && keys[i].func)
964 keys[i].func(&(keys[i].arg));
965 }
966
967 void
968 killclient(const Arg *arg) {
969 XEvent ev;
970
971 if(!sel)
972 return;
973 if(isprotodel(sel)) {
974 ev.type = ClientMessage;
975 ev.xclient.window = sel->win;
976 ev.xclient.message_type = wmatom[WMProtocols];
977 ev.xclient.format = 32;
978 ev.xclient.data.l[0] = wmatom[WMDelete];
979 ev.xclient.data.l[1] = CurrentTime;
980 XSendEvent(dpy, sel->win, False, NoEventMask, &ev);
981 }
982 else
983 XKillClient(dpy, sel->win);
984 }
985
986 void
987 manage(Window w, XWindowAttributes *wa) {
988 static Client cz;
989 Client *c, *t = NULL;
990 Window trans = None;
991 XWindowChanges wc;
992
993 if(!(c = malloc(sizeof(Client))))
994 die("fatal: could not malloc() %u bytes\n", sizeof(Client));
995 *c = cz;
996 c->win = w;
997 for(c->mon = 0; selmon != &mon[c->mon]; c->mon++);
998
999 /* geometry */
1000 c->x = wa->x;
1001 c->y = wa->y;
1002 c->w = wa->width;
1003 c->h = wa->height;
1004 c->oldbw = wa->border_width;
1005 if(c->w == sw && c->h == sh) {
1006 c->x = sx;
1007 c->y = sy;
1008 c->bw = 0;
1009 }
1010 else {
1011 if(c->x + WIDTH(c) > sx + sw)
1012 c->x = sx + sw - WIDTH(c);
1013 if(c->y + HEIGHT(c) > sy + sh)
1014 c->y = sy + sh - HEIGHT(c);
1015 c->x = MAX(c->x, sx);
1016 /* only fix client y-offset, if the client center might cover the bar */
1017 c->y = MAX(c->y, ((selmon->by == 0) && (c->x + (c->w / 2) >= selmon->wx)
1018 && (c->x + (c->w / 2) < selmon->wx + selmon->ww)) ? bh : sy);
1019 c->bw = borderpx;
1020 }
1021
1022 wc.border_width = c->bw;
1023 XConfigureWindow(dpy, w, CWBorderWidth, &wc);
1024 XSetWindowBorder(dpy, w, dc.norm[ColBorder]);
1025 configure(c); /* propagates border_width, if size doesn't change */
1026 updatesizehints(c);
1027 XSelectInput(dpy, w, EnterWindowMask|FocusChangeMask|PropertyChangeMask|StructureNotifyMask);
1028 grabbuttons(c, False);
1029 updatetitle(c);
1030 if(XGetTransientForHint(dpy, w, &trans))
1031 t = getclient(trans);
1032 if(t)
1033 c->tags = t->tags;
1034 else
1035 applyrules(c);
1036 if(!c->isfloating)
1037 c->isfloating = trans != None || c->isfixed;
1038 if(c->isfloating)
1039 XRaiseWindow(dpy, c->win);
1040 attach(c);
1041 attachstack(c);
1042 XMoveResizeWindow(dpy, c->win, c->x + 2 * sw, c->y, c->w, c->h); /* some windows require this */
1043 XMapWindow(dpy, c->win);
1044 setclientstate(c, NormalState);
1045 arrange();
1046 }
1047
1048 void
1049 mappingnotify(XEvent *e) {
1050 XMappingEvent *ev = &e->xmapping;
1051
1052 XRefreshKeyboardMapping(ev);
1053 if(ev->request == MappingKeyboard)
1054 grabkeys();
1055 }
1056
1057 void
1058 maprequest(XEvent *e) {
1059 static XWindowAttributes wa;
1060 XMapRequestEvent *ev = &e->xmaprequest;
1061
1062 if(!XGetWindowAttributes(dpy, ev->window, &wa))
1063 return;
1064 if(wa.override_redirect)
1065 return;
1066 if(!getclient(ev->window))
1067 manage(ev->window, &wa);
1068 }
1069
1070 void
1071 monocle(Monitor *m) {
1072 Client *c;
1073
1074 for(c = nexttiled(m, clients); c; c = nexttiled(m, c->next))
1075 resize(c, m->wx, m->wy, m->ww - 2 * c->bw, m->wh - 2 * c->bw);
1076 }
1077
1078 void
1079 movemouse(const Arg *arg) {
1080 int x, y, ocx, ocy, di, nx, ny;
1081 unsigned int dui;
1082 Client *c;
1083 Window dummy;
1084 XEvent ev;
1085
1086 if(!(c = sel))
1087 return;
1088 restack(selmon);
1089 ocx = c->x;
1090 ocy = c->y;
1091 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1092 None, cursor[CurMove], CurrentTime) != GrabSuccess)
1093 return;
1094 XQueryPointer(dpy, root, &dummy, &dummy, &x, &y, &di, &di, &dui);
1095 do {
1096 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
1097 switch (ev.type) {
1098 case ConfigureRequest:
1099 case Expose:
1100 case MapRequest:
1101 handler[ev.type](&ev);
1102 break;
1103 case MotionNotify:
1104 nx = ocx + (ev.xmotion.x - x);
1105 ny = ocy + (ev.xmotion.y - y);
1106 if(snap && nx >= selmon->wx && nx <= selmon->wx + selmon->ww
1107 && ny >= selmon->wy && ny <= selmon->wy + selmon->wh) {
1108 if(abs(selmon->wx - nx) < snap)
1109 nx = selmon->wx;
1110 else if(abs((selmon->wx + selmon->ww) - (nx + WIDTH(c))) < snap)
1111 nx = selmon->wx + selmon->ww - WIDTH(c);
1112 if(abs(selmon->wy - ny) < snap)
1113 ny = selmon->wy;
1114 else if(abs((selmon->wy + selmon->wh) - (ny + HEIGHT(c))) < snap)
1115 ny = selmon->wy + selmon->wh - HEIGHT(c);
1116 if(!c->isfloating && lt[selmon->sellt]->arrange
1117 && (abs(nx - c->x) > snap || abs(ny - c->y) > snap))
1118 togglefloating(NULL);
1119 }
1120 if(!lt[selmon->sellt]->arrange || c->isfloating)
1121 resize(c, nx, ny, c->w, c->h);
1122 break;
1123 }
1124 }
1125 while(ev.type != ButtonRelease);
1126 XUngrabPointer(dpy, CurrentTime);
1127 }
1128
1129 Client *
1130 nexttiled(Monitor *m, Client *c) {
1131 // TODO: m handling
1132 for(; c && (c->isfloating || !ISVISIBLE(m, c)); c = c->next);
1133 return c;
1134 }
1135
1136 void
1137 propertynotify(XEvent *e) {
1138 Client *c;
1139 Window trans;
1140 XPropertyEvent *ev = &e->xproperty;
1141
1142 if((ev->window == root) && (ev->atom == XA_WM_NAME))
1143 updatestatus();
1144 else if(ev->state == PropertyDelete)
1145 return; /* ignore */
1146 else if((c = getclient(ev->window))) {
1147 switch (ev->atom) {
1148 default: break;
1149 case XA_WM_TRANSIENT_FOR:
1150 XGetTransientForHint(dpy, c->win, &trans);
1151 if(!c->isfloating && (c->isfloating = (getclient(trans) != NULL)))
1152 arrange();
1153 break;
1154 case XA_WM_NORMAL_HINTS:
1155 updatesizehints(c);
1156 break;
1157 case XA_WM_HINTS:
1158 updatewmhints(c);
1159 drawbars();
1160 break;
1161 }
1162 if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
1163 updatetitle(c);
1164 if(c == sel)
1165 drawbars();
1166 }
1167 }
1168 }
1169
1170 void
1171 quit(const Arg *arg) {
1172 running = False;
1173 }
1174
1175 void
1176 resize(Client *c, int x, int y, int w, int h) {
1177 XWindowChanges wc;
1178
1179 if(applysizehints(c, &x, &y, &w, &h)) {
1180 c->x = wc.x = x;
1181 c->y = wc.y = y;
1182 c->w = wc.width = w;
1183 c->h = wc.height = h;
1184 wc.border_width = c->bw;
1185 XConfigureWindow(dpy, c->win,
1186 CWX|CWY|CWWidth|CWHeight|CWBorderWidth, &wc);
1187 configure(c);
1188 XSync(dpy, False);
1189 }
1190 }
1191
1192 void
1193 resizemouse(const Arg *arg) {
1194 int ocx, ocy;
1195 int nw, nh;
1196 Client *c;
1197 XEvent ev;
1198
1199 if(!(c = sel))
1200 return;
1201 restack(selmon);
1202 ocx = c->x;
1203 ocy = c->y;
1204 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1205 None, cursor[CurResize], CurrentTime) != GrabSuccess)
1206 return;
1207 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->bw - 1, c->h + c->bw - 1);
1208 do {
1209 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
1210 switch(ev.type) {
1211 case ConfigureRequest:
1212 case Expose:
1213 case MapRequest:
1214 handler[ev.type](&ev);
1215 break;
1216 case MotionNotify:
1217 nw = MAX(ev.xmotion.x - ocx - 2 * c->bw + 1, 1);
1218 nh = MAX(ev.xmotion.y - ocy - 2 * c->bw + 1, 1);
1219
1220 if(snap && nw >= selmon->wx && nw <= selmon->wx + selmon->ww
1221 && nh >= selmon->wy && nh <= selmon->wy + selmon->wh) {
1222 if(!c->isfloating && lt[selmon->sellt]->arrange
1223 && (abs(nw - c->w) > snap || abs(nh - c->h) > snap))
1224 togglefloating(NULL);
1225 }
1226 if(!lt[selmon->sellt]->arrange || c->isfloating)
1227 resize(c, c->x, c->y, nw, nh);
1228 break;
1229 }
1230 }
1231 while(ev.type != ButtonRelease);
1232 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->bw - 1, c->h + c->bw - 1);
1233 XUngrabPointer(dpy, CurrentTime);
1234 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1235 }
1236
1237 void
1238 restack(Monitor *m) {
1239 Client *c;
1240 XEvent ev;
1241 XWindowChanges wc;
1242
1243 drawbars();
1244 if(!sel)
1245 return;
1246 if(m == selmon && (sel->isfloating || !lt[m->sellt]->arrange))
1247 XRaiseWindow(dpy, sel->win);
1248 if(lt[m->sellt]->arrange) {
1249 wc.stack_mode = Below;
1250 wc.sibling = m->barwin;
1251 for(c = stack; c; c = c->snext)
1252 if(!c->isfloating && ISVISIBLE(m, c)) {
1253 XConfigureWindow(dpy, c->win, CWSibling|CWStackMode, &wc);
1254 wc.sibling = c->win;
1255 }
1256 }
1257 XSync(dpy, False);
1258 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1259 }
1260
1261 void
1262 run(void) {
1263 XEvent ev;
1264
1265 /* main event loop */
1266 XSync(dpy, False);
1267 while(running && !XNextEvent(dpy, &ev)) {
1268 if(handler[ev.type])
1269 (handler[ev.type])(&ev); /* call handler */
1270 }
1271 }
1272
1273 void
1274 scan(void) {
1275 unsigned int i, num;
1276 Window d1, d2, *wins = NULL;
1277 XWindowAttributes wa;
1278
1279 if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1280 for(i = 0; i < num; i++) {
1281 if(!XGetWindowAttributes(dpy, wins[i], &wa)
1282 || wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1283 continue;
1284 if(wa.map_state == IsViewable || getstate(wins[i]) == IconicState)
1285 manage(wins[i], &wa);
1286 }
1287 for(i = 0; i < num; i++) { /* now the transients */
1288 if(!XGetWindowAttributes(dpy, wins[i], &wa))
1289 continue;
1290 if(XGetTransientForHint(dpy, wins[i], &d1)
1291 && (wa.map_state == IsViewable || getstate(wins[i]) == IconicState))
1292 manage(wins[i], &wa);
1293 }
1294 if(wins)
1295 XFree(wins);
1296 }
1297 }
1298
1299 void
1300 setclientstate(Client *c, long state) {
1301 long data[] = {state, None};
1302
1303 XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1304 PropModeReplace, (unsigned char *)data, 2);
1305 }
1306
1307 void
1308 setlayout(const Arg *arg) {
1309 if(!arg || !arg->v || arg->v != lt[selmon->sellt])
1310 selmon->sellt ^= 1;
1311 if(arg && arg->v)
1312 lt[selmon->sellt] = (Layout *)arg->v;
1313 if(sel)
1314 arrange();
1315 else
1316 drawbars();
1317 }
1318
1319 /* arg > 1.0 will set mfact absolutly */
1320 void
1321 setmfact(const Arg *arg) {
1322 float f;
1323
1324 if(!arg || !lt[selmon->sellt]->arrange)
1325 return;
1326 f = arg->f < 1.0 ? arg->f + selmon->mfact : arg->f - 1.0;
1327 if(f < 0.1 || f > 0.9)
1328 return;
1329 selmon->mfact = f;
1330 arrange();
1331 }
1332
1333 void
1334 setup(void) {
1335 unsigned int i;
1336 int w;
1337 XSetWindowAttributes wa;
1338
1339 /* init screen */
1340 screen = DefaultScreen(dpy);
1341 root = RootWindow(dpy, screen);
1342 initfont(font);
1343 sx = 0;
1344 sy = 0;
1345 sw = DisplayWidth(dpy, screen);
1346 sh = DisplayHeight(dpy, screen);
1347 bh = dc.h = dc.font.height + 2;
1348 lt[0] = &layouts[0];
1349 lt[1] = &layouts[1 % LENGTH(layouts)];
1350 updategeom();
1351
1352 /* init atoms */
1353 wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1354 wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1355 wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1356 netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1357 netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1358
1359 /* init cursors */
1360 wa.cursor = cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1361 cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1362 cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1363
1364 /* init appearance */
1365 dc.norm[ColBorder] = getcolor(normbordercolor);
1366 dc.norm[ColBG] = getcolor(normbgcolor);
1367 dc.norm[ColFG] = getcolor(normfgcolor);
1368 dc.sel[ColBorder] = getcolor(selbordercolor);
1369 dc.sel[ColBG] = getcolor(selbgcolor);
1370 dc.sel[ColFG] = getcolor(selfgcolor);
1371 dc.drawable = XCreatePixmap(dpy, root, DisplayWidth(dpy, screen), bh, DefaultDepth(dpy, screen));
1372 dc.gc = XCreateGC(dpy, root, 0, NULL);
1373 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
1374 if(!dc.font.set)
1375 XSetFont(dpy, dc.gc, dc.font.xfont->fid);
1376
1377 /* init bars */
1378 wa.override_redirect = True;
1379 wa.background_pixmap = ParentRelative;
1380 wa.event_mask = ButtonPressMask|ExposureMask;
1381 for(blw = i = 0; LENGTH(layouts) > 1 && i < LENGTH(layouts); i++) {
1382 w = TEXTW(layouts[i].symbol);
1383 blw = MAX(blw, w);
1384 }
1385
1386 for(i = 0; i < nmons; i++) {
1387 mon[i].barwin = XCreateWindow(dpy, root, mon[i].wx, mon[i].by, mon[i].ww, bh, 0, DefaultDepth(dpy, screen),
1388
1389 CopyFromParent, DefaultVisual(dpy, screen),
1390 CWOverrideRedirect|CWBackPixmap|CWEventMask, &wa);
1391 XDefineCursor(dpy, mon[i].barwin, cursor[CurNormal]);
1392 XMapRaised(dpy, mon[i].barwin);
1393 }
1394 updatestatus();
1395
1396 /* EWMH support per view */
1397 XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1398 PropModeReplace, (unsigned char *) netatom, NetLast);
1399
1400 /* select for events */
1401 wa.event_mask = SubstructureRedirectMask|SubstructureNotifyMask|ButtonPressMask
1402 |EnterWindowMask|LeaveWindowMask|StructureNotifyMask
1403 |PropertyChangeMask;
1404 XChangeWindowAttributes(dpy, root, CWEventMask|CWCursor, &wa);
1405 XSelectInput(dpy, root, wa.event_mask);
1406
1407 grabkeys();
1408 }
1409
1410 void
1411 showhide(Client *c) {
1412 if(!c)
1413 return;
1414 if(ISVISIBLE((&mon[c->mon]), c)) { /* show clients top down */
1415 XMoveWindow(dpy, c->win, c->x, c->y);
1416 if(!lt[selmon->sellt]->arrange || c->isfloating)
1417 resize(c, c->x, c->y, c->w, c->h);
1418 showhide(c->snext);
1419 }
1420 else { /* hide clients bottom up */
1421 showhide(c->snext);
1422 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
1423 }
1424 }
1425
1426
1427 void
1428 sigchld(int signal) {
1429 while(0 < waitpid(-1, NULL, WNOHANG));
1430 }
1431
1432 void
1433 spawn(const Arg *arg) {
1434 signal(SIGCHLD, sigchld);
1435 if(fork() == 0) {
1436 if(dpy)
1437 close(ConnectionNumber(dpy));
1438 setsid();
1439 execvp(((char **)arg->v)[0], (char **)arg->v);
1440 fprintf(stderr, "dwm: execvp %s", ((char **)arg->v)[0]);
1441 perror(" failed");
1442 exit(0);
1443 }
1444 }
1445
1446 void
1447 tag(const Arg *arg) {
1448 if(sel && arg->ui & TAGMASK) {
1449 sel->tags = arg->ui & TAGMASK;
1450 arrange();
1451 }
1452 }
1453
1454 #ifdef XINERAMA
1455 void
1456 tagmon(const Arg *arg) {
1457 if(!sel || arg->ui >= nmons)
1458 return;
1459 sel->mon = arg->ui;
1460 arrange();
1461 }
1462 #endif /* XINERAMA */
1463
1464 int
1465 textnw(const char *text, unsigned int len) {
1466 XRectangle r;
1467
1468 if(dc.font.set) {
1469 XmbTextExtents(dc.font.set, text, len, NULL, &r);
1470 return r.width;
1471 }
1472 return XTextWidth(dc.font.xfont, text, len);
1473 }
1474
1475 void
1476 tile(Monitor *m) {
1477 int x, y, h, w, mw;
1478 unsigned int i, n;
1479 Client *c;
1480
1481 for(n = 0, c = nexttiled(m, clients); c; c = nexttiled(m, c->next), n++);
1482 if(n == 0)
1483 return;
1484
1485 /* master */
1486 c = nexttiled(m, clients);
1487 mw = m->mfact * m->ww;
1488 resize(c, m->wx, m->wy, (n == 1 ? m->ww : mw) - 2 * c->bw, m->wh - 2 * c->bw);
1489
1490 if(--n == 0)
1491 return;
1492
1493 /* tile stack */
1494 x = (m->wx + mw > c->x + c->w) ? c->x + c->w + 2 * c->bw : m->wx + mw;
1495 y = m->wy;
1496 w = (m->wx + mw > c->x + c->w) ? m->wx + m->ww - x : m->ww - mw;
1497 h = m->wh / n;
1498 if(h < bh)
1499 h = m->wh;
1500
1501 for(i = 0, c = nexttiled(m, c->next); c; c = nexttiled(m, c->next), i++) {
1502 resize(c, x, y, w - 2 * c->bw, /* remainder */ ((i + 1 == n)
1503 ? m->wy + m->wh - y - 2 * c->bw : h - 2 * c->bw));
1504 if(h != m->wh)
1505 y = c->y + HEIGHT(c);
1506 }
1507 }
1508
1509 void
1510 togglebar(const Arg *arg) {
1511 selmon->showbar = !selmon->showbar;
1512 updategeom();
1513 XMoveResizeWindow(dpy, selmon->barwin, selmon->wx, selmon->by, selmon->ww, bh);
1514 arrange();
1515 }
1516
1517 void
1518 togglefloating(const Arg *arg) {
1519 if(!sel)
1520 return;
1521 sel->isfloating = !sel->isfloating || sel->isfixed;
1522 if(sel->isfloating)
1523 resize(sel, sel->x, sel->y, sel->w, sel->h);
1524 arrange();
1525 }
1526
1527 void
1528 toggletag(const Arg *arg) {
1529 unsigned int mask;
1530
1531 if(!sel)
1532 return;
1533
1534 mask = sel->tags ^ (arg->ui & TAGMASK);
1535 if(mask) {
1536 sel->tags = mask;
1537 arrange();
1538 }
1539 }
1540
1541 void
1542 toggleview(const Arg *arg) {
1543 unsigned int mask = tagset[selmon->seltags] ^ (arg->ui & TAGMASK);
1544
1545 if(mask) {
1546 tagset[selmon->seltags] = mask;
1547 arrange();
1548 }
1549 }
1550
1551 void
1552 unmanage(Client *c) {
1553 XWindowChanges wc;
1554
1555 wc.border_width = c->oldbw;
1556 /* The server grab construct avoids race conditions. */
1557 XGrabServer(dpy);
1558 XSetErrorHandler(xerrordummy);
1559 XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
1560 detach(c);
1561 detachstack(c);
1562 if(sel == c)
1563 focus(NULL);
1564 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1565 setclientstate(c, WithdrawnState);
1566 free(c);
1567 XSync(dpy, False);
1568 XSetErrorHandler(xerror);
1569 XUngrabServer(dpy);
1570 arrange();
1571 }
1572
1573 void
1574 unmapnotify(XEvent *e) {
1575 Client *c;
1576 XUnmapEvent *ev = &e->xunmap;
1577
1578 if((c = getclient(ev->window)))
1579 unmanage(c);
1580 }
1581
1582 void
1583 updategeom(void) {
1584 #ifdef XINERAMA
1585 int n;
1586 unsigned int i = 0;
1587 Client *c;
1588 XineramaScreenInfo *info = NULL;
1589
1590 /* window area geometry */
1591 if(XineramaIsActive(dpy) && (info = XineramaQueryScreens(dpy, &n))) {
1592 if(n != nmons) {
1593 for(c = clients; c; c = c->next)
1594 if(c->mon >= n)
1595 c->mon = n - 1;
1596 if(!(mon = (Monitor *)realloc(mon, sizeof(Monitor) * n)))
1597 die("fatal: could not realloc() %u bytes\n", sizeof(Monitor) * nmons);
1598 }
1599 for(i = 0; i < n ; i++) {
1600 /* TODO: consider re-using XineramaScreenInfo */
1601 mon[i].symbol[0] = '[';
1602 mon[i].symbol[1] = '0' + info[i].screen_number;
1603 mon[i].symbol[2] = ']';
1604 mon[i].symbol[3] = 0;
1605 if(!selmon) { /* not initialised yet */
1606 mon[i].mfact = mfact;
1607 mon[i].showbar = showbar;
1608 mon[i].topbar = topbar;
1609 }
1610 mon[i].wx = info[i].x_org;
1611 mon[i].wy = mon[i].showbar && mon[i].topbar ? info[i].y_org + bh : info[i].y_org;
1612 mon[i].ww = info[i].width;
1613 mon[i].wh = mon[i].showbar ? info[i].height - bh : info[i].height;
1614 mon[i].seltags = 0;
1615 mon[i].sellt = 0;
1616 if(mon[i].showbar)
1617 mon[i].by = mon[i].topbar ? info[i].y_org : mon[i].wy + mon[i].wh;
1618 else
1619 mon[i].by = -bh;
1620 }
1621 nmons = (unsigned int)n;
1622 if(!selmon) {
1623 selmon = &mon[0];
1624 int di, x, y;
1625 unsigned int dui;
1626 Window dummy;
1627 if(XQueryPointer(dpy, root, &dummy, &dummy, &x, &y, &di, &di, &dui))
1628 for(i = 0; i < nmons; i++)
1629 if(INRECT(x, y, info[i].x_org, info[i].y_org, info[i].width, info[i].height)) {
1630 selmon = &mon[i];
1631 break;
1632 }
1633 }
1634 XFree(info);
1635 }
1636 else
1637 #endif /* XINERAMA */
1638 {
1639 if(!mon) {
1640 nmons = 1;
1641 if(!(mon = (Monitor *)malloc(sizeof(Monitor))))
1642 die("fatal: could not malloc() %u bytes\n", sizeof(Monitor));
1643 }
1644 if(!selmon) {
1645 mon[0].symbol[0] = '[';
1646 mon[0].symbol[1] = '0';
1647 mon[0].symbol[2] = ']';
1648 mon[0].symbol[3] = 0;
1649 mon[0].mfact = mfact;
1650 mon[0].showbar = showbar;
1651 mon[0].topbar = topbar;
1652 }
1653 mon[0].wx = sx;
1654 mon[0].wy = mon[0].showbar && mon[0].topbar ? sy + bh : sy;
1655 mon[0].ww = sw;
1656 mon[0].wh = mon[0].showbar ? sh - bh : sh;
1657 mon[0].seltags = 0;
1658 mon[0].sellt = 0;
1659 if(mon[0].showbar)
1660 mon[0].by = mon[0].topbar ? sy : mon[0].wy + mon[0].wh;
1661 else
1662 mon[0].by = -bh;
1663 selmon = &mon[0];
1664 }
1665 }
1666
1667 void
1668 updatenumlockmask(void) {
1669 unsigned int i, j;
1670 XModifierKeymap *modmap;
1671
1672 numlockmask = 0;
1673 modmap = XGetModifierMapping(dpy);
1674 for(i = 0; i < 8; i++)
1675 for(j = 0; j < modmap->max_keypermod; j++)
1676 if(modmap->modifiermap[i * modmap->max_keypermod + j]
1677 == XKeysymToKeycode(dpy, XK_Num_Lock))
1678 numlockmask = (1 << i);
1679 XFreeModifiermap(modmap);
1680 }
1681
1682 void
1683 updatesizehints(Client *c) {
1684 long msize;
1685 XSizeHints size;
1686
1687 if(!XGetWMNormalHints(dpy, c->win, &size, &msize))
1688 /* size is uninitialized, ensure that size.flags aren't used */
1689 size.flags = PSize;
1690 if(size.flags & PBaseSize) {
1691 c->basew = size.base_width;
1692 c->baseh = size.base_height;
1693 }
1694 else if(size.flags & PMinSize) {
1695 c->basew = size.min_width;
1696 c->baseh = size.min_height;
1697 }
1698 else
1699 c->basew = c->baseh = 0;
1700 if(size.flags & PResizeInc) {
1701 c->incw = size.width_inc;
1702 c->inch = size.height_inc;
1703 }
1704 else
1705 c->incw = c->inch = 0;
1706 if(size.flags & PMaxSize) {
1707 c->maxw = size.max_width;
1708 c->maxh = size.max_height;
1709 }
1710 else
1711 c->maxw = c->maxh = 0;
1712 if(size.flags & PMinSize) {
1713 c->minw = size.min_width;
1714 c->minh = size.min_height;
1715 }
1716 else if(size.flags & PBaseSize) {
1717 c->minw = size.base_width;
1718 c->minh = size.base_height;
1719 }
1720 else
1721 c->minw = c->minh = 0;
1722 if(size.flags & PAspect) {
1723 c->mina = (float)size.min_aspect.y / (float)size.min_aspect.x;
1724 c->maxa = (float)size.max_aspect.x / (float)size.max_aspect.y;
1725 }
1726 else
1727 c->maxa = c->mina = 0.0;
1728 c->isfixed = (c->maxw && c->minw && c->maxh && c->minh
1729 && c->maxw == c->minw && c->maxh == c->minh);
1730 }
1731
1732 void
1733 updatetitle(Client *c) {
1734 if(!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
1735 gettextprop(c->win, XA_WM_NAME, c->name, sizeof c->name);
1736 }
1737
1738 void
1739 updatestatus() {
1740 if(!gettextprop(root, XA_WM_NAME, stext, sizeof(stext)))
1741 strcpy(stext, "dwm-"VERSION);
1742 drawbar(selmon);
1743 }
1744
1745 void
1746 updatewmhints(Client *c) {
1747 XWMHints *wmh;
1748
1749 if((wmh = XGetWMHints(dpy, c->win))) {
1750 if(c == sel && wmh->flags & XUrgencyHint) {
1751 wmh->flags &= ~XUrgencyHint;
1752 XSetWMHints(dpy, c->win, wmh);
1753 }
1754 else
1755 c->isurgent = (wmh->flags & XUrgencyHint) ? True : False;
1756
1757 XFree(wmh);
1758 }
1759 }
1760
1761 void
1762 view(const Arg *arg) {
1763 if((arg->ui & TAGMASK) == tagset[selmon->seltags])
1764 return;
1765 selmon->seltags ^= 1; /* toggle sel tagset */
1766 if(arg->ui & TAGMASK)
1767 tagset[selmon->seltags] = arg->ui & TAGMASK;
1768 arrange();
1769 }
1770
1771 /* There's no way to check accesses to destroyed windows, thus those cases are
1772 * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
1773 * default error handler, which may call exit. */
1774 int
1775 xerror(Display *dpy, XErrorEvent *ee) {
1776 if(ee->error_code == BadWindow
1777 || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1778 || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1779 || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1780 || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1781 || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1782 || (ee->request_code == X_GrabButton && ee->error_code == BadAccess)
1783 || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1784 || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1785 return 0;
1786 fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1787 ee->request_code, ee->error_code);
1788 return xerrorxlib(dpy, ee); /* may call exit */
1789 }
1790
1791 int
1792 xerrordummy(Display *dpy, XErrorEvent *ee) {
1793 return 0;
1794 }
1795
1796 /* Startup Error handler to check if another window manager
1797 * is already running. */
1798 int
1799 xerrorstart(Display *dpy, XErrorEvent *ee) {
1800 otherwm = True;
1801 return -1;
1802 }
1803
1804 void
1805 zoom(const Arg *arg) {
1806 Client *c = sel;
1807
1808 if(!lt[selmon->sellt]->arrange || lt[selmon->sellt]->arrange == monocle || (sel && sel->isfloating))
1809 return;
1810 if(c == nexttiled(selmon, clients))
1811 if(!c || !(c = nexttiled(selmon, c->next)))
1812 return;
1813 detach(c);
1814 attach(c);
1815 focus(c);
1816 arrange();
1817 }
1818
1819 int
1820 main(int argc, char *argv[]) {
1821 if(argc == 2 && !strcmp("-v", argv[1]))
1822 die("dwm-"VERSION", © 2006-2009 dwm engineers, see LICENSE for details\n");
1823 else if(argc != 1)
1824 die("usage: dwm [-v]\n");
1825
1826 if(!setlocale(LC_CTYPE, "") || !XSupportsLocale())
1827 fputs("warning: no locale support\n", stderr);
1828
1829 if(!(dpy = XOpenDisplay(NULL)))
1830 die("dwm: cannot open display\n");
1831
1832 checkotherwm();
1833 setup();
1834 scan();
1835 run();
1836 cleanup();
1837
1838 XCloseDisplay(dpy);
1839 return 0;
1840 }