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