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