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