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