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