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