JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
document open/close focus predictability
[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                         // this window is should not be visible. move off top, but don't change h/w
1209                         resize(c, m->wx, m->wy - 4000, c->w, c->h, False, 0);
1210                 }
1211         }
1212 }
1213
1214 void
1215 motionnotify(XEvent *e) {
1216         static Monitor *mon = NULL;
1217         Monitor *m;
1218         XMotionEvent *ev = &e->xmotion;
1219
1220         if(ev->window != root)
1221                 return;
1222         if((m = recttomon(ev->x_root, ev->y_root, 1, 1)) != mon && mon) {
1223                 unfocus(selmon->sel, True);
1224                 selmon = m;
1225                 focus(NULL);
1226         }
1227         mon = m;
1228 }
1229
1230 void
1231 movemouse(const Arg *arg) {
1232         int x, y, ocx, ocy, nx, ny;
1233         Client *c;
1234         Monitor *m;
1235         XEvent ev;
1236         Time lasttime = 0;
1237
1238         if(!(c = selmon->sel))
1239                 return;
1240         if(c->isfullscreen) /* no support moving fullscreen windows by mouse */
1241                 return;
1242         restack(selmon);
1243         ocx = c->x;
1244         ocy = c->y;
1245         if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1246         None, cursor[CurMove]->cursor, CurrentTime) != GrabSuccess)
1247                 return;
1248         if(!getrootptr(&x, &y))
1249                 return;
1250         do {
1251                 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
1252                 switch(ev.type) {
1253                 case ConfigureRequest:
1254                 case Expose:
1255                 case MapRequest:
1256                         handler[ev.type](&ev);
1257                         break;
1258                 case MotionNotify:
1259                         if ((ev.xmotion.time - lasttime) <= (1000 / 60))
1260                                 continue;
1261                         lasttime = ev.xmotion.time;
1262
1263                         nx = ocx + (ev.xmotion.x - x);
1264                         ny = ocy + (ev.xmotion.y - y);
1265                         if(nx >= selmon->wx && nx <= selmon->wx + selmon->ww
1266                         && ny >= selmon->wy && ny <= selmon->wy + selmon->wh) {
1267                                 if(abs(selmon->wx - nx) < snap)
1268                                         nx = selmon->wx;
1269                                 else if(abs((selmon->wx + selmon->ww) - (nx + WIDTH(c))) < snap)
1270                                         nx = selmon->wx + selmon->ww - WIDTH(c);
1271                                 if(abs(selmon->wy - ny) < snap)
1272                                         ny = selmon->wy;
1273                                 else if(abs((selmon->wy + selmon->wh) - (ny + HEIGHT(c))) < snap)
1274                                         ny = selmon->wy + selmon->wh - HEIGHT(c);
1275                                 if(!c->isfloating && selmon->lt[selmon->sellt]->arrange
1276                                 && (abs(nx - c->x) > snap || abs(ny - c->y) > snap))
1277                                         togglefloating(NULL);
1278                         }
1279                         if(!selmon->lt[selmon->sellt]->arrange || c->isfloating)
1280                                 resize(c, nx, ny, c->w, c->h, True, 0);
1281                         break;
1282                 }
1283         } while(ev.type != ButtonRelease);
1284         XUngrabPointer(dpy, CurrentTime);
1285         if((m = recttomon(c->x, c->y, c->w, c->h)) != selmon) {
1286                 sendmon(c, m);
1287                 selmon = m;
1288                 focus(NULL);
1289         }
1290 }
1291
1292 Client *
1293 nexttiled(Client *c) {
1294         for(; c && (c->isfloating || !ISVISIBLE(c)); c = c->next);
1295         return c;
1296 }
1297
1298 Client *
1299 snexttiled(Client *c) {
1300         for(; c && (c->isfloating || !ISVISIBLE(c)); c = c->snext);
1301         return c;
1302 }
1303
1304 Client *
1305 nextvisible(Client *c) {
1306         for(; c && !ISVISIBLE(c); c = c->next);
1307         return c;
1308 }
1309
1310 void
1311 pop(Client *c) {
1312         detach(c);
1313         attach_as_master(c);
1314         focus(c);
1315         arrange(c->mon);
1316 }
1317
1318 void
1319 propertynotify(XEvent *e) {
1320         Client *c;
1321         Window trans;
1322         XPropertyEvent *ev = &e->xproperty;
1323
1324         if((ev->window == root) && (ev->atom == XA_WM_NAME))
1325                 updatestatus();
1326         else if(ev->state == PropertyDelete)
1327                 return; /* ignore */
1328         else if((c = wintoclient(ev->window))) {
1329                 switch(ev->atom) {
1330                 default: break;
1331                 case XA_WM_TRANSIENT_FOR:
1332                         if(!c->isfloating && (XGetTransientForHint(dpy, c->win, &trans)) &&
1333                            (c->isfloating = (wintoclient(trans)) != NULL))
1334                                 arrange(c->mon);
1335                         break;
1336                 case XA_WM_NORMAL_HINTS:
1337                         updatesizehints(c);
1338                         break;
1339                 case XA_WM_HINTS:
1340                         updatewmhints(c);
1341                         drawbars();
1342                         break;
1343                 }
1344                 if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
1345                         updatetitle(c);
1346                         if(c == c->mon->sel)
1347                                 drawbar(c->mon);
1348                 }
1349                 if(ev->atom == netatom[NetWMWindowType])
1350                         updatewindowtype(c);
1351         }
1352 }
1353
1354 void
1355 quit(const Arg *arg) {
1356         running = False;
1357 }
1358
1359 Monitor *
1360 recttomon(int x, int y, int w, int h) {
1361         Monitor *m, *r = selmon;
1362         int a, area = 0;
1363
1364         for(m = mons; m; m = m->next)
1365                 if((a = INTERSECT(x, y, w, h, m)) > area) {
1366                         area = a;
1367                         r = m;
1368                 }
1369         return r;
1370 }
1371
1372 void
1373 resize(Client *c, int x, int y, int w, int h, Bool interact, Client *base) {
1374         if(applysizehints(c, &x, &y, &w, &h, interact))
1375                 resizeclient(c, x, y, w, h, base);
1376 }
1377
1378 void
1379 resizeclient(Client *c, int x, int y, int w, int h, Client *base) {
1380         XWindowChanges wc;
1381         unsigned long mask = CWX|CWY|CWWidth|CWHeight|CWBorderWidth;
1382
1383         c->oldx = c->x; c->x = wc.x = x;
1384         c->oldy = c->y; c->y = wc.y = y;
1385         c->oldw = c->w; c->w = wc.width = w;
1386         c->oldh = c->h; c->h = wc.height = h;
1387         // base = 0;
1388         if (base) {
1389                 wc.stack_mode = Above;
1390                 wc.sibling = base->win;
1391                 mask |= CWStackMode|CWSibling;
1392         }
1393         wc.border_width = c->bw;
1394         XConfigureWindow(dpy, c->win, mask, &wc);
1395         configure(c);
1396         XSync(dpy, False);
1397 }
1398
1399 void
1400 resizemouse(const Arg *arg) {
1401         int ocx, ocy, nw, nh;
1402         Client *c;
1403         Monitor *m;
1404         XEvent ev;
1405         Time lasttime = 0;
1406
1407         if(!(c = selmon->sel))
1408                 return;
1409         if(c->isfullscreen) /* no support resizing fullscreen windows by mouse */
1410                 return;
1411         restack(selmon);
1412         ocx = c->x;
1413         ocy = c->y;
1414         if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1415                         None, cursor[CurResize]->cursor, CurrentTime) != GrabSuccess)
1416                 return;
1417         XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->bw - 1, c->h + c->bw - 1);
1418         do {
1419                 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
1420                 switch(ev.type) {
1421                 case ConfigureRequest:
1422                 case Expose:
1423                 case MapRequest:
1424                         handler[ev.type](&ev);
1425                         break;
1426                 case MotionNotify:
1427                         if ((ev.xmotion.time - lasttime) <= (1000 / 60))
1428                                 continue;
1429                         lasttime = ev.xmotion.time;
1430
1431                         nw = MAX(ev.xmotion.x - ocx - 2 * c->bw + 1, 1);
1432                         nh = MAX(ev.xmotion.y - ocy - 2 * c->bw + 1, 1);
1433                         if(c->mon->wx + nw >= selmon->wx && c->mon->wx + nw <= selmon->wx + selmon->ww
1434                         && c->mon->wy + nh >= selmon->wy && c->mon->wy + nh <= selmon->wy + selmon->wh)
1435                         {
1436                                 if(!c->isfloating && selmon->lt[selmon->sellt]->arrange
1437                                 && (abs(nw - c->w) > snap || abs(nh - c->h) > snap))
1438                                         togglefloating(NULL);
1439                         }
1440                         if(!selmon->lt[selmon->sellt]->arrange || c->isfloating)
1441                                 resize(c, c->x, c->y, nw, nh, True, 0);
1442                         break;
1443                 }
1444         } while(ev.type != ButtonRelease);
1445         XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->bw - 1, c->h + c->bw - 1);
1446         XUngrabPointer(dpy, CurrentTime);
1447         while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1448         if((m = recttomon(c->x, c->y, c->w, c->h)) != selmon) {
1449                 sendmon(c, m);
1450                 selmon = m;
1451                 focus(NULL);
1452         }
1453 }
1454
1455 void
1456 restack(Monitor *m) {
1457         Client *c;
1458         XEvent ev;
1459         XWindowChanges wc;
1460
1461         drawbar(m);
1462         if(!m->sel)
1463                 return;
1464         if(m->sel->isfloating || !m->lt[m->sellt]->arrange)
1465                 XRaiseWindow(dpy, m->sel->win);
1466         if(m->lt[m->sellt]->arrange) {
1467                 wc.stack_mode = Below;
1468                 wc.sibling = m->barwin;
1469                 for(c = m->clients; c; c = c->next)
1470                         if(!c->isfloating && ISVISIBLE(c)) {
1471                                 XConfigureWindow(dpy, c->win, CWSibling|CWStackMode, &wc);
1472                                 wc.sibling = c->win;
1473                                 wc.stack_mode = Above;
1474                         }
1475         }
1476         XSync(dpy, False);
1477         while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1478 }
1479
1480 void
1481 run(void) {
1482         XEvent ev;
1483         /* main event loop */
1484         XSync(dpy, False);
1485         while(running && !XNextEvent(dpy, &ev))
1486                 if(handler[ev.type])
1487                         handler[ev.type](&ev); /* call handler */
1488 }
1489
1490 void
1491 scan(void) {
1492         unsigned int i, num;
1493         Window d1, d2, *wins = NULL;
1494         XWindowAttributes wa;
1495
1496         if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1497                 for(i = 0; i < num; i++) {
1498                         if(!XGetWindowAttributes(dpy, wins[i], &wa)
1499                         || wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1500                                 continue;
1501                         if(wa.map_state == IsViewable || getstate(wins[i]) == IconicState)
1502                                 manage(wins[i], &wa);
1503                 }
1504                 for(i = 0; i < num; i++) { /* now the transients */
1505                         if(!XGetWindowAttributes(dpy, wins[i], &wa))
1506                                 continue;
1507                         if(XGetTransientForHint(dpy, wins[i], &d1)
1508                         && (wa.map_state == IsViewable || getstate(wins[i]) == IconicState))
1509                                 manage(wins[i], &wa);
1510                 }
1511                 if(wins)
1512                         XFree(wins);
1513         }
1514 }
1515
1516 void
1517 sendmon(Client *c, Monitor *m) {
1518         if(c->mon == m)
1519                 return;
1520         unfocus(c, True);
1521         detachstack(c);
1522         detach(c);
1523         c->mon = m;
1524         c->tags = m->tagset[m->seltags]; /* assign tags of target monitor */
1525         attach(c);
1526         attachstack(c);
1527         focus(NULL);
1528         arrange(NULL);
1529 }
1530
1531 void
1532 setclientstate(Client *c, long state) {
1533         long data[] = { state, None };
1534
1535         XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1536                         PropModeReplace, (unsigned char *)data, 2);
1537 }
1538
1539 Bool
1540 sendevent(Client *c, Atom proto) {
1541         int n;
1542         Atom *protocols;
1543         Bool exists = False;
1544         XEvent ev;
1545
1546         if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
1547                 while(!exists && n--)
1548                         exists = protocols[n] == proto;
1549                 XFree(protocols);
1550         }
1551         if(exists) {
1552                 ev.type = ClientMessage;
1553                 ev.xclient.window = c->win;
1554                 ev.xclient.message_type = wmatom[WMProtocols];
1555                 ev.xclient.format = 32;
1556                 ev.xclient.data.l[0] = proto;
1557                 ev.xclient.data.l[1] = CurrentTime;
1558                 XSendEvent(dpy, c->win, False, NoEventMask, &ev);
1559         }
1560         return exists;
1561 }
1562
1563 void
1564 setfocus(Client *c) {
1565         if(!c->neverfocus) {
1566                 XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
1567                 XChangeProperty(dpy, root, netatom[NetActiveWindow],
1568                                 XA_WINDOW, 32, PropModeReplace,
1569                                 (unsigned char *) &(c->win), 1);
1570         }
1571         sendevent(c, wmatom[WMTakeFocus]);
1572 }
1573
1574 void
1575 setfullscreen(Client *c, Bool fullscreen) {
1576         if(fullscreen) {
1577                 XChangeProperty(dpy, c->win, netatom[NetWMState], XA_ATOM, 32,
1578                                 PropModeReplace, (unsigned char*)&netatom[NetWMFullscreen], 1);
1579                 c->isfullscreen = True;
1580                 c->oldstate = c->isfloating;
1581                 c->oldbw = c->bw;
1582                 c->bw = 0;
1583                 c->isfloating = True;
1584                 resizeclient(c, c->mon->mx, c->mon->my, c->mon->mw, c->mon->mh, 0);
1585                 XRaiseWindow(dpy, c->win);
1586         }
1587         else {
1588                 XChangeProperty(dpy, c->win, netatom[NetWMState], XA_ATOM, 32,
1589                                 PropModeReplace, (unsigned char*)0, 0);
1590                 c->isfullscreen = False;
1591                 c->isfloating = c->oldstate;
1592                 c->bw = c->oldbw;
1593                 c->x = c->oldx;
1594                 c->y = c->oldy;
1595                 c->w = c->oldw;
1596                 c->h = c->oldh;
1597                 resizeclient(c, c->x, c->y, c->w, c->h, 0);
1598                 arrange(c->mon);
1599         }
1600 }
1601
1602 void
1603 setlayout(const Arg *arg) {
1604         if(!arg || !arg->v || arg->v != selmon->lt[selmon->sellt])
1605                 selmon->sellt ^= 1;
1606         if(arg && arg->v)
1607                 selmon->lt[selmon->sellt] = (Layout *)arg->v;
1608         strncpy(selmon->ltsymbol, selmon->lt[selmon->sellt]->symbol, sizeof selmon->ltsymbol);
1609         if(selmon->sel)
1610                 arrange(selmon);
1611         else
1612                 drawbar(selmon);
1613 }
1614
1615 /* arg > 1.0 will set mfact absolutly */
1616 void
1617 setmfact(const Arg *arg) {
1618         float f;
1619
1620         if(!arg || !selmon->lt[selmon->sellt]->arrange)
1621                 return;
1622         f = arg->f < 1.0 ? arg->f + selmon->mfact : arg->f - 1.0;
1623         if(f < 0.1 || f > 0.9)
1624                 return;
1625         selmon->mfact = f;
1626         arrange(selmon);
1627 }
1628
1629 void
1630 setup(void) {
1631         XSetWindowAttributes wa;
1632
1633         /* clean up any zombies immediately */
1634         sigchld(0);
1635
1636         /* init screen */
1637         screen = DefaultScreen(dpy);
1638         root = RootWindow(dpy, screen);
1639         fnt = drw_font_create(dpy, font);
1640         sw = DisplayWidth(dpy, screen);
1641         sh = DisplayHeight(dpy, screen);
1642         bh = fnt->h + 2;
1643         drw = drw_create(dpy, screen, root, sw, sh);
1644         drw_setfont(drw, fnt);
1645         updategeom();
1646         /* init atoms */
1647         wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1648         wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1649         wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1650         wmatom[WMTakeFocus] = XInternAtom(dpy, "WM_TAKE_FOCUS", False);
1651         netatom[NetActiveWindow] = XInternAtom(dpy, "_NET_ACTIVE_WINDOW", False);
1652         netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1653         netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1654         netatom[NetWMState] = XInternAtom(dpy, "_NET_WM_STATE", False);
1655         netatom[NetWMFullscreen] = XInternAtom(dpy, "_NET_WM_STATE_FULLSCREEN", False);
1656         netatom[NetWMWindowOpacity] = XInternAtom(dpy, "_NET_WM_WINDOW_OPACITY", False);
1657         netatom[NetWMWindowType] = XInternAtom(dpy, "_NET_WM_WINDOW_TYPE", False);
1658         netatom[NetWMWindowTypeDialog] = XInternAtom(dpy, "_NET_WM_WINDOW_TYPE_DIALOG", False);
1659         netatom[NetClientList] = XInternAtom(dpy, "_NET_CLIENT_LIST", False);
1660         netatom[NetSupportingWMCheck] = XInternAtom(dpy, "_NET_SUPPORTING_WM_CHECK", False);
1661         /* init cursors */
1662         cursor[CurNormal] = drw_cur_create(drw, XC_left_ptr);
1663         cursor[CurResize] = drw_cur_create(drw, XC_sizing);
1664         cursor[CurMove] = drw_cur_create(drw, XC_fleur);
1665         /* init appearance */
1666         scheme[SchemeNorm].border = drw_clr_create(drw, normbordercolor);
1667         scheme[SchemeNorm].bg = drw_clr_create(drw, normbgcolor);
1668         scheme[SchemeNorm].fg = drw_clr_create(drw, normfgcolor);
1669         scheme[SchemeSel].border = drw_clr_create(drw, selbordercolor);
1670         scheme[SchemeSel].bg = drw_clr_create(drw, selbgcolor);
1671         scheme[SchemeSel].fg = drw_clr_create(drw, selfgcolor);
1672         /* init bars */
1673         updatebars();
1674         updatestatus();
1675         /* EWMH support per view */
1676         XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1677                         PropModeReplace, (unsigned char *) netatom, NetLast);
1678         XDeleteProperty(dpy, root, netatom[NetClientList]);
1679         /* select for events */
1680         wa.cursor = cursor[CurNormal]->cursor;
1681         wa.event_mask = SubstructureRedirectMask|SubstructureNotifyMask|ButtonPressMask|PointerMotionMask
1682                         |EnterWindowMask|LeaveWindowMask|StructureNotifyMask|PropertyChangeMask;
1683         XChangeWindowAttributes(dpy, root, CWEventMask|CWCursor, &wa);
1684         XSelectInput(dpy, root, wa.event_mask);
1685         grabkeys();
1686         focus(NULL);
1687 }
1688
1689 void
1690 showhide(Client *c) {
1691         if(!c)
1692                 return;
1693         if(ISVISIBLE(c)) { /* show clients top down */
1694                 XMoveWindow(dpy, c->win, c->x, c->y);
1695                 if((!c->mon->lt[c->mon->sellt]->arrange || c->isfloating) && !c->isfullscreen)
1696                         resize(c, c->x, c->y, c->w, c->h, False, 0);
1697                 showhide(c->snext);
1698         }
1699         else { /* hide clients bottom up */
1700                 showhide(c->snext);
1701                 XMoveWindow(dpy, c->win, WIDTH(c) * -2, c->y);
1702         }
1703 }
1704
1705 void
1706 sigchld(int unused) {
1707         if(signal(SIGCHLD, sigchld) == SIG_ERR)
1708                 die("Can't install SIGCHLD handler");
1709         while(0 < waitpid(-1, NULL, WNOHANG));
1710 }
1711
1712 void
1713 spawn(const Arg *arg) {
1714         int tag = 0, i;
1715         if(arg->v == termcmd) {
1716                 for(i = 0; i < 32; ++i) {
1717                         if(selmon->tagset[selmon->seltags] & (1 << i)) {
1718                                 tag = i;
1719                                 break;
1720                         }
1721                 }
1722                 WORKSPACE_NUMBER[17] = workspace_numbers_str[tag][0];
1723                 WORKSPACE_NUMBER[18] = workspace_numbers_str[tag][1];
1724         }
1725         if(arg->v == dmenucmd)
1726                 dmenumon[0] = '0' + selmon->num;
1727         if(fork() == 0) {
1728                 if(dpy)
1729                         close(ConnectionNumber(dpy));
1730                 setsid();
1731                 execvp(((char **)arg->v)[0], (char **)arg->v);
1732                 fprintf(stderr, "dwm: execvp %s", ((char **)arg->v)[0]);
1733                 perror(" failed");
1734                 exit(EXIT_SUCCESS);
1735         }
1736 }
1737
1738 void
1739 tag(const Arg *arg) {
1740         if(selmon->sel && arg->ui & TAGMASK) {
1741                 selmon->sel->tags = arg->ui & TAGMASK;
1742                 focus(NULL);
1743                 arrange(selmon);
1744         }
1745 }
1746
1747 void
1748 tagmon(const Arg *arg) {
1749         if(!selmon->sel || !mons->next)
1750                 return;
1751         sendmon(selmon->sel, dirtomon(arg->i));
1752 }
1753
1754 void
1755 tile(Monitor *m) {
1756         unsigned int i, n, h, mw, my, ty;
1757         Client *c;
1758
1759         for(n = 0, c = nexttiled(m->clients); c; c = nexttiled(c->next), n++);
1760         if(n == 0)
1761                 return;
1762
1763         if(n > m->nmaster)
1764                 mw = m->nmaster ? m->ww * m->mfact : 0;
1765         else {
1766                 c = nexttiled(m->clients);
1767                 if (c && !c->screen_hog)
1768                         mw = m->ww * m->mfact;
1769                 else
1770                         mw = m->ww;
1771         }
1772         for(i = my = ty = 0, c = nexttiled(m->clients); c; c = nexttiled(c->next), i++)
1773                 if(i < m->nmaster) {
1774                         h = (m->wh - my) / (MIN(n, m->nmaster) - i);
1775                         resize(c, m->wx, m->wy + my, mw - (2*c->bw), h - (2*c->bw), False, 0);
1776                         my += HEIGHT(c);
1777                 }
1778                 else {
1779                         h = (m->wh - ty) / (n - i);
1780                         resize(c, m->wx + mw, m->wy + ty, m->ww - mw - (2*c->bw), h - (2*c->bw), False, 0);
1781                         ty += HEIGHT(c);
1782                 }
1783 }
1784
1785 #define TAB_HEIGHT 19
1786 #define TAB_PAD     7
1787
1788 void
1789 jason_layout(Monitor *m) {
1790         unsigned int i, tiled_count, mw, right_width, tab_counts[2] = {0,0}, cur_tab = 0, *tab_count;
1791         int tab_top;
1792         Client *c, *vis_slave = 0, *base = 0;
1793
1794         tab_count = &(tab_counts[0]);
1795
1796         for(tiled_count = 0, c = nexttiled(m->clients); c; c = nexttiled(c->next), tiled_count++) {
1797                 if (tiled_count == 0) { // master
1798                         if (c->next) {
1799                                 if (m->sel && (m->sel == c || m->sel->isfloating || !ISVISIBLE(m->sel))) {
1800                                         vis_slave = nexttiled(c->next);
1801                                 } else {
1802                                         vis_slave = m->sel;
1803                                 }
1804                         }
1805                 } else {
1806                         if (c == vis_slave) {
1807                                 tab_count = &(tab_counts[1]);
1808                         } else {
1809                                 (*tab_count) += 1;
1810                         }
1811                 }
1812         }
1813         if(tiled_count == 0) {
1814                 return;
1815         }
1816
1817         if(tiled_count > 1 || (tiled_count == 1 && !nexttiled(m->clients)->screen_hog)) {
1818                 mw = m->ww * m->mfact;
1819         } else {
1820                 mw = m->ww;
1821         }
1822         right_width = m->ww - mw;
1823         tab_count = &(tab_counts[0]);
1824         tab_top = m->wy - (m->wh - (2 * (TAB_HEIGHT + TAB_PAD))) + TAB_HEIGHT;
1825         for (i = 0, c = nexttiled(m->clients); c; c = nexttiled(c->next), i++) {
1826                 if (i == 0) {
1827                         resize(c, m->wx, m->wy, mw, m->wh, False, 0);
1828                 } else {
1829                         if (c == vis_slave) {
1830                                 resize(c, m->wx + mw, m->wy + TAB_HEIGHT + TAB_PAD, right_width, m->wh - 2 * (TAB_HEIGHT + TAB_PAD), False, base);
1831                                 tab_count = &(tab_counts[1]);
1832                                 tab_top = m->wy + m->wh - TAB_HEIGHT;
1833                                 cur_tab = 0;
1834                         } else {
1835                                 // this function does not get called when focus changes
1836                                 // resize(c, m->wx + m->ww, m->wy, m->ww - mw, m->wh, False);
1837                                 resize(c, m->wx + mw + right_width * cur_tab / (*tab_count), tab_top, right_width, m->wh - 2 * (TAB_HEIGHT + TAB_PAD), False, base);
1838                                 cur_tab += 1;
1839                         }
1840                 }
1841                 base = c;
1842         }
1843 }
1844
1845 void
1846 togglebar(const Arg *arg) {
1847         selmon->showbar = !selmon->showbar;
1848         updatebarpos(selmon);
1849         XMoveResizeWindow(dpy, selmon->barwin, selmon->wx, selmon->by, selmon->ww, bh);
1850         arrange(selmon);
1851 }
1852
1853 void
1854 togglefloating(const Arg *arg) {
1855         if(!selmon->sel)
1856                 return;
1857         if(selmon->sel->isfullscreen) /* no support for fullscreen windows */
1858                 return;
1859         selmon->sel->isfloating = !selmon->sel->isfloating || selmon->sel->isfixed;
1860         if(selmon->sel->isfloating)
1861                 resize(selmon->sel, selmon->sel->x, selmon->sel->y,
1862                        selmon->sel->w, selmon->sel->h, False, 0);
1863         arrange(selmon);
1864 }
1865
1866 void
1867 toggletag(const Arg *arg) {
1868         unsigned int newtags;
1869
1870         if(!selmon->sel)
1871                 return;
1872         newtags = selmon->sel->tags ^ (arg->ui & TAGMASK);
1873         if(newtags) {
1874                 selmon->sel->tags = newtags;
1875                 focus(NULL);
1876                 arrange(selmon);
1877         }
1878 }
1879
1880 void
1881 toggleview(const Arg *arg) {
1882         unsigned int newtagset = selmon->tagset[selmon->seltags] ^ (arg->ui & TAGMASK);
1883
1884         if(newtagset) {
1885                 selmon->tagset[selmon->seltags] = newtagset;
1886                 focus(NULL);
1887                 arrange(selmon);
1888         }
1889 }
1890
1891 void
1892 unfocus(Client *c, Bool setfocus) {
1893         if(!c)
1894                 return;
1895         grabbuttons(c, False);
1896         XSetWindowBorder(dpy, c->win, scheme[SchemeNorm].border->rgb);
1897         if(setfocus) {
1898                 XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
1899                 XDeleteProperty(dpy, root, netatom[NetActiveWindow]);
1900         }
1901 }
1902
1903 void
1904 unmanage(Client *c, Bool destroyed) {
1905         Monitor *m = c->mon;
1906         XWindowChanges wc;
1907
1908         /* The server grab construct avoids race conditions. */
1909         detachstack(c);
1910         detach(c);
1911         if(!destroyed) {
1912                 wc.border_width = c->oldbw;
1913                 XGrabServer(dpy);
1914                 XSetErrorHandler(xerrordummy);
1915                 XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
1916                 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1917                 setclientstate(c, WithdrawnState);
1918                 XSync(dpy, False);
1919                 XSetErrorHandler(xerror);
1920                 XUngrabServer(dpy);
1921         }
1922         free(c);
1923         focus(selmon ? selmon->sel : NULL);
1924         updateclientlist();
1925         arrange(m);
1926 }
1927
1928 void
1929 unmapnotify(XEvent *e) {
1930         Client *c;
1931         XUnmapEvent *ev = &e->xunmap;
1932
1933         if((c = wintoclient(ev->window))) {
1934                 if(ev->send_event)
1935                         setclientstate(c, WithdrawnState);
1936                 else
1937                         unmanage(c, False);
1938         }
1939 }
1940
1941 void
1942 updatebars(void) {
1943         Monitor *m;
1944         XSetWindowAttributes wa = {
1945                 .override_redirect = True,
1946                 .background_pixmap = ParentRelative,
1947                 .event_mask = ButtonPressMask|ExposureMask
1948         };
1949         for(m = mons; m; m = m->next) {
1950                 if (m->barwin)
1951                         continue;
1952                 m->barwin = XCreateWindow(dpy, root, m->wx, m->by, m->ww, bh, 0, DefaultDepth(dpy, screen),
1953                                           CopyFromParent, DefaultVisual(dpy, screen),
1954                                           CWOverrideRedirect|CWBackPixmap|CWEventMask, &wa);
1955                 XChangeProperty(dpy, root, netatom[NetSupportingWMCheck], XA_WINDOW, 32,
1956                                 PropModeReplace, (unsigned char *) &(m->barwin), 1);
1957                 XChangeProperty(dpy, m->barwin, netatom[NetSupportingWMCheck], XA_WINDOW, 32,
1958                                 PropModeReplace, (unsigned char *) &(m->barwin), 1);
1959                 XChangeProperty(dpy, m->barwin, netatom[NetWMName], XA_STRING, 8,
1960                                 PropModeReplace, (unsigned char *) "dwm", 3);
1961                 XDefineCursor(dpy, m->barwin, cursor[CurNormal]->cursor);
1962                 XMapRaised(dpy, m->barwin);
1963         }
1964 }
1965
1966 void
1967 updatebarpos(Monitor *m) {
1968         m->wy = m->my;
1969         m->wh = m->mh;
1970         if(m->showbar) {
1971                 m->wh -= bh;
1972                 m->by = m->topbar ? m->wy : m->wy + m->wh;
1973                 m->wy = m->topbar ? m->wy + bh : m->wy;
1974         }
1975         else
1976                 m->by = -bh;
1977 }
1978
1979 void
1980 updateclientlist() {
1981         Client *c;
1982         Monitor *m;
1983
1984         XDeleteProperty(dpy, root, netatom[NetClientList]);
1985         for(m = mons; m; m = m->next)
1986                 for(c = m->clients; c; c = c->next)
1987                         XChangeProperty(dpy, root, netatom[NetClientList],
1988                                         XA_WINDOW, 32, PropModeAppend,
1989                                         (unsigned char *) &(c->win), 1);
1990 }
1991
1992 Bool
1993 updategeom(void) {
1994         Bool dirty = False;
1995
1996 #ifdef XINERAMA
1997         if(XineramaIsActive(dpy)) {
1998                 int i, j, n, nn;
1999                 Client *c;
2000                 Monitor *m;
2001                 XineramaScreenInfo *info = XineramaQueryScreens(dpy, &nn);
2002                 XineramaScreenInfo *unique = NULL;
2003
2004                 for(n = 0, m = mons; m; m = m->next, n++);
2005                 /* only consider unique geometries as separate screens */
2006                 if(!(unique = (XineramaScreenInfo *)malloc(sizeof(XineramaScreenInfo) * nn)))
2007                         die("fatal: could not malloc() %u bytes\n", sizeof(XineramaScreenInfo) * nn);
2008                 for(i = 0, j = 0; i < nn; i++)
2009                         if(isuniquegeom(unique, j, &info[i]))
2010                                 memcpy(&unique[j++], &info[i], sizeof(XineramaScreenInfo));
2011                 XFree(info);
2012                 nn = j;
2013                 if(n <= nn) {
2014                         for(i = 0; i < (nn - n); i++) { /* new monitors available */
2015                                 for(m = mons; m && m->next; m = m->next);
2016                                 if(m)
2017                                         m->next = createmon();
2018                                 else
2019                                         mons = createmon();
2020                         }
2021                         for(i = 0, m = mons; i < nn && m; m = m->next, i++)
2022                                 if(i >= n
2023                                 || (unique[i].x_org != m->mx || unique[i].y_org != m->my
2024                                     || unique[i].width != m->mw || unique[i].height != m->mh))
2025                                 {
2026                                         dirty = True;
2027                                         m->num = i;
2028                                         m->mx = m->wx = unique[i].x_org;
2029                                         m->my = m->wy = unique[i].y_org;
2030                                         m->mw = m->ww = unique[i].width;
2031                                         m->mh = m->wh = unique[i].height;
2032                                         updatebarpos(m);
2033                                 }
2034                 }
2035                 else { /* less monitors available nn < n */
2036                         for(i = nn; i < n; i++) {
2037                                 for(m = mons; m && m->next; m = m->next);
2038                                 while(m->clients) {
2039                                         dirty = True;
2040                                         c = m->clients;
2041                                         m->clients = c->next;
2042                                         detachstack(c);
2043                                         c->mon = mons;
2044                                         attach(c);
2045                                         attachstack(c);
2046                                 }
2047                                 if(m == selmon)
2048                                         selmon = mons;
2049                                 cleanupmon(m);
2050                         }
2051                 }
2052                 free(unique);
2053         }
2054         else
2055 #endif /* XINERAMA */
2056         /* default monitor setup */
2057         {
2058                 if(!mons)
2059                         mons = createmon();
2060                 if(mons->mw != sw || mons->mh != sh) {
2061                         dirty = True;
2062                         mons->mw = mons->ww = sw;
2063                         mons->mh = mons->wh = sh;
2064                         updatebarpos(mons);
2065                 }
2066         }
2067         if(dirty) {
2068                 selmon = mons;
2069                 selmon = wintomon(root);
2070         }
2071         return dirty;
2072 }
2073
2074 void
2075 updatenumlockmask(void) {
2076         unsigned int i, j;
2077         XModifierKeymap *modmap;
2078
2079         numlockmask = 0;
2080         modmap = XGetModifierMapping(dpy);
2081         for(i = 0; i < 8; i++)
2082                 for(j = 0; j < modmap->max_keypermod; j++)
2083                         if(modmap->modifiermap[i * modmap->max_keypermod + j]
2084                            == XKeysymToKeycode(dpy, XK_Num_Lock))
2085                                 numlockmask = (1 << i);
2086         XFreeModifiermap(modmap);
2087 }
2088
2089 void
2090 updatesizehints(Client *c) {
2091         long msize;
2092         XSizeHints size;
2093
2094         if(!XGetWMNormalHints(dpy, c->win, &size, &msize))
2095                 /* size is uninitialized, ensure that size.flags aren't used */
2096                 size.flags = PSize;
2097         if(size.flags & PBaseSize) {
2098                 c->basew = size.base_width;
2099                 c->baseh = size.base_height;
2100         }
2101         else if(size.flags & PMinSize) {
2102                 c->basew = size.min_width;
2103                 c->baseh = size.min_height;
2104         }
2105         else
2106                 c->basew = c->baseh = 0;
2107         if(size.flags & PResizeInc) {
2108                 c->incw = size.width_inc;
2109                 c->inch = size.height_inc;
2110         }
2111         else
2112                 c->incw = c->inch = 0;
2113         if(size.flags & PMaxSize) {
2114                 c->maxw = size.max_width;
2115                 c->maxh = size.max_height;
2116         }
2117         else
2118                 c->maxw = c->maxh = 0;
2119         if(size.flags & PMinSize) {
2120                 c->minw = size.min_width;
2121                 c->minh = size.min_height;
2122         }
2123         else if(size.flags & PBaseSize) {
2124                 c->minw = size.base_width;
2125                 c->minh = size.base_height;
2126         }
2127         else
2128                 c->minw = c->minh = 0;
2129         if(size.flags & PAspect) {
2130                 c->mina = (float)size.min_aspect.y / size.min_aspect.x;
2131                 c->maxa = (float)size.max_aspect.x / size.max_aspect.y;
2132         }
2133         else
2134                 c->maxa = c->mina = 0.0;
2135         c->isfixed = (c->maxw && c->minw && c->maxh && c->minh
2136                      && c->maxw == c->minw && c->maxh == c->minh);
2137 }
2138
2139 void
2140 updatetitle(Client *c) {
2141         if(!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
2142                 gettextprop(c->win, XA_WM_NAME, c->name, sizeof c->name);
2143         if(c->name[0] == '\0') /* hack to mark broken clients */
2144                 strcpy(c->name, broken);
2145 }
2146
2147 void
2148 updatestatus(void) {
2149         if(!gettextprop(root, XA_WM_NAME, stext, sizeof(stext)))
2150                 strcpy(stext, "dwm-"VERSION);
2151         drawbar(selmon);
2152 }
2153
2154 void
2155 updatewindowtype(Client *c) {
2156         Atom state = getatomprop(c, netatom[NetWMState]);
2157         Atom wtype = getatomprop(c, netatom[NetWMWindowType]);
2158
2159         if(state == netatom[NetWMFullscreen])
2160                 setfullscreen(c, True);
2161         if(wtype == netatom[NetWMWindowTypeDialog])
2162                 c->isfloating = True;
2163 }
2164
2165 void
2166 updatewmhints(Client *c) {
2167         XWMHints *wmh;
2168
2169         if((wmh = XGetWMHints(dpy, c->win))) {
2170                 if(c == selmon->sel && wmh->flags & XUrgencyHint) {
2171                         wmh->flags &= ~XUrgencyHint;
2172                         XSetWMHints(dpy, c->win, wmh);
2173                 }
2174                 else
2175                         c->isurgent = (wmh->flags & XUrgencyHint) ? True : False;
2176                 if(wmh->flags & InputHint)
2177                         c->neverfocus = !wmh->input;
2178                 else
2179                         c->neverfocus = False;
2180                 XFree(wmh);
2181         }
2182 }
2183
2184 void
2185 view(const Arg *arg) {
2186         if((arg->ui & TAGMASK) == selmon->tagset[selmon->seltags])
2187                 return;
2188         selmon->seltags ^= 1; /* toggle sel tagset */
2189         if(arg->ui & TAGMASK)
2190                 selmon->tagset[selmon->seltags] = arg->ui & TAGMASK;
2191         focus(NULL);
2192         arrange(selmon);
2193 }
2194
2195 Client *
2196 wintoclient(Window w) {
2197         Client *c;
2198         Monitor *m;
2199
2200         for(m = mons; m; m = m->next)
2201                 for(c = m->clients; c; c = c->next)
2202                         if(c->win == w)
2203                                 return c;
2204         return NULL;
2205 }
2206
2207 Monitor *
2208 wintomon(Window w) {
2209         int x, y;
2210         Client *c;
2211         Monitor *m;
2212
2213         if(w == root && getrootptr(&x, &y))
2214                 return recttomon(x, y, 1, 1);
2215         for(m = mons; m; m = m->next)
2216                 if(w == m->barwin)
2217                         return m;
2218         if((c = wintoclient(w)))
2219                 return c->mon;
2220         return selmon;
2221 }
2222
2223 /* There's no way to check accesses to destroyed windows, thus those cases are
2224  * ignored (especially on UnmapNotify's).  Other types of errors call Xlibs
2225  * default error handler, which may call exit.  */
2226 int
2227 xerror(Display *dpy, XErrorEvent *ee) {
2228         if(ee->error_code == BadWindow
2229         || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
2230         || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
2231         || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
2232         || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
2233         || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
2234         || (ee->request_code == X_GrabButton && ee->error_code == BadAccess)
2235         || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
2236         || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
2237                 return 0;
2238         fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
2239                         ee->request_code, ee->error_code);
2240         return xerrorxlib(dpy, ee); /* may call exit */
2241 }
2242
2243 int
2244 xerrordummy(Display *dpy, XErrorEvent *ee) {
2245         return 0;
2246 }
2247
2248 /* Startup Error handler to check if another window manager
2249  * is already running. */
2250 int
2251 xerrorstart(Display *dpy, XErrorEvent *ee) {
2252         die("dwm: another window manager is already running\n");
2253         return -1;
2254 }
2255
2256 void
2257 zoom(const Arg *arg) {
2258         Client *c = selmon->sel;
2259
2260         if(!selmon->lt[selmon->sellt]->arrange
2261         || (selmon->sel && selmon->sel->isfloating))
2262                 return;
2263         if(c == nexttiled(selmon->clients))
2264                 if(!c || !(c = nexttiled(c->next)))
2265                         return;
2266         pop(c);
2267 }
2268
2269 int
2270 main(int argc, char *argv[]) {
2271         if(argc == 2 && !strcmp("-v", argv[1]))
2272                 die("dwm-"VERSION", © 2006-2014 dwm engineers, see LICENSE for details\n");
2273         else if(argc != 1)
2274                 die("usage: dwm [-v]\n");
2275         if(!setlocale(LC_CTYPE, "") || !XSupportsLocale())
2276                 fputs("warning: no locale support\n", stderr);
2277         if(!(dpy = XOpenDisplay(NULL)))
2278                 die("dwm: cannot open display\n");
2279         checkotherwm();
2280         setup();
2281         scan();
2282         run();
2283         cleanup();
2284         XCloseDisplay(dpy);
2285         return EXIT_SUCCESS;
2286 }