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