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