JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
fixed title rendering on non-active screen
[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) { /* status is only drawn on selected monitor */
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         }
656         else {
657                 dc.x = m->ww;
658         }
659         if((dc.w = dc.x - x) > bh) {
660                 dc.x = x;
661                 if(m->sel) {
662                         col = m == selmon ? dc.sel : dc.norm;
663                         drawtext(m->sel->name, col, False);
664                         drawsquare(m->sel->isfixed, m->sel->isfloating, False, col);
665                 }
666                 else
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;
832         Monitor *m;
833
834         for(m = mons; m; m = m->next)
835                 for(c = m->clients; c; c = c->next)
836                         if(c->win == w)
837                                 return c;
838         return NULL;
839 }
840
841 unsigned long
842 getcolor(const char *colstr) {
843         Colormap cmap = DefaultColormap(dpy, screen);
844         XColor color;
845
846         if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
847                 die("error, cannot allocate color '%s'\n", colstr);
848         return color.pixel;
849 }
850
851 long
852 getstate(Window w) {
853         int format, status;
854         long result = -1;
855         unsigned char *p = NULL;
856         unsigned long n, extra;
857         Atom real;
858
859         status = XGetWindowProperty(dpy, w, wmatom[WMState], 0L, 2L, False, wmatom[WMState],
860                         &real, &format, &n, &extra, (unsigned char **)&p);
861         if(status != Success)
862                 return -1;
863         if(n != 0)
864                 result = *p;
865         XFree(p);
866         return result;
867 }
868
869 Bool
870 gettextprop(Window w, Atom atom, char *text, unsigned int size) {
871         char **list = NULL;
872         int n;
873         XTextProperty name;
874
875         if(!text || size == 0)
876                 return False;
877         text[0] = '\0';
878         XGetTextProperty(dpy, w, &name, atom);
879         if(!name.nitems)
880                 return False;
881         if(name.encoding == XA_STRING)
882                 strncpy(text, (char *)name.value, size - 1);
883         else {
884                 if(XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success
885                 && n > 0 && *list) {
886                         strncpy(text, *list, size - 1);
887                         XFreeStringList(list);
888                 }
889         }
890         text[size - 1] = '\0';
891         XFree(name.value);
892         return True;
893 }
894
895 void
896 grabbuttons(Client *c, Bool focused) {
897         updatenumlockmask();
898         {
899                 unsigned int i, j;
900                 unsigned int modifiers[] = { 0, LockMask, numlockmask, numlockmask|LockMask };
901                 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
902                 if(focused) {
903                         for(i = 0; i < LENGTH(buttons); i++)
904                                 if(buttons[i].click == ClkClientWin)
905                                         for(j = 0; j < LENGTH(modifiers); j++)
906                                                 XGrabButton(dpy, buttons[i].button,
907                                                             buttons[i].mask | modifiers[j],
908                                                             c->win, False, BUTTONMASK,
909                                                             GrabModeAsync, GrabModeSync, None, None);
910                 } else
911                         XGrabButton(dpy, AnyButton, AnyModifier, c->win, False,
912                                     BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
913         }
914 }
915
916 void
917 grabkeys(void) {
918         updatenumlockmask();
919         { /* grab keys */
920                 unsigned int i, j;
921                 unsigned int modifiers[] = { 0, LockMask, numlockmask, numlockmask|LockMask };
922                 KeyCode code;
923
924                 XUngrabKey(dpy, AnyKey, AnyModifier, root);
925                 for(i = 0; i < LENGTH(keys); i++) {
926                         if((code = XKeysymToKeycode(dpy, keys[i].keysym)))
927                                 for(j = 0; j < LENGTH(modifiers); j++)
928                                         XGrabKey(dpy, code, keys[i].mod | modifiers[j], root,
929                                                  True, GrabModeAsync, GrabModeAsync);
930                 }
931         }
932 }
933
934 void
935 initfont(const char *fontstr) {
936         char *def, **missing;
937         int i, n;
938
939         missing = NULL;
940         dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
941         if(missing) {
942                 while(n--)
943                         fprintf(stderr, "dwm: missing fontset: %s\n", missing[n]);
944                 XFreeStringList(missing);
945         }
946         if(dc.font.set) {
947                 XFontSetExtents *font_extents;
948                 XFontStruct **xfonts;
949                 char **font_names;
950                 dc.font.ascent = dc.font.descent = 0;
951                 font_extents = XExtentsOfFontSet(dc.font.set);
952                 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
953                 for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
954                         dc.font.ascent = MAX(dc.font.ascent, (*xfonts)->ascent);
955                         dc.font.descent = MAX(dc.font.descent,(*xfonts)->descent);
956                         xfonts++;
957                 }
958         }
959         else {
960                 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr))
961                 && !(dc.font.xfont = XLoadQueryFont(dpy, "fixed")))
962                         die("error, cannot load font: '%s'\n", fontstr);
963                 dc.font.ascent = dc.font.xfont->ascent;
964                 dc.font.descent = dc.font.xfont->descent;
965         }
966         dc.font.height = dc.font.ascent + dc.font.descent;
967 }
968
969 Bool
970 isprotodel(Client *c) {
971         int i, n;
972         Atom *protocols;
973         Bool ret = False;
974
975         if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
976                 for(i = 0; !ret && i < n; i++)
977                         if(protocols[i] == wmatom[WMDelete])
978                                 ret = True;
979                 XFree(protocols);
980         }
981         return ret;
982 }
983
984 void
985 keypress(XEvent *e) {
986         unsigned int i;
987         KeySym keysym;
988         XKeyEvent *ev;
989
990         ev = &e->xkey;
991         keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
992         for(i = 0; i < LENGTH(keys); i++)
993                 if(keysym == keys[i].keysym
994                    && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state)
995                    && keys[i].func)
996                         keys[i].func(&(keys[i].arg));
997 }
998
999 void
1000 killclient(const Arg *arg) {
1001         XEvent ev;
1002
1003         if(!selmon->sel)
1004                 return;
1005         if(isprotodel(selmon->sel)) {
1006                 ev.type = ClientMessage;
1007                 ev.xclient.window = selmon->sel->win;
1008                 ev.xclient.message_type = wmatom[WMProtocols];
1009                 ev.xclient.format = 32;
1010                 ev.xclient.data.l[0] = wmatom[WMDelete];
1011                 ev.xclient.data.l[1] = CurrentTime;
1012                 XSendEvent(dpy, selmon->sel->win, False, NoEventMask, &ev);
1013         }
1014         else
1015                 XKillClient(dpy, selmon->sel->win);
1016 }
1017
1018 void
1019 manage(Window w, XWindowAttributes *wa) {
1020         static Client cz;
1021         Client *c, *t = NULL;
1022         Window trans = None;
1023         XWindowChanges wc;
1024
1025         if(!(c = malloc(sizeof(Client))))
1026                 die("fatal: could not malloc() %u bytes\n", sizeof(Client));
1027         *c = cz;
1028         c->win = w;
1029         c->mon = selmon;
1030
1031         /* geometry */
1032         c->x = wa->x;
1033         c->y = wa->y;
1034         c->w = wa->width;
1035         c->h = wa->height;
1036         c->oldbw = wa->border_width;
1037         if(c->w == sw && c->h == sh) {
1038                 c->x = sx;
1039                 c->y = sy;
1040                 c->bw = 0;
1041         }
1042         else {
1043                 if(c->x + WIDTH(c) > sx + sw)
1044                         c->x = sx + sw - WIDTH(c);
1045                 if(c->y + HEIGHT(c) > sy + sh)
1046                         c->y = sy + sh - HEIGHT(c);
1047                 c->x = MAX(c->x, sx);
1048                 /* only fix client y-offset, if the client center might cover the bar */
1049                 c->y = MAX(c->y, ((c->mon->by == 0) && (c->x + (c->w / 2) >= c->mon->wx)
1050                            && (c->x + (c->w / 2) < c->mon->wx + c->mon->ww)) ? bh : sy);
1051                 c->bw = borderpx;
1052         }
1053
1054         wc.border_width = c->bw;
1055         XConfigureWindow(dpy, w, CWBorderWidth, &wc);
1056         XSetWindowBorder(dpy, w, dc.norm[ColBorder]);
1057         configure(c); /* propagates border_width, if size doesn't change */
1058         updatesizehints(c);
1059         XSelectInput(dpy, w, EnterWindowMask|FocusChangeMask|PropertyChangeMask|StructureNotifyMask);
1060         grabbuttons(c, False);
1061         updatetitle(c);
1062         if(XGetTransientForHint(dpy, w, &trans))
1063                 t = getclient(trans);
1064         if(t)
1065                 c->tags = t->tags;
1066         else
1067                 applyrules(c);
1068         if(!c->isfloating)
1069                 c->isfloating = trans != None || c->isfixed;
1070         if(c->isfloating)
1071                 XRaiseWindow(dpy, c->win);
1072         attach(c);
1073         attachstack(c);
1074         XMoveResizeWindow(dpy, c->win, c->x + 2 * sw, c->y, c->w, c->h); /* some windows require this */
1075         XMapWindow(dpy, c->win);
1076         setclientstate(c, NormalState);
1077         arrange();
1078 }
1079
1080 void
1081 mappingnotify(XEvent *e) {
1082         XMappingEvent *ev = &e->xmapping;
1083
1084         XRefreshKeyboardMapping(ev);
1085         if(ev->request == MappingKeyboard)
1086                 grabkeys();
1087 }
1088
1089 void
1090 maprequest(XEvent *e) {
1091         static XWindowAttributes wa;
1092         XMapRequestEvent *ev = &e->xmaprequest;
1093
1094         if(!XGetWindowAttributes(dpy, ev->window, &wa))
1095                 return;
1096         if(wa.override_redirect)
1097                 return;
1098         if(!getclient(ev->window))
1099                 manage(ev->window, &wa);
1100 }
1101
1102 void
1103 monocle(Monitor *m) {
1104         Client *c;
1105
1106         for(c = nexttiled(m->clients); c; c = nexttiled(c->next))
1107                 resize(c, m->wx, m->wy, m->ww - 2 * c->bw, m->wh - 2 * c->bw);
1108 }
1109
1110 void
1111 movemouse(const Arg *arg) {
1112         int x, y, ocx, ocy, di, nx, ny;
1113         unsigned int dui;
1114         Client *c;
1115         Window dummy;
1116         XEvent ev;
1117
1118         if(!(c = selmon->sel))
1119                 return;
1120         restack(selmon);
1121         ocx = c->x;
1122         ocy = c->y;
1123         if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1124         None, cursor[CurMove], CurrentTime) != GrabSuccess)
1125                 return;
1126         XQueryPointer(dpy, root, &dummy, &dummy, &x, &y, &di, &di, &dui);
1127         do {
1128                 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
1129                 switch (ev.type) {
1130                 case ConfigureRequest:
1131                 case Expose:
1132                 case MapRequest:
1133                         handler[ev.type](&ev);
1134                         break;
1135                 case MotionNotify:
1136                         nx = ocx + (ev.xmotion.x - x);
1137                         ny = ocy + (ev.xmotion.y - y);
1138                         if(snap && nx >= selmon->wx && nx <= selmon->wx + selmon->ww
1139                                 && ny >= selmon->wy && ny <= selmon->wy + selmon->wh) {
1140                                 if(abs(selmon->wx - nx) < snap)
1141                                         nx = selmon->wx;
1142                                 else if(abs((selmon->wx + selmon->ww) - (nx + WIDTH(c))) < snap)
1143                                         nx = selmon->wx + selmon->ww - WIDTH(c);
1144                                 if(abs(selmon->wy - ny) < snap)
1145                                         ny = selmon->wy;
1146                                 else if(abs((selmon->wy + selmon->wh) - (ny + HEIGHT(c))) < snap)
1147                                         ny = selmon->wy + selmon->wh - HEIGHT(c);
1148                                 if(!c->isfloating && lt[selmon->sellt]->arrange
1149                                                   && (abs(nx - c->x) > snap || abs(ny - c->y) > snap))
1150                                         togglefloating(NULL);
1151                         }
1152                         if(!lt[selmon->sellt]->arrange || c->isfloating)
1153                                 resize(c, nx, ny, c->w, c->h);
1154                         break;
1155                 }
1156         }
1157         while(ev.type != ButtonRelease);
1158         XUngrabPointer(dpy, CurrentTime);
1159 }
1160
1161 Client *
1162 nexttiled(Client *c) {
1163         for(; c && (c->isfloating || !ISVISIBLE(c)); c = c->next);
1164         return c;
1165 }
1166
1167 void
1168 propertynotify(XEvent *e) {
1169         Client *c;
1170         Window trans;
1171         XPropertyEvent *ev = &e->xproperty;
1172
1173         if((ev->window == root) && (ev->atom == XA_WM_NAME))
1174                 updatestatus();
1175         else if(ev->state == PropertyDelete)
1176                 return; /* ignore */
1177         else if((c = getclient(ev->window))) {
1178                 switch (ev->atom) {
1179                 default: break;
1180                 case XA_WM_TRANSIENT_FOR:
1181                         XGetTransientForHint(dpy, c->win, &trans);
1182                         if(!c->isfloating && (c->isfloating = (getclient(trans) != NULL)))
1183                                 arrange();
1184                         break;
1185                 case XA_WM_NORMAL_HINTS:
1186                         updatesizehints(c);
1187                         break;
1188                 case XA_WM_HINTS:
1189                         updatewmhints(c);
1190                         drawbars();
1191                         break;
1192                 }
1193                 if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
1194                         updatetitle(c);
1195                         if(c == selmon->sel)
1196                                 drawbars();
1197                 }
1198         }
1199 }
1200
1201 void
1202 quit(const Arg *arg) {
1203         running = False;
1204 }
1205
1206 void
1207 resize(Client *c, int x, int y, int w, int h) {
1208         XWindowChanges wc;
1209
1210         if(applysizehints(c, &x, &y, &w, &h)) {
1211                 c->x = wc.x = x;
1212                 c->y = wc.y = y;
1213                 c->w = wc.width = w;
1214                 c->h = wc.height = h;
1215                 wc.border_width = c->bw;
1216                 XConfigureWindow(dpy, c->win,
1217                                 CWX|CWY|CWWidth|CWHeight|CWBorderWidth, &wc);
1218                 configure(c);
1219                 XSync(dpy, False);
1220         }
1221 }
1222
1223 void
1224 resizemouse(const Arg *arg) {
1225         int ocx, ocy;
1226         int nw, nh;
1227         Client *c;
1228         XEvent ev;
1229
1230         if(!(c = selmon->sel))
1231                 return;
1232         restack(selmon);
1233         ocx = c->x;
1234         ocy = c->y;
1235         if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1236         None, cursor[CurResize], CurrentTime) != GrabSuccess)
1237                 return;
1238         XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->bw - 1, c->h + c->bw - 1);
1239         do {
1240                 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
1241                 switch(ev.type) {
1242                 case ConfigureRequest:
1243                 case Expose:
1244                 case MapRequest:
1245                         handler[ev.type](&ev);
1246                         break;
1247                 case MotionNotify:
1248                         nw = MAX(ev.xmotion.x - ocx - 2 * c->bw + 1, 1);
1249                         nh = MAX(ev.xmotion.y - ocy - 2 * c->bw + 1, 1);
1250
1251                         if(snap && nw >= selmon->wx && nw <= selmon->wx + selmon->ww
1252                                 && nh >= selmon->wy && nh <= selmon->wy + selmon->wh) {
1253                                 if(!c->isfloating && lt[selmon->sellt]->arrange
1254                                    && (abs(nw - c->w) > snap || abs(nh - c->h) > snap))
1255                                         togglefloating(NULL);
1256                         }
1257                         if(!lt[selmon->sellt]->arrange || c->isfloating)
1258                                 resize(c, c->x, c->y, nw, nh);
1259                         break;
1260                 }
1261         }
1262         while(ev.type != ButtonRelease);
1263         XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->bw - 1, c->h + c->bw - 1);
1264         XUngrabPointer(dpy, CurrentTime);
1265         while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1266 }
1267
1268 void
1269 restack(Monitor *m) {
1270         Client *c;
1271         XEvent ev;
1272         XWindowChanges wc;
1273
1274         drawbars();
1275         if(!m->sel)
1276                 return;
1277         if(m->sel->isfloating || !lt[m->sellt]->arrange)
1278                 XRaiseWindow(dpy, m->sel->win);
1279         if(lt[m->sellt]->arrange) {
1280                 wc.stack_mode = Below;
1281                 wc.sibling = m->barwin;
1282                 for(c = m->stack; c; c = c->snext)
1283                         if(!c->isfloating && ISVISIBLE(c)) {
1284                                 XConfigureWindow(dpy, c->win, CWSibling|CWStackMode, &wc);
1285                                 wc.sibling = c->win;
1286                         }
1287         }
1288         XSync(dpy, False);
1289         while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1290 }
1291
1292 void
1293 run(void) {
1294         XEvent ev;
1295
1296         /* main event loop */
1297         XSync(dpy, False);
1298         while(running && !XNextEvent(dpy, &ev)) {
1299                 if(handler[ev.type])
1300                         (handler[ev.type])(&ev); /* call handler */
1301         }
1302 }
1303
1304 void
1305 scan(void) {
1306         unsigned int i, num;
1307         Window d1, d2, *wins = NULL;
1308         XWindowAttributes wa;
1309
1310         if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1311                 for(i = 0; i < num; i++) {
1312                         if(!XGetWindowAttributes(dpy, wins[i], &wa)
1313                         || wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1314                                 continue;
1315                         if(wa.map_state == IsViewable || getstate(wins[i]) == IconicState)
1316                                 manage(wins[i], &wa);
1317                 }
1318                 for(i = 0; i < num; i++) { /* now the transients */
1319                         if(!XGetWindowAttributes(dpy, wins[i], &wa))
1320                                 continue;
1321                         if(XGetTransientForHint(dpy, wins[i], &d1)
1322                         && (wa.map_state == IsViewable || getstate(wins[i]) == IconicState))
1323                                 manage(wins[i], &wa);
1324                 }
1325                 if(wins)
1326                         XFree(wins);
1327         }
1328 }
1329
1330 void
1331 setclientstate(Client *c, long state) {
1332         long data[] = {state, None};
1333
1334         XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1335                         PropModeReplace, (unsigned char *)data, 2);
1336 }
1337
1338 void
1339 setlayout(const Arg *arg) {
1340         if(!arg || !arg->v || arg->v != lt[selmon->sellt])
1341                 selmon->sellt ^= 1;
1342         if(arg && arg->v)
1343                 lt[selmon->sellt] = (Layout *)arg->v;
1344         if(selmon->sel)
1345                 arrange();
1346         else
1347                 drawbars();
1348 }
1349
1350 /* arg > 1.0 will set mfact absolutly */
1351 void
1352 setmfact(const Arg *arg) {
1353         float f;
1354
1355         if(!arg || !lt[selmon->sellt]->arrange)
1356                 return;
1357         f = arg->f < 1.0 ? arg->f + selmon->mfact : arg->f - 1.0;
1358         if(f < 0.1 || f > 0.9)
1359                 return;
1360         selmon->mfact = f;
1361         arrange();
1362 }
1363
1364 void
1365 setup(void) {
1366         unsigned int i;
1367         int w;
1368         XSetWindowAttributes wa;
1369
1370         /* init screen */
1371         screen = DefaultScreen(dpy);
1372         root = RootWindow(dpy, screen);
1373         initfont(font);
1374         sx = 0;
1375         sy = 0;
1376         sw = DisplayWidth(dpy, screen);
1377         sh = DisplayHeight(dpy, screen);
1378         bh = dc.h = dc.font.height + 2;
1379         lt[0] = &layouts[0];
1380         lt[1] = &layouts[1 % LENGTH(layouts)];
1381         updategeom();
1382
1383         /* init atoms */
1384         wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1385         wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1386         wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1387         netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1388         netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1389
1390         /* init cursors */
1391         cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1392         cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1393         cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1394
1395         /* init appearance */
1396         dc.norm[ColBorder] = getcolor(normbordercolor);
1397         dc.norm[ColBG] = getcolor(normbgcolor);
1398         dc.norm[ColFG] = getcolor(normfgcolor);
1399         dc.sel[ColBorder] = getcolor(selbordercolor);
1400         dc.sel[ColBG] = getcolor(selbgcolor);
1401         dc.sel[ColFG] = getcolor(selfgcolor);
1402         dc.drawable = XCreatePixmap(dpy, root, DisplayWidth(dpy, screen), bh, DefaultDepth(dpy, screen));
1403         dc.gc = XCreateGC(dpy, root, 0, NULL);
1404         XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
1405         if(!dc.font.set)
1406                 XSetFont(dpy, dc.gc, dc.font.xfont->fid);
1407
1408         /* init bars */
1409         for(blw = i = 0; LENGTH(layouts) > 1 && i < LENGTH(layouts); i++) {
1410                 w = TEXTW(layouts[i].symbol);
1411                 blw = MAX(blw, w);
1412         }
1413         updatebars();
1414         updatestatus();
1415
1416         /* EWMH support per view */
1417         XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1418                         PropModeReplace, (unsigned char *) netatom, NetLast);
1419
1420         /* select for events */
1421         wa.cursor = cursor[CurNormal];
1422         wa.event_mask = SubstructureRedirectMask|SubstructureNotifyMask|ButtonPressMask
1423                         |EnterWindowMask|LeaveWindowMask|StructureNotifyMask
1424                         |PropertyChangeMask;
1425         XChangeWindowAttributes(dpy, root, CWEventMask|CWCursor, &wa);
1426         XSelectInput(dpy, root, wa.event_mask);
1427
1428         grabkeys();
1429 }
1430
1431 void
1432 showhide(Client *c) {
1433         if(!c)
1434                 return;
1435         if(ISVISIBLE(c)) { /* show clients top down */
1436                 XMoveWindow(dpy, c->win, c->x, c->y);
1437                 if(!lt[c->mon->sellt]->arrange || c->isfloating)
1438                         resize(c, c->x, c->y, c->w, c->h);
1439                 showhide(c->snext);
1440         }
1441         else { /* hide clients bottom up */
1442                 showhide(c->snext);
1443                 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
1444         }
1445 }
1446
1447
1448 void
1449 sigchld(int signal) {
1450         while(0 < waitpid(-1, NULL, WNOHANG));
1451 }
1452
1453 void
1454 spawn(const Arg *arg) {
1455         signal(SIGCHLD, sigchld);
1456         if(fork() == 0) {
1457                 if(dpy)
1458                         close(ConnectionNumber(dpy));
1459                 setsid();
1460                 execvp(((char **)arg->v)[0], (char **)arg->v);
1461                 fprintf(stderr, "dwm: execvp %s", ((char **)arg->v)[0]);
1462                 perror(" failed");
1463                 exit(0);
1464         }
1465 }
1466
1467 void
1468 tag(const Arg *arg) {
1469         if(selmon->sel && arg->ui & TAGMASK) {
1470                 selmon->sel->tags = arg->ui & TAGMASK;
1471                 arrange();
1472         }
1473 }
1474
1475 #ifdef XINERAMA
1476 void
1477 tagmon(const Arg *arg) {
1478         unsigned int i;
1479         Client *c;
1480         Monitor *m;
1481
1482         if(!(c = selmon->sel))
1483                 return;
1484         for(i = 0, m = mons; m; m = m->next, i++)
1485                 if(i == arg->ui) {
1486                         detach(c);
1487                         detachstack(c);
1488                         c->mon = m;
1489                         attach(c);
1490                         attachstack(c);
1491                         selmon->sel = selmon->stack;
1492                         m->sel = c;
1493                         arrange();
1494                         break;
1495                 }
1496 }
1497 #endif /* XINERAMA */
1498
1499 int
1500 textnw(const char *text, unsigned int len) {
1501         XRectangle r;
1502
1503         if(dc.font.set) {
1504                 XmbTextExtents(dc.font.set, text, len, NULL, &r);
1505                 return r.width;
1506         }
1507         return XTextWidth(dc.font.xfont, text, len);
1508 }
1509
1510 void
1511 tile(Monitor *m) {
1512         int x, y, h, w, mw;
1513         unsigned int i, n;
1514         Client *c;
1515
1516         for(n = 0, c = nexttiled(m->clients); c; c = nexttiled(c->next), n++);
1517         if(n == 0)
1518                 return;
1519
1520         /* master */
1521         c = nexttiled(m->clients);
1522         mw = m->mfact * m->ww;
1523         resize(c, m->wx, m->wy, (n == 1 ? m->ww : mw) - 2 * c->bw, m->wh - 2 * c->bw);
1524
1525         if(--n == 0)
1526                 return;
1527
1528         /* tile stack */
1529         x = (m->wx + mw > c->x + c->w) ? c->x + c->w + 2 * c->bw : m->wx + mw;
1530         y = m->wy;
1531         w = (m->wx + mw > c->x + c->w) ? m->wx + m->ww - x : m->ww - mw;
1532         h = m->wh / n;
1533         if(h < bh)
1534                 h = m->wh;
1535
1536         for(i = 0, c = nexttiled(c->next); c; c = nexttiled(c->next), i++) {
1537                 resize(c, x, y, w - 2 * c->bw, /* remainder */ ((i + 1 == n)
1538                        ? m->wy + m->wh - y - 2 * c->bw : h - 2 * c->bw));
1539                 if(h != m->wh)
1540                         y = c->y + HEIGHT(c);
1541         }
1542 }
1543
1544 void
1545 togglebar(const Arg *arg) {
1546         selmon->showbar = !selmon->showbar;
1547         updatebarpos(selmon);
1548         XMoveResizeWindow(dpy, selmon->barwin, selmon->wx, selmon->by, selmon->ww, bh);
1549         arrange();
1550 }
1551
1552 void
1553 togglefloating(const Arg *arg) {
1554         if(!selmon->sel)
1555                 return;
1556         selmon->sel->isfloating = !selmon->sel->isfloating || selmon->sel->isfixed;
1557         if(selmon->sel->isfloating)
1558                 resize(selmon->sel, selmon->sel->x, selmon->sel->y, selmon->sel->w, selmon->sel->h);
1559         arrange();
1560 }
1561
1562 void
1563 toggletag(const Arg *arg) {
1564         unsigned int mask;
1565
1566         if(!selmon->sel)
1567                 return;
1568         
1569         mask = selmon->sel->tags ^ (arg->ui & TAGMASK);
1570         if(mask) {
1571                 selmon->sel->tags = mask;
1572                 arrange();
1573         }
1574 }
1575
1576 void
1577 toggleview(const Arg *arg) {
1578         unsigned int mask = selmon->tagset[selmon->seltags] ^ (arg->ui & TAGMASK);
1579
1580         if(mask) {
1581                 selmon->tagset[selmon->seltags] = mask;
1582                 arrange();
1583         }
1584 }
1585
1586 void
1587 unmanage(Client *c) {
1588         XWindowChanges wc;
1589
1590         wc.border_width = c->oldbw;
1591         /* The server grab construct avoids race conditions. */
1592         XGrabServer(dpy);
1593         XSetErrorHandler(xerrordummy);
1594         XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
1595         detach(c);
1596         detachstack(c);
1597         if(c->mon->sel == c) {
1598                 c->mon->sel = c->mon->stack;
1599                 focus(NULL);
1600         }
1601         XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1602         setclientstate(c, WithdrawnState);
1603         free(c);
1604         XSync(dpy, False);
1605         XSetErrorHandler(xerror);
1606         XUngrabServer(dpy);
1607         arrange();
1608 }
1609
1610 void
1611 unmapnotify(XEvent *e) {
1612         Client *c;
1613         XUnmapEvent *ev = &e->xunmap;
1614
1615         if((c = getclient(ev->window)))
1616                 unmanage(c);
1617 }
1618
1619 void
1620 updatebars(void) {
1621         Monitor *m;
1622         XSetWindowAttributes wa;
1623
1624         wa.override_redirect = True;
1625         wa.background_pixmap = ParentRelative;
1626         wa.event_mask = ButtonPressMask|ExposureMask;
1627
1628         for(m = mons; m; m = m->next) {
1629                 m->barwin = XCreateWindow(dpy, root, m->wx, m->by, m->ww, bh, 0, DefaultDepth(dpy, screen),
1630
1631                                           CopyFromParent, DefaultVisual(dpy, screen),
1632                                           CWOverrideRedirect|CWBackPixmap|CWEventMask, &wa);
1633                 XDefineCursor(dpy, m->barwin, cursor[CurNormal]);
1634                 XMapRaised(dpy, m->barwin);
1635         }
1636 }
1637
1638 void
1639 updatebarpos(Monitor *m) {
1640         m->wy = m->my;
1641         m->wh = m->mh;
1642         if(m->showbar) {
1643                 m->wh -= bh;
1644                 m->by = m->topbar ? m->wy : m->wy + m->wh;
1645                 m->wy = m->topbar ? m->wy + bh : m->wy;
1646         }
1647         else
1648                 m->by = -bh;
1649 }
1650
1651 void
1652 updategeom(void) {
1653         int i, di, n = 1, x, y;
1654         unsigned int dui;
1655         Client *c;
1656         Monitor *newmons = NULL, *m, *tm;
1657         Window dummy;
1658
1659 #ifdef XINULATOR
1660         n = 2;
1661 #elif defined(XINERAMA)
1662         XineramaScreenInfo *info = NULL;
1663
1664         if(XineramaIsActive(dpy))
1665                 info = XineramaQueryScreens(dpy, &n);
1666 #endif
1667         /* allocate monitor(s) for the new geometry setup */
1668         for(i = 0; i < n; i++) {
1669                 m = (Monitor *)malloc(sizeof(Monitor));
1670                 m->next = newmons;
1671                 newmons = m;
1672         }
1673
1674         /* initialise monitor(s) */
1675 #ifdef XINULATOR
1676         if(1) {
1677                 m = newmons;
1678                 m->screen_number = 0;
1679                 m->wx = sx;
1680                 m->my = m->wy = sy;
1681                 m->ww = sw;
1682                 m->mh = m->wh = sh / 2;
1683                 m = newmons->next;
1684                 m->screen_number = 1;
1685                 m->wx = sx;
1686                 m->my = m->wy = sy + sh / 2;
1687                 m->ww = sw;
1688                 m->mh = m->wh = sh / 2;
1689         }
1690         else
1691 #elif defined(XINERAMA)
1692         if(XineramaIsActive(dpy)) {
1693                 for(i = 0, m = newmons; m; m = m->next, i++) {
1694                         m->screen_number = info[i].screen_number;
1695                         m->wx = info[i].x_org;
1696                         m->my = m->wy = info[i].y_org;
1697                         m->ww = info[i].width;
1698                         m->mh = m->wh = info[i].height;
1699                 }
1700                 XFree(info);
1701         }
1702         else
1703 #endif
1704         /* default monitor setup */
1705         {
1706                 m->screen_number = 0;
1707                 m->wx = sx;
1708                 m->my = m->wy = sy;
1709                 m->ww = sw;
1710                 m->mh = m->wh = sh;
1711         }
1712
1713         /* bar geometry setup */
1714         for(m = newmons; m; m = m->next) {
1715                 /* TODO: consider removing the following values from config.h */
1716                 m->clients = NULL;
1717                 m->sel = NULL;
1718                 m->stack = NULL;
1719                 m->seltags = 0;
1720                 m->sellt = 0;
1721                 m->tagset[0] = m->tagset[1] = 1;
1722                 m->mfact = mfact;
1723                 m->showbar = showbar;
1724                 m->topbar = topbar;
1725                 updatebarpos(m);
1726         }
1727
1728         /* reassign left over clients of disappeared monitors */
1729         for(tm = mons; tm; tm = tm->next) {
1730                 while(tm->clients) {
1731                         c = tm->clients;
1732                         tm->clients = c->next;
1733                         detachstack(c);
1734                         c->mon = newmons;
1735                         attach(c);
1736                         attachstack(c);
1737                 }
1738         }
1739
1740         /* select focused monitor */
1741         selmon = newmons;
1742         if(XQueryPointer(dpy, root, &dummy, &dummy, &x, &y, &di, &di, &dui)) 
1743                 for(m = newmons; m; m = m->next)
1744                         if(INRECT(x, y, m->wx, m->wy, m->ww, m->wh)) {
1745                                 selmon = m;
1746                                 break;
1747                         }
1748
1749         /* final assignment of new monitors */
1750         cleanupmons();
1751         mons = newmons;
1752 }
1753
1754 void
1755 updatenumlockmask(void) {
1756         unsigned int i, j;
1757         XModifierKeymap *modmap;
1758
1759         numlockmask = 0;
1760         modmap = XGetModifierMapping(dpy);
1761         for(i = 0; i < 8; i++)
1762                 for(j = 0; j < modmap->max_keypermod; j++)
1763                         if(modmap->modifiermap[i * modmap->max_keypermod + j]
1764                            == XKeysymToKeycode(dpy, XK_Num_Lock))
1765                                 numlockmask = (1 << i);
1766         XFreeModifiermap(modmap);
1767 }
1768
1769 void
1770 updatesizehints(Client *c) {
1771         long msize;
1772         XSizeHints size;
1773
1774         if(!XGetWMNormalHints(dpy, c->win, &size, &msize))
1775                 /* size is uninitialized, ensure that size.flags aren't used */
1776                 size.flags = PSize;
1777         if(size.flags & PBaseSize) {
1778                 c->basew = size.base_width;
1779                 c->baseh = size.base_height;
1780         }
1781         else if(size.flags & PMinSize) {
1782                 c->basew = size.min_width;
1783                 c->baseh = size.min_height;
1784         }
1785         else
1786                 c->basew = c->baseh = 0;
1787         if(size.flags & PResizeInc) {
1788                 c->incw = size.width_inc;
1789                 c->inch = size.height_inc;
1790         }
1791         else
1792                 c->incw = c->inch = 0;
1793         if(size.flags & PMaxSize) {
1794                 c->maxw = size.max_width;
1795                 c->maxh = size.max_height;
1796         }
1797         else
1798                 c->maxw = c->maxh = 0;
1799         if(size.flags & PMinSize) {
1800                 c->minw = size.min_width;
1801                 c->minh = size.min_height;
1802         }
1803         else if(size.flags & PBaseSize) {
1804                 c->minw = size.base_width;
1805                 c->minh = size.base_height;
1806         }
1807         else
1808                 c->minw = c->minh = 0;
1809         if(size.flags & PAspect) {
1810                 c->mina = (float)size.min_aspect.y / (float)size.min_aspect.x;
1811                 c->maxa = (float)size.max_aspect.x / (float)size.max_aspect.y;
1812         }
1813         else
1814                 c->maxa = c->mina = 0.0;
1815         c->isfixed = (c->maxw && c->minw && c->maxh && c->minh
1816                      && c->maxw == c->minw && c->maxh == c->minh);
1817 }
1818
1819 void
1820 updatetitle(Client *c) {
1821         if(!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
1822                 gettextprop(c->win, XA_WM_NAME, c->name, sizeof c->name);
1823 }
1824
1825 void
1826 updatestatus() {
1827         if(!gettextprop(root, XA_WM_NAME, stext, sizeof(stext)))
1828                 strcpy(stext, "dwm-"VERSION);
1829         drawbar(selmon);
1830 }
1831
1832 void
1833 updatewmhints(Client *c) {
1834         XWMHints *wmh;
1835
1836         if((wmh = XGetWMHints(dpy, c->win))) {
1837                 if(c == selmon->sel && wmh->flags & XUrgencyHint) {
1838                         wmh->flags &= ~XUrgencyHint;
1839                         XSetWMHints(dpy, c->win, wmh);
1840                 }
1841                 else
1842                         c->isurgent = (wmh->flags & XUrgencyHint) ? True : False;
1843
1844                 XFree(wmh);
1845         }
1846 }
1847
1848 void
1849 view(const Arg *arg) {
1850         if((arg->ui & TAGMASK) == selmon->tagset[selmon->seltags])
1851                 return;
1852         selmon->seltags ^= 1; /* toggle sel tagset */
1853         if(arg->ui & TAGMASK)
1854                 selmon->tagset[selmon->seltags] = arg->ui & TAGMASK;
1855         arrange();
1856 }
1857
1858 /* There's no way to check accesses to destroyed windows, thus those cases are
1859  * ignored (especially on UnmapNotify's).  Other types of errors call Xlibs
1860  * default error handler, which may call exit.  */
1861 int
1862 xerror(Display *dpy, XErrorEvent *ee) {
1863         if(ee->error_code == BadWindow
1864         || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1865         || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1866         || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1867         || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1868         || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1869         || (ee->request_code == X_GrabButton && ee->error_code == BadAccess)
1870         || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1871         || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1872                 return 0;
1873         fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1874                         ee->request_code, ee->error_code);
1875         return xerrorxlib(dpy, ee); /* may call exit */
1876 }
1877
1878 int
1879 xerrordummy(Display *dpy, XErrorEvent *ee) {
1880         return 0;
1881 }
1882
1883 /* Startup Error handler to check if another window manager
1884  * is already running. */
1885 int
1886 xerrorstart(Display *dpy, XErrorEvent *ee) {
1887         otherwm = True;
1888         return -1;
1889 }
1890
1891 void
1892 zoom(const Arg *arg) {
1893         Client *c = selmon->sel;
1894
1895         if(!lt[selmon->sellt]->arrange || lt[selmon->sellt]->arrange == monocle || (selmon->sel && selmon->sel->isfloating))
1896                 return;
1897         if(c == nexttiled(selmon->clients))
1898                 if(!c || !(c = nexttiled(c->next)))
1899                         return;
1900         detach(c);
1901         attach(c);
1902         focus(c);
1903         arrange();
1904 }
1905
1906 int
1907 main(int argc, char *argv[]) {
1908         if(argc == 2 && !strcmp("-v", argv[1]))
1909                 die("dwm-"VERSION", © 2006-2009 dwm engineers, see LICENSE for details\n");
1910         else if(argc != 1)
1911                 die("usage: dwm [-v]\n");
1912
1913         if(!setlocale(LC_CTYPE, "") || !XSupportsLocale())
1914                 fputs("warning: no locale support\n", stderr);
1915
1916         if(!(dpy = XOpenDisplay(NULL)))
1917                 die("dwm: cannot open display\n");
1918
1919         checkotherwm();
1920         setup();
1921         scan();
1922         run();
1923         cleanup();
1924
1925         XCloseDisplay(dpy);
1926         return 0;
1927 }