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