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