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