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