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