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