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