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