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