JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
some restack fixes, still odd behavior if n>1 on unmanaging clients
[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 unmanage(Client *c);
215 static void unmapnotify(XEvent *e);
216 static void updategeom(void);
217 static void updatebarpos(Monitor *m);
218 static void updatebars(void);
219 static void updatenumlockmask(void);
220 static void updatesizehints(Client *c);
221 static void updatestatus(void);
222 static void updatetitle(Client *c);
223 static void updatewmhints(Client *c);
224 static void view(const Arg *arg);
225 static int xerror(Display *dpy, XErrorEvent *ee);
226 static int xerrordummy(Display *dpy, XErrorEvent *ee);
227 static int xerrorstart(Display *dpy, XErrorEvent *ee);
228 static void zoom(const Arg *arg);
229 #ifdef XINERAMA
230 static void focusmon(const Arg *arg);
231 static void tagmon(const Arg *arg);
232 #endif /* XINERAMA */
233
234 /* variables */
235 static char stext[256];
236 static int screen;
237 static int sx, sy, sw, sh;   /* X display screen geometry x, y, width, height */
238 static int bh, blw = 0;      /* bar geometry */
239 static int (*xerrorxlib)(Display *, XErrorEvent *);
240 static unsigned int numlockmask = 0;
241 static void (*handler[LASTEvent]) (XEvent *) = {
242         [ButtonPress] = buttonpress,
243         [ConfigureRequest] = configurerequest,
244         [ConfigureNotify] = configurenotify,
245         [DestroyNotify] = destroynotify,
246         [EnterNotify] = enternotify,
247         [Expose] = expose,
248         [FocusIn] = focusin,
249         [KeyPress] = keypress,
250         [MappingNotify] = mappingnotify,
251         [MapRequest] = maprequest,
252         [PropertyNotify] = propertynotify,
253         [UnmapNotify] = unmapnotify
254 };
255 static Atom wmatom[WMLast], netatom[NetLast];
256 static Bool otherwm;
257 static Bool running = True;
258 static Cursor cursor[CurLast];
259 static Display *dpy;
260 static DC dc;
261 static Layout *lt[] = { NULL, NULL };
262 static Monitor *mons = NULL, *selmon = NULL;
263 static Window root;
264 /* configuration, allows nested code to access above variables */
265 #include "config.h"
266
267 /* compile-time check if all tags fit into an unsigned int bit array. */
268 struct NumTags { char limitexceeded[sizeof(unsigned int) * 8 < LENGTH(tags) ? -1 : 1]; };
269
270 /* function implementations */
271 void
272 applyrules(Client *c) {
273         unsigned int i;
274         Rule *r;
275         XClassHint ch = { 0 };
276
277         /* rule matching */
278         c->isfloating = c->tags = 0;
279         if(XGetClassHint(dpy, c->win, &ch)) {
280                 for(i = 0; i < LENGTH(rules); i++) {
281                         r = &rules[i];
282                         if((!r->title || strstr(c->name, r->title))
283                         && (!r->class || (ch.res_class && strstr(ch.res_class, r->class)))
284                         && (!r->instance || (ch.res_name && strstr(ch.res_name, r->instance)))) {
285                                 c->isfloating = r->isfloating;
286                                 c->tags |= r->tags;
287                         }
288                 }
289                 if(ch.res_class)
290                         XFree(ch.res_class);
291                 if(ch.res_name)
292                         XFree(ch.res_name);
293         }
294         c->tags = c->tags & TAGMASK ? c->tags & TAGMASK : c->mon->tagset[c->mon->seltags];
295 }
296
297 Bool
298 applysizehints(Client *c, int *x, int *y, int *w, int *h) {
299         Bool baseismin;
300
301         /* set minimum possible */
302         *w = MAX(1, *w);
303         *h = MAX(1, *h);
304
305         if(*x > sx + sw)
306                 *x = sw - WIDTH(c);
307         if(*y > sy + sh)
308                 *y = sh - HEIGHT(c);
309         if(*x + *w + 2 * c->bw < sx)
310                 *x = sx;
311         if(*y + *h + 2 * c->bw < sy)
312                 *y = sy;
313         if(*h < bh)
314                 *h = bh;
315         if(*w < bh)
316                 *w = bh;
317
318         if(resizehints || c->isfloating) {
319                 /* see last two sentences in ICCCM 4.1.2.3 */
320                 baseismin = c->basew == c->minw && c->baseh == c->minh;
321
322                 if(!baseismin) { /* temporarily remove base dimensions */
323                         *w -= c->basew;
324                         *h -= c->baseh;
325                 }
326
327                 /* adjust for aspect limits */
328                 if(c->mina > 0 && c->maxa > 0) {
329                         if(c->maxa < (float)*w / *h)
330                                 *w = *h * c->maxa;
331                         else if(c->mina < (float)*h / *w)
332                                 *h = *w * c->mina;
333                 }
334
335                 if(baseismin) { /* increment calculation requires this */
336                         *w -= c->basew;
337                         *h -= c->baseh;
338                 }
339
340                 /* adjust for increment value */
341                 if(c->incw)
342                         *w -= *w % c->incw;
343                 if(c->inch)
344                         *h -= *h % c->inch;
345
346                 /* restore base dimensions */
347                 *w += c->basew;
348                 *h += c->baseh;
349
350                 *w = MAX(*w, c->minw);
351                 *h = MAX(*h, c->minh);
352
353                 if(c->maxw)
354                         *w = MIN(*w, c->maxw);
355
356                 if(c->maxh)
357                         *h = MIN(*h, c->maxh);
358         }
359         return *x != c->x || *y != c->y || *w != c->w || *h != c->h;
360 }
361
362 void
363 arrange(void) {
364         Monitor *m;
365
366         /* optimise two loops into one, check focus(NULL) */
367         for(m = mons; m; m = m->next)
368                 showhide(m->stack);
369         focus(NULL);
370         for(m = mons; m; m = m->next) {
371                 if(lt[m->sellt]->arrange)
372                         lt[m->sellt]->arrange(m);
373                 restack(m);
374         }
375 }
376
377 void
378 attach(Client *c) {
379         c->next = c->mon->clients;
380         c->mon->clients = c;
381 }
382
383 void
384 attachstack(Client *c) {
385         c->snext = c->mon->stack;
386         c->mon->stack = c;
387 }
388
389 void
390 buttonpress(XEvent *e) {
391         unsigned int i, x, click;
392         Arg arg = {0};
393         Client *c;
394         XButtonPressedEvent *ev = &e->xbutton;
395
396         click = ClkRootWin;
397         if(ev->window == selmon->barwin && ev->x >= selmon->btx) {
398                 i = 0;
399                 x = selmon->btx;
400                 do
401                         x += TEXTW(tags[i]);
402                 while(ev->x >= x && ++i < LENGTH(tags));
403                 if(i < LENGTH(tags)) {
404                         click = ClkTagBar;
405                         arg.ui = 1 << i;
406                 }
407                 else if(ev->x < x + blw)
408                         click = ClkLtSymbol;
409                 else if(ev->x > selmon->wx + selmon->ww - TEXTW(stext))
410                         click = ClkStatusText;
411                 else
412                         click = ClkWinTitle;
413         }
414         else if((c = getclient(ev->window))) {
415                 focus(c);
416                 click = ClkClientWin;
417         }
418
419         for(i = 0; i < LENGTH(buttons); i++)
420                 if(click == buttons[i].click && buttons[i].func && buttons[i].button == ev->button
421                    && CLEANMASK(buttons[i].mask) == CLEANMASK(ev->state))
422                         buttons[i].func(click == ClkTagBar && buttons[i].arg.i == 0 ? &arg : &buttons[i].arg);
423 }
424
425 void
426 checkotherwm(void) {
427         otherwm = False;
428         xerrorxlib = XSetErrorHandler(xerrorstart);
429
430         /* this causes an error if some other window manager is running */
431         XSelectInput(dpy, DefaultRootWindow(dpy), SubstructureRedirectMask);
432         XSync(dpy, False);
433         if(otherwm)
434                 die("dwm: another window manager is already running\n");
435         XSetErrorHandler(xerror);
436         XSync(dpy, False);
437 }
438
439 void
440 cleanup(void) {
441         Arg a = {.ui = ~0};
442         Layout foo = { "", NULL };
443         Monitor *m;
444
445         view(&a);
446         lt[selmon->sellt] = &foo;
447
448         /* TODO: consider simplifying cleanup code of the stack, perhaps do that in cleanmons() ? */
449         for(m = mons; m; m = m->next)
450                 while(m->stack)
451                         unmanage(m->stack);
452         if(dc.font.set)
453                 XFreeFontSet(dpy, dc.font.set);
454         else
455                 XFreeFont(dpy, dc.font.xfont);
456         XUngrabKey(dpy, AnyKey, AnyModifier, root);
457         XFreePixmap(dpy, dc.drawable);
458         XFreeGC(dpy, dc.gc);
459         XFreeCursor(dpy, cursor[CurNormal]);
460         XFreeCursor(dpy, cursor[CurResize]);
461         XFreeCursor(dpy, cursor[CurMove]);
462         cleanupmons();
463         XSync(dpy, False);
464         XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime);
465 }
466
467 void
468 cleanupmons(void) {
469         Monitor *m;
470
471         while(mons) {
472                 m = mons->next;
473                 XUnmapWindow(dpy, mons->barwin);
474                 XDestroyWindow(dpy, mons->barwin);
475                 free(mons);
476                 mons = m;
477         }
478 }
479
480 void
481 clearurgent(Client *c) {
482         XWMHints *wmh;
483
484         c->isurgent = False;
485         if(!(wmh = XGetWMHints(dpy, c->win)))
486                 return;
487         wmh->flags &= ~XUrgencyHint;
488         XSetWMHints(dpy, c->win, wmh);
489         XFree(wmh);
490 }
491
492 void
493 configure(Client *c) {
494         XConfigureEvent ce;
495
496         ce.type = ConfigureNotify;
497         ce.display = dpy;
498         ce.event = c->win;
499         ce.window = c->win;
500         ce.x = c->x;
501         ce.y = c->y;
502         ce.width = c->w;
503         ce.height = c->h;
504         ce.border_width = c->bw;
505         ce.above = None;
506         ce.override_redirect = False;
507         XSendEvent(dpy, c->win, False, StructureNotifyMask, (XEvent *)&ce);
508 }
509
510 void
511 configurenotify(XEvent *e) {
512         Monitor *m;
513         XConfigureEvent *ev = &e->xconfigure;
514
515         if(ev->window == root && (ev->width != sw || ev->height != sh)) {
516                 sw = ev->width;
517                 sh = ev->height;
518                 updategeom();
519                 if(dc.drawable != 0)
520                         XFreePixmap(dpy, dc.drawable);
521                 dc.drawable = XCreatePixmap(dpy, root, sw, bh, DefaultDepth(dpy, screen));
522                 updatebars();
523                 for(m = mons; m; m = m->next)
524                         XMoveResizeWindow(dpy, m->barwin, m->wx, m->by, m->ww, bh);
525                 arrange();
526         }
527 }
528
529 void
530 configurerequest(XEvent *e) {
531         Client *c;
532         XConfigureRequestEvent *ev = &e->xconfigurerequest;
533         XWindowChanges wc;
534
535         if((c = getclient(ev->window))) {
536                 if(ev->value_mask & CWBorderWidth)
537                         c->bw = ev->border_width;
538                 else if(c->isfloating || !lt[selmon->sellt]->arrange) {
539                         if(ev->value_mask & CWX)
540                                 c->x = sx + ev->x;
541                         if(ev->value_mask & CWY)
542                                 c->y = sy + ev->y;
543                         if(ev->value_mask & CWWidth)
544                                 c->w = ev->width;
545                         if(ev->value_mask & CWHeight)
546                                 c->h = ev->height;
547                         if((c->x - sx + c->w) > sw && c->isfloating)
548                                 c->x = sx + (sw / 2 - c->w / 2); /* center in x direction */
549                         if((c->y - sy + c->h) > sh && c->isfloating)
550                                 c->y = sy + (sh / 2 - c->h / 2); /* center in y direction */
551                         if((ev->value_mask & (CWX|CWY)) && !(ev->value_mask & (CWWidth|CWHeight)))
552                                 configure(c);
553                         if(ISVISIBLE(c))
554                                 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h);
555                 }
556                 else
557                         configure(c);
558         }
559         else {
560                 wc.x = ev->x;
561                 wc.y = ev->y;
562                 wc.width = ev->width;
563                 wc.height = ev->height;
564                 wc.border_width = ev->border_width;
565                 wc.sibling = ev->above;
566                 wc.stack_mode = ev->detail;
567                 XConfigureWindow(dpy, ev->window, ev->value_mask, &wc);
568         }
569         XSync(dpy, False);
570 }
571
572 void
573 destroynotify(XEvent *e) {
574         Client *c;
575         XDestroyWindowEvent *ev = &e->xdestroywindow;
576
577         if((c = getclient(ev->window)))
578                 unmanage(c);
579 }
580
581 void
582 detach(Client *c) {
583         Client **tc;
584
585         for(tc = &c->mon->clients; *tc && *tc != c; tc = &(*tc)->next);
586         *tc = c->next;
587 }
588
589 void
590 detachstack(Client *c) {
591         Client **tc;
592
593         for(tc = &c->mon->stack; *tc && *tc != c; tc = &(*tc)->snext);
594         *tc = c->snext;
595 }
596
597 void
598 die(const char *errstr, ...) {
599         va_list ap;
600
601         va_start(ap, errstr);
602         vfprintf(stderr, errstr, ap);
603         va_end(ap);
604         exit(EXIT_FAILURE);
605 }
606
607 void
608 drawbar(Monitor *m) {
609         int x;
610         unsigned int i, occ = 0, urg = 0;
611         unsigned long *col;
612         Client *c;
613
614         for(c = m->clients; c; c = c->next) {
615                 occ |= c->tags;
616                 if(c->isurgent)
617                         urg |= c->tags;
618         }
619
620         dc.x = 0;
621 #ifdef XINERAMA
622         {
623                 char buf[2];
624                 buf[0] = m->screen_number + '0';
625                 buf[1] = '\0';
626                 dc.w = TEXTW(buf);
627                 drawtext(buf, selmon == m ? dc.sel : dc.norm, True);
628                 dc.x += dc.w;
629         }
630 #endif /* XINERAMA */
631         m->btx = dc.x;
632         for(i = 0; i < LENGTH(tags); i++) {
633                 dc.w = TEXTW(tags[i]);
634                 col = m->tagset[m->seltags] & 1 << i ? dc.sel : dc.norm;
635                 drawtext(tags[i], col, urg & 1 << i);
636                 drawsquare(m == selmon && selmon->sel && selmon->sel->tags & 1 << i,
637                            occ & 1 << i, urg & 1 << i, col);
638                 dc.x += dc.w;
639         }
640         if(blw > 0) {
641                 dc.w = blw;
642                 drawtext(lt[m->sellt]->symbol, dc.norm, False);
643                 x = dc.x + dc.w;
644         }
645         else
646                 x = dc.x;
647         if(m == selmon) {
648                 dc.w = TEXTW(stext);
649                 dc.x = m->ww - dc.w;
650                 if(dc.x < x) {
651                         dc.x = x;
652                         dc.w = m->ww - x;
653                 }
654                 drawtext(stext, dc.norm, False);
655                 if((dc.w = dc.x - x) > bh) {
656                         dc.x = x;
657                         if(selmon->sel) {
658                                 drawtext(selmon->sel->name, dc.sel, False);
659                                 drawsquare(selmon->sel->isfixed, selmon->sel->isfloating, False, dc.sel);
660                         }
661                         else
662                                 drawtext(NULL, dc.norm, False);
663                 }
664         }
665         else {
666                 dc.x = x;
667                 dc.w = m->ww - x;
668                 drawtext(NULL, dc.norm, False);
669         }
670         XCopyArea(dpy, dc.drawable, m->barwin, dc.gc, 0, 0, m->ww, bh, 0, 0);
671         XSync(dpy, False);
672 }
673
674 void
675 drawbars() {
676         Monitor *m;
677
678         for(m = mons; m; m = m->next)
679                 drawbar(m);
680 }
681
682 void
683 drawsquare(Bool filled, Bool empty, Bool invert, unsigned long col[ColLast]) {
684         int x;
685         XGCValues gcv;
686         XRectangle r = { dc.x, dc.y, dc.w, dc.h };
687
688         gcv.foreground = col[invert ? ColBG : ColFG];
689         XChangeGC(dpy, dc.gc, GCForeground, &gcv);
690         x = (dc.font.ascent + dc.font.descent + 2) / 4;
691         r.x = dc.x + 1;
692         r.y = dc.y + 1;
693         if(filled) {
694                 r.width = r.height = x + 1;
695                 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
696         }
697         else if(empty) {
698                 r.width = r.height = x;
699                 XDrawRectangles(dpy, dc.drawable, dc.gc, &r, 1);
700         }
701 }
702
703 void
704 drawtext(const char *text, unsigned long col[ColLast], Bool invert) {
705         char buf[256];
706         int i, x, y, h, len, olen;
707         XRectangle r = { dc.x, dc.y, dc.w, dc.h };
708
709         XSetForeground(dpy, dc.gc, col[invert ? ColFG : ColBG]);
710         XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
711         if(!text)
712                 return;
713         olen = strlen(text);
714         h = dc.font.ascent + dc.font.descent;
715         y = dc.y + (dc.h / 2) - (h / 2) + dc.font.ascent;
716         x = dc.x + (h / 2);
717         /* shorten text if necessary */
718         for(len = MIN(olen, sizeof buf); len && textnw(text, len) > dc.w - h; len--);
719         if(!len)
720                 return;
721         memcpy(buf, text, len);
722         if(len < olen)
723                 for(i = len; i && i > len - 3; buf[--i] = '.');
724         XSetForeground(dpy, dc.gc, col[invert ? ColBG : ColFG]);
725         if(dc.font.set)
726                 XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
727         else
728                 XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
729 }
730
731 void
732 enternotify(XEvent *e) {
733         Client *c;
734         XCrossingEvent *ev = &e->xcrossing;
735
736         if((ev->mode != NotifyNormal || ev->detail == NotifyInferior) && ev->window != root)
737                 return;
738         if((c = getclient(ev->window)))
739                 focus(c);
740         else
741                 focus(NULL);
742 }
743
744 void
745 expose(XEvent *e) {
746         Monitor *m;
747         XExposeEvent *ev = &e->xexpose;
748
749         if(ev->count == 0)
750                 for(m = mons; m; m = m->next)
751                         if(ev->window == m->barwin) {
752                                 drawbar(m);
753                                 break;
754                         }
755 }
756
757 void
758 focus(Client *c) {
759         if(!c || !ISVISIBLE(c))
760                 for(c = selmon->stack; c && !ISVISIBLE(c); c = c->snext);
761         if(selmon->sel && selmon->sel != c) {
762                 grabbuttons(selmon->sel, False);
763                 XSetWindowBorder(dpy, selmon->sel->win, dc.norm[ColBorder]);
764         }
765         if(c) {
766                 if(c->isurgent)
767                         clearurgent(c);
768                 detachstack(c);
769                 attachstack(c);
770                 grabbuttons(c, True);
771                 XSetWindowBorder(dpy, c->win, dc.sel[ColBorder]);
772                 XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
773         }
774         else
775                 XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
776         selmon->sel = c;
777         drawbars();
778 }
779
780 void
781 focusin(XEvent *e) { /* there are some broken focus acquiring clients */
782         XFocusChangeEvent *ev = &e->xfocus;
783
784         if(selmon->sel && ev->window != selmon->sel->win)
785                 XSetInputFocus(dpy, selmon->sel->win, RevertToPointerRoot, CurrentTime);
786 }
787
788 #ifdef XINERAMA
789 void
790 focusmon(const Arg *arg) {
791         unsigned int i;
792         Monitor *m; 
793
794         for(i = 0, m = mons; m; m = m->next, i++)
795                 if(i == arg->ui) {
796                         selmon = m;
797                         focus(NULL);
798                         drawbars();
799                         break;
800                 }
801 }
802 #endif /* XINERAMA */
803
804 void
805 focusstack(const Arg *arg) {
806         Client *c = NULL, *i;
807
808         if(!selmon->sel)
809                 return;
810         if(arg->i > 0) {
811                 for(c = selmon->sel->next; c && !ISVISIBLE(c); c = c->next);
812                 if(!c)
813                         for(c = selmon->clients; c && !ISVISIBLE(c); c = c->next);
814         }
815         else {
816                 for(i = selmon->clients; i != selmon->sel; i = i->next)
817                         if(ISVISIBLE(i))
818                                 c = i;
819                 if(!c)
820                         for(; i; i = i->next)
821                                 if(ISVISIBLE(i))
822                                         c = i;
823         }
824         if(c) {
825                 focus(c);
826                 restack(selmon);
827         }
828 }
829
830 Client *
831 getclient(Window w) {
832         Client *c = NULL;
833         Monitor *m;
834
835         for(m = mons; m; m = m->next)
836                 for(c = m->clients; c && c->win != w; c = c->next);
837         return c;
838 }
839
840 unsigned long
841 getcolor(const char *colstr) {
842         Colormap cmap = DefaultColormap(dpy, screen);
843         XColor color;
844
845         if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
846                 die("error, cannot allocate color '%s'\n", colstr);
847         return color.pixel;
848 }
849
850 long
851 getstate(Window w) {
852         int format, status;
853         long result = -1;
854         unsigned char *p = NULL;
855         unsigned long n, extra;
856         Atom real;
857
858         status = XGetWindowProperty(dpy, w, wmatom[WMState], 0L, 2L, False, wmatom[WMState],
859                         &real, &format, &n, &extra, (unsigned char **)&p);
860         if(status != Success)
861                 return -1;
862         if(n != 0)
863                 result = *p;
864         XFree(p);
865         return result;
866 }
867
868 Bool
869 gettextprop(Window w, Atom atom, char *text, unsigned int size) {
870         char **list = NULL;
871         int n;
872         XTextProperty name;
873
874         if(!text || size == 0)
875                 return False;
876         text[0] = '\0';
877         XGetTextProperty(dpy, w, &name, atom);
878         if(!name.nitems)
879                 return False;
880         if(name.encoding == XA_STRING)
881                 strncpy(text, (char *)name.value, size - 1);
882         else {
883                 if(XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success
884                 && n > 0 && *list) {
885                         strncpy(text, *list, size - 1);
886                         XFreeStringList(list);
887                 }
888         }
889         text[size - 1] = '\0';
890         XFree(name.value);
891         return True;
892 }
893
894 void
895 grabbuttons(Client *c, Bool focused) {
896         updatenumlockmask();
897         {
898                 unsigned int i, j;
899                 unsigned int modifiers[] = { 0, LockMask, numlockmask, numlockmask|LockMask };
900                 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
901                 if(focused) {
902                         for(i = 0; i < LENGTH(buttons); i++)
903                                 if(buttons[i].click == ClkClientWin)
904                                         for(j = 0; j < LENGTH(modifiers); j++)
905                                                 XGrabButton(dpy, buttons[i].button,
906                                                             buttons[i].mask | modifiers[j],
907                                                             c->win, False, BUTTONMASK,
908                                                             GrabModeAsync, GrabModeSync, None, None);
909                 } else
910                         XGrabButton(dpy, AnyButton, AnyModifier, c->win, False,
911                                     BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
912         }
913 }
914
915 void
916 grabkeys(void) {
917         updatenumlockmask();
918         { /* grab keys */
919                 unsigned int i, j;
920                 unsigned int modifiers[] = { 0, LockMask, numlockmask, numlockmask|LockMask };
921                 KeyCode code;
922
923                 XUngrabKey(dpy, AnyKey, AnyModifier, root);
924                 for(i = 0; i < LENGTH(keys); i++) {
925                         if((code = XKeysymToKeycode(dpy, keys[i].keysym)))
926                                 for(j = 0; j < LENGTH(modifiers); j++)
927                                         XGrabKey(dpy, code, keys[i].mod | modifiers[j], root,
928                                                  True, GrabModeAsync, GrabModeAsync);
929                 }
930         }
931 }
932
933 void
934 initfont(const char *fontstr) {
935         char *def, **missing;
936         int i, n;
937
938         missing = NULL;
939         dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
940         if(missing) {
941                 while(n--)
942                         fprintf(stderr, "dwm: missing fontset: %s\n", missing[n]);
943                 XFreeStringList(missing);
944         }
945         if(dc.font.set) {
946                 XFontSetExtents *font_extents;
947                 XFontStruct **xfonts;
948                 char **font_names;
949                 dc.font.ascent = dc.font.descent = 0;
950                 font_extents = XExtentsOfFontSet(dc.font.set);
951                 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
952                 for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
953                         dc.font.ascent = MAX(dc.font.ascent, (*xfonts)->ascent);
954                         dc.font.descent = MAX(dc.font.descent,(*xfonts)->descent);
955                         xfonts++;
956                 }
957         }
958         else {
959                 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr))
960                 && !(dc.font.xfont = XLoadQueryFont(dpy, "fixed")))
961                         die("error, cannot load font: '%s'\n", fontstr);
962                 dc.font.ascent = dc.font.xfont->ascent;
963                 dc.font.descent = dc.font.xfont->descent;
964         }
965         dc.font.height = dc.font.ascent + dc.font.descent;
966 }
967
968 Bool
969 isprotodel(Client *c) {
970         int i, n;
971         Atom *protocols;
972         Bool ret = False;
973
974         if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
975                 for(i = 0; !ret && i < n; i++)
976                         if(protocols[i] == wmatom[WMDelete])
977                                 ret = True;
978                 XFree(protocols);
979         }
980         return ret;
981 }
982
983 void
984 keypress(XEvent *e) {
985         unsigned int i;
986         KeySym keysym;
987         XKeyEvent *ev;
988
989         ev = &e->xkey;
990         keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
991         for(i = 0; i < LENGTH(keys); i++)
992                 if(keysym == keys[i].keysym
993                    && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state)
994                    && keys[i].func)
995                         keys[i].func(&(keys[i].arg));
996 }
997
998 void
999 killclient(const Arg *arg) {
1000         XEvent ev;
1001
1002         if(!selmon->sel)
1003                 return;
1004         if(isprotodel(selmon->sel)) {
1005                 ev.type = ClientMessage;
1006                 ev.xclient.window = selmon->sel->win;
1007                 ev.xclient.message_type = wmatom[WMProtocols];
1008                 ev.xclient.format = 32;
1009                 ev.xclient.data.l[0] = wmatom[WMDelete];
1010                 ev.xclient.data.l[1] = CurrentTime;
1011                 XSendEvent(dpy, selmon->sel->win, False, NoEventMask, &ev);
1012         }
1013         else
1014                 XKillClient(dpy, selmon->sel->win);
1015 }
1016
1017 void
1018 manage(Window w, XWindowAttributes *wa) {
1019         static Client cz;
1020         Client *c, *t = NULL;
1021         Window trans = None;
1022         XWindowChanges wc;
1023
1024         if(!(c = malloc(sizeof(Client))))
1025                 die("fatal: could not malloc() %u bytes\n", sizeof(Client));
1026         *c = cz;
1027         c->win = w;
1028         c->mon = selmon;
1029
1030         /* geometry */
1031         c->x = wa->x;
1032         c->y = wa->y;
1033         c->w = wa->width;
1034         c->h = wa->height;
1035         c->oldbw = wa->border_width;
1036         if(c->w == sw && c->h == sh) {
1037                 c->x = sx;
1038                 c->y = sy;
1039                 c->bw = 0;
1040         }
1041         else {
1042                 if(c->x + WIDTH(c) > sx + sw)
1043                         c->x = sx + sw - WIDTH(c);
1044                 if(c->y + HEIGHT(c) > sy + sh)
1045                         c->y = sy + sh - HEIGHT(c);
1046                 c->x = MAX(c->x, sx);
1047                 /* only fix client y-offset, if the client center might cover the bar */
1048                 c->y = MAX(c->y, ((c->mon->by == 0) && (c->x + (c->w / 2) >= c->mon->wx)
1049                            && (c->x + (c->w / 2) < c->mon->wx + c->mon->ww)) ? bh : sy);
1050                 c->bw = borderpx;
1051         }
1052
1053         wc.border_width = c->bw;
1054         XConfigureWindow(dpy, w, CWBorderWidth, &wc);
1055         XSetWindowBorder(dpy, w, dc.norm[ColBorder]);
1056         configure(c); /* propagates border_width, if size doesn't change */
1057         updatesizehints(c);
1058         XSelectInput(dpy, w, EnterWindowMask|FocusChangeMask|PropertyChangeMask|StructureNotifyMask);
1059         grabbuttons(c, False);
1060         updatetitle(c);
1061         if(XGetTransientForHint(dpy, w, &trans))
1062                 t = getclient(trans);
1063         if(t)
1064                 c->tags = t->tags;
1065         else
1066                 applyrules(c);
1067         if(!c->isfloating)
1068                 c->isfloating = trans != None || c->isfixed;
1069         if(c->isfloating)
1070                 XRaiseWindow(dpy, c->win);
1071         attach(c);
1072         attachstack(c);
1073         XMoveResizeWindow(dpy, c->win, c->x + 2 * sw, c->y, c->w, c->h); /* some windows require this */
1074         XMapWindow(dpy, c->win);
1075         setclientstate(c, NormalState);
1076         arrange();
1077 }
1078
1079 void
1080 mappingnotify(XEvent *e) {
1081         XMappingEvent *ev = &e->xmapping;
1082
1083         XRefreshKeyboardMapping(ev);
1084         if(ev->request == MappingKeyboard)
1085                 grabkeys();
1086 }
1087
1088 void
1089 maprequest(XEvent *e) {
1090         static XWindowAttributes wa;
1091         XMapRequestEvent *ev = &e->xmaprequest;
1092
1093         if(!XGetWindowAttributes(dpy, ev->window, &wa))
1094                 return;
1095         if(wa.override_redirect)
1096                 return;
1097         if(!getclient(ev->window))
1098                 manage(ev->window, &wa);
1099 }
1100
1101 void
1102 monocle(Monitor *m) {
1103         Client *c;
1104
1105         for(c = nexttiled(m->clients); c; c = nexttiled(c->next))
1106                 resize(c, m->wx, m->wy, m->ww - 2 * c->bw, m->wh - 2 * c->bw);
1107 }
1108
1109 void
1110 movemouse(const Arg *arg) {
1111         int x, y, ocx, ocy, di, nx, ny;
1112         unsigned int dui;
1113         Client *c;
1114         Window dummy;
1115         XEvent ev;
1116
1117         if(!(c = selmon->sel))
1118                 return;
1119         restack(selmon);
1120         ocx = c->x;
1121         ocy = c->y;
1122         if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1123         None, cursor[CurMove], CurrentTime) != GrabSuccess)
1124                 return;
1125         XQueryPointer(dpy, root, &dummy, &dummy, &x, &y, &di, &di, &dui);
1126         do {
1127                 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
1128                 switch (ev.type) {
1129                 case ConfigureRequest:
1130                 case Expose:
1131                 case MapRequest:
1132                         handler[ev.type](&ev);
1133                         break;
1134                 case MotionNotify:
1135                         nx = ocx + (ev.xmotion.x - x);
1136                         ny = ocy + (ev.xmotion.y - y);
1137                         if(snap && nx >= selmon->wx && nx <= selmon->wx + selmon->ww
1138                                 && ny >= selmon->wy && ny <= selmon->wy + selmon->wh) {
1139                                 if(abs(selmon->wx - nx) < snap)
1140                                         nx = selmon->wx;
1141                                 else if(abs((selmon->wx + selmon->ww) - (nx + WIDTH(c))) < snap)
1142                                         nx = selmon->wx + selmon->ww - WIDTH(c);
1143                                 if(abs(selmon->wy - ny) < snap)
1144                                         ny = selmon->wy;
1145                                 else if(abs((selmon->wy + selmon->wh) - (ny + HEIGHT(c))) < snap)
1146                                         ny = selmon->wy + selmon->wh - HEIGHT(c);
1147                                 if(!c->isfloating && lt[selmon->sellt]->arrange
1148                                                   && (abs(nx - c->x) > snap || abs(ny - c->y) > snap))
1149                                         togglefloating(NULL);
1150                         }
1151                         if(!lt[selmon->sellt]->arrange || c->isfloating)
1152                                 resize(c, nx, ny, c->w, c->h);
1153                         break;
1154                 }
1155         }
1156         while(ev.type != ButtonRelease);
1157         XUngrabPointer(dpy, CurrentTime);
1158 }
1159
1160 Client *
1161 nexttiled(Client *c) {
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(!m->sel)
1275                 return;
1276         if(m->sel->isfloating || !lt[m->sellt]->arrange)
1277                 XRaiseWindow(dpy, m->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(c->mon->sel == c) {
1597                 c->mon->sel = c->mon->stack;
1598                 focus(NULL);
1599         }
1600         XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1601         setclientstate(c, WithdrawnState);
1602         free(c);
1603         XSync(dpy, False);
1604         XSetErrorHandler(xerror);
1605         XUngrabServer(dpy);
1606         arrange();
1607 }
1608
1609 void
1610 unmapnotify(XEvent *e) {
1611         Client *c;
1612         XUnmapEvent *ev = &e->xunmap;
1613
1614         if((c = getclient(ev->window)))
1615                 unmanage(c);
1616 }
1617
1618 void
1619 updatebars(void) {
1620         Monitor *m;
1621         XSetWindowAttributes wa;
1622
1623         wa.override_redirect = True;
1624         wa.background_pixmap = ParentRelative;
1625         wa.event_mask = ButtonPressMask|ExposureMask;
1626
1627         for(m = mons; m; m = m->next) {
1628                 m->barwin = XCreateWindow(dpy, root, m->wx, m->by, m->ww, bh, 0, DefaultDepth(dpy, screen),
1629
1630                                           CopyFromParent, DefaultVisual(dpy, screen),
1631                                           CWOverrideRedirect|CWBackPixmap|CWEventMask, &wa);
1632                 XDefineCursor(dpy, m->barwin, cursor[CurNormal]);
1633                 XMapRaised(dpy, m->barwin);
1634         }
1635 }
1636
1637 void
1638 updatebarpos(Monitor *m) {
1639         m->wy = m->my;
1640         m->wh = m->mh;
1641         if(m->showbar) {
1642                 m->wh -= bh;
1643                 m->by = m->topbar ? m->wy : m->wy + m->wh;
1644                 m->wy = m->topbar ? m->wy + bh : m->wy;
1645         }
1646         else
1647                 m->by = -bh;
1648 }
1649
1650 void
1651 updategeom(void) {
1652         int i, n = 1;
1653         Client *c;
1654         Monitor *newmons = NULL, *m, *tm;
1655
1656 #ifdef XINULATOR
1657         n = 2;
1658 #elif defined(XINERAMA)
1659         XineramaScreenInfo *info = NULL;
1660
1661         if(XineramaIsActive(dpy))
1662                 info = XineramaQueryScreens(dpy, &n);
1663 #endif
1664         /* allocate monitor(s) for the new geometry setup */
1665         for(i = 0; i < n; i++) {
1666                 m = (Monitor *)malloc(sizeof(Monitor));
1667                 m->next = newmons;
1668                 newmons = m;
1669         }
1670
1671         /* initialise monitor(s) */
1672 #ifdef XINULATOR
1673         if(1) {
1674                 m = newmons;
1675                 m->screen_number = 0;
1676                 m->wx = sx;
1677                 m->my = m->wy = sy;
1678                 m->ww = sw;
1679                 m->mh = m->wh = sh / 2;
1680                 m = newmons->next;
1681                 m->screen_number = 1;
1682                 m->wx = sx;
1683                 m->my = m->wy = sy + sh / 2;
1684                 m->ww = sw;
1685                 m->mh = m->wh = sh / 2;
1686         }
1687         else
1688 #elif defined(XINERAMA)
1689         if(XineramaIsActive(dpy)) {
1690                 for(i = 0, m = newmons; m; m = m->next, i++) {
1691                         m->screen_number = info[i].screen_number;
1692                         m->wx = info[i].x_org;
1693                         m->my = m->wy = info[i].y_org;
1694                         m->ww = info[i].width;
1695                         m->mh = m->wh = info[i].height;
1696                 }
1697                 XFree(info);
1698         }
1699         else
1700 #endif
1701         /* default monitor setup */
1702         {
1703                 m->screen_number = 0;
1704                 m->wx = sx;
1705                 m->my = m->wy = sy;
1706                 m->ww = sw;
1707                 m->mh = m->wh = sh;
1708         }
1709
1710         /* bar geometry setup */
1711         for(m = newmons; m; m = m->next) {
1712                 /* TODO: consider removing the following values from config.h */
1713                 m->clients = NULL;
1714                 m->sel = NULL;
1715                 m->stack = NULL;
1716                 m->seltags = 0;
1717                 m->sellt = 0;
1718                 m->tagset[0] = m->tagset[1] = 1;
1719                 m->mfact = mfact;
1720                 m->showbar = showbar;
1721                 m->topbar = topbar;
1722                 updatebarpos(m);
1723                 /* reassign all clients with same screen number */
1724                 for(tm = mons; tm; tm = tm->next)
1725                         if(tm->screen_number == m->screen_number) {
1726                                 m->clients = tm->clients;
1727                                 m->sel = m->stack = tm->stack;
1728                                 tm->clients = NULL;
1729                                 tm->stack = NULL;
1730                                 for(c = m->clients; c; c = c->next)
1731                                         c->mon = m;
1732                         }
1733         }
1734
1735         /* reassign left over clients of disappeared monitors */
1736         for(tm = mons; tm; tm = tm->next) {
1737                 while((c = tm->clients)) {
1738                         detach(c);
1739                         detachstack(c);
1740                         c->mon = newmons;
1741                         attach(c);
1742                         attachstack(c);
1743                 }
1744         }
1745
1746         /* select focused monitor */
1747         if(!selmon) {
1748                 selmon = newmons;
1749                 int di, x, y;
1750                 unsigned int dui;
1751                 Window dummy;
1752                 if(XQueryPointer(dpy, root, &dummy, &dummy, &x, &y, &di, &di, &dui)) 
1753                         for(m = newmons; m; m = m->next)
1754                                 if(INRECT(x, y, m->wx, m->wy, m->ww, m->wh)) {
1755                                         selmon = m;
1756                                         break;
1757                                 }
1758         }
1759
1760         /* final assignment of new monitors */
1761         cleanupmons();
1762         mons = newmons;
1763 }
1764
1765 void
1766 updatenumlockmask(void) {
1767         unsigned int i, j;
1768         XModifierKeymap *modmap;
1769
1770         numlockmask = 0;
1771         modmap = XGetModifierMapping(dpy);
1772         for(i = 0; i < 8; i++)
1773                 for(j = 0; j < modmap->max_keypermod; j++)
1774                         if(modmap->modifiermap[i * modmap->max_keypermod + j]
1775                            == XKeysymToKeycode(dpy, XK_Num_Lock))
1776                                 numlockmask = (1 << i);
1777         XFreeModifiermap(modmap);
1778 }
1779
1780 void
1781 updatesizehints(Client *c) {
1782         long msize;
1783         XSizeHints size;
1784
1785         if(!XGetWMNormalHints(dpy, c->win, &size, &msize))
1786                 /* size is uninitialized, ensure that size.flags aren't used */
1787                 size.flags = PSize;
1788         if(size.flags & PBaseSize) {
1789                 c->basew = size.base_width;
1790                 c->baseh = size.base_height;
1791         }
1792         else if(size.flags & PMinSize) {
1793                 c->basew = size.min_width;
1794                 c->baseh = size.min_height;
1795         }
1796         else
1797                 c->basew = c->baseh = 0;
1798         if(size.flags & PResizeInc) {
1799                 c->incw = size.width_inc;
1800                 c->inch = size.height_inc;
1801         }
1802         else
1803                 c->incw = c->inch = 0;
1804         if(size.flags & PMaxSize) {
1805                 c->maxw = size.max_width;
1806                 c->maxh = size.max_height;
1807         }
1808         else
1809                 c->maxw = c->maxh = 0;
1810         if(size.flags & PMinSize) {
1811                 c->minw = size.min_width;
1812                 c->minh = size.min_height;
1813         }
1814         else if(size.flags & PBaseSize) {
1815                 c->minw = size.base_width;
1816                 c->minh = size.base_height;
1817         }
1818         else
1819                 c->minw = c->minh = 0;
1820         if(size.flags & PAspect) {
1821                 c->mina = (float)size.min_aspect.y / (float)size.min_aspect.x;
1822                 c->maxa = (float)size.max_aspect.x / (float)size.max_aspect.y;
1823         }
1824         else
1825                 c->maxa = c->mina = 0.0;
1826         c->isfixed = (c->maxw && c->minw && c->maxh && c->minh
1827                      && c->maxw == c->minw && c->maxh == c->minh);
1828 }
1829
1830 void
1831 updatetitle(Client *c) {
1832         if(!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
1833                 gettextprop(c->win, XA_WM_NAME, c->name, sizeof c->name);
1834 }
1835
1836 void
1837 updatestatus() {
1838         if(!gettextprop(root, XA_WM_NAME, stext, sizeof(stext)))
1839                 strcpy(stext, "dwm-"VERSION);
1840         drawbar(selmon);
1841 }
1842
1843 void
1844 updatewmhints(Client *c) {
1845         XWMHints *wmh;
1846
1847         if((wmh = XGetWMHints(dpy, c->win))) {
1848                 if(c == selmon->sel && wmh->flags & XUrgencyHint) {
1849                         wmh->flags &= ~XUrgencyHint;
1850                         XSetWMHints(dpy, c->win, wmh);
1851                 }
1852                 else
1853                         c->isurgent = (wmh->flags & XUrgencyHint) ? True : False;
1854
1855                 XFree(wmh);
1856         }
1857 }
1858
1859 void
1860 view(const Arg *arg) {
1861         if((arg->ui & TAGMASK) == selmon->tagset[selmon->seltags])
1862                 return;
1863         selmon->seltags ^= 1; /* toggle sel tagset */
1864         if(arg->ui & TAGMASK)
1865                 selmon->tagset[selmon->seltags] = arg->ui & TAGMASK;
1866         arrange();
1867 }
1868
1869 /* There's no way to check accesses to destroyed windows, thus those cases are
1870  * ignored (especially on UnmapNotify's).  Other types of errors call Xlibs
1871  * default error handler, which may call exit.  */
1872 int
1873 xerror(Display *dpy, XErrorEvent *ee) {
1874         if(ee->error_code == BadWindow
1875         || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1876         || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1877         || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1878         || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1879         || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1880         || (ee->request_code == X_GrabButton && ee->error_code == BadAccess)
1881         || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1882         || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1883                 return 0;
1884         fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1885                         ee->request_code, ee->error_code);
1886         return xerrorxlib(dpy, ee); /* may call exit */
1887 }
1888
1889 int
1890 xerrordummy(Display *dpy, XErrorEvent *ee) {
1891         return 0;
1892 }
1893
1894 /* Startup Error handler to check if another window manager
1895  * is already running. */
1896 int
1897 xerrorstart(Display *dpy, XErrorEvent *ee) {
1898         otherwm = True;
1899         return -1;
1900 }
1901
1902 void
1903 zoom(const Arg *arg) {
1904         Client *c = selmon->sel;
1905
1906         if(!lt[selmon->sellt]->arrange || lt[selmon->sellt]->arrange == monocle || (selmon->sel && selmon->sel->isfloating))
1907                 return;
1908         if(c == nexttiled(selmon->clients))
1909                 if(!c || !(c = nexttiled(c->next)))
1910                         return;
1911         detach(c);
1912         attach(c);
1913         focus(c);
1914         arrange();
1915 }
1916
1917 int
1918 main(int argc, char *argv[]) {
1919         if(argc == 2 && !strcmp("-v", argv[1]))
1920                 die("dwm-"VERSION", © 2006-2009 dwm engineers, see LICENSE for details\n");
1921         else if(argc != 1)
1922                 die("usage: dwm [-v]\n");
1923
1924         if(!setlocale(LC_CTYPE, "") || !XSupportsLocale())
1925                 fputs("warning: no locale support\n", stderr);
1926
1927         if(!(dpy = XOpenDisplay(NULL)))
1928                 die("dwm: cannot open display\n");
1929
1930         checkotherwm();
1931         setup();
1932         scan();
1933         run();
1934         cleanup();
1935
1936         XCloseDisplay(dpy);
1937         return 0;
1938 }