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