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