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