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