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