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