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