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