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