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