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