applied swallow
[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         unsigned int i;
1089         selmon->nmaster = MAX(selmon->nmaster + arg->i, 0);
1090         for(i=0; i<LENGTH(tags); ++i)
1091                 if(selmon->tagset[selmon->seltags] & 1<<i)
1092                         selmon->pertag->nmasters[i+1] = selmon->nmaster;
1093
1094         if(selmon->pertag->curtag == 0)
1095         {
1096                 selmon->pertag->nmasters[0] = selmon->nmaster;
1097         }
1098         arrange(selmon);
1099 }
1100
1101 #ifdef XINERAMA
1102 static int
1103 isuniquegeom(XineramaScreenInfo *unique, size_t n, XineramaScreenInfo *info)
1104 {
1105         while (n--)
1106                 if (unique[n].x_org == info->x_org && unique[n].y_org == info->y_org
1107                 && unique[n].width == info->width && unique[n].height == info->height)
1108                         return 0;
1109         return 1;
1110 }
1111 #endif /* XINERAMA */
1112
1113 void
1114 keypress(XEvent *e)
1115 {
1116         unsigned int i;
1117         KeySym keysym;
1118         XKeyEvent *ev;
1119
1120         ev = &e->xkey;
1121         keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
1122         for (i = 0; i < LENGTH(keys); i++)
1123                 if (keysym == keys[i].keysym
1124                 && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state)
1125                 && keys[i].func)
1126                         keys[i].func(&(keys[i].arg));
1127 }
1128
1129 void
1130 killclient(const Arg *arg)
1131 {
1132         if (!selmon->sel)
1133                 return;
1134         if (!sendevent(selmon->sel, wmatom[WMDelete])) {
1135                 XGrabServer(dpy);
1136                 XSetErrorHandler(xerrordummy);
1137                 XSetCloseDownMode(dpy, DestroyAll);
1138                 XKillClient(dpy, selmon->sel->win);
1139                 XSync(dpy, False);
1140                 XSetErrorHandler(xerror);
1141                 XUngrabServer(dpy);
1142         }
1143 }
1144
1145 void
1146 manage(Window w, XWindowAttributes *wa)
1147 {
1148         Client *c, *t = NULL, *term = NULL;
1149         Window trans = None;
1150         XWindowChanges wc;
1151
1152         c = ecalloc(1, sizeof(Client));
1153         c->win = w;
1154         c->pid = winpid(w);
1155         /* geometry */
1156         c->x = c->oldx = wa->x;
1157         c->y = c->oldy = wa->y;
1158         c->w = c->oldw = wa->width;
1159         c->h = c->oldh = wa->height;
1160         c->oldbw = wa->border_width;
1161
1162         updatetitle(c);
1163         if (XGetTransientForHint(dpy, w, &trans) && (t = wintoclient(trans))) {
1164                 c->mon = t->mon;
1165                 c->tags = t->tags;
1166         } else {
1167                 c->mon = selmon;
1168                 applyrules(c);
1169                 term = termforwin(c);
1170         }
1171
1172         if (c->x + WIDTH(c) > c->mon->mx + c->mon->mw)
1173                 c->x = c->mon->mx + c->mon->mw - WIDTH(c);
1174         if (c->y + HEIGHT(c) > c->mon->my + c->mon->mh)
1175                 c->y = c->mon->my + c->mon->mh - HEIGHT(c);
1176         c->x = MAX(c->x, c->mon->mx);
1177         /* only fix client y-offset, if the client center might cover the bar */
1178         c->y = MAX(c->y, ((c->mon->by == c->mon->my) && (c->x + (c->w / 2) >= c->mon->wx)
1179                 && (c->x + (c->w / 2) < c->mon->wx + c->mon->ww)) ? bh : c->mon->my);
1180         c->bw = borderpx;
1181
1182         wc.border_width = c->bw;
1183         XConfigureWindow(dpy, w, CWBorderWidth, &wc);
1184         XSetWindowBorder(dpy, w, scheme[SchemeNorm][ColBorder].pixel);
1185         configure(c); /* propagates border_width, if size doesn't change */
1186         updatewindowtype(c);
1187         updatesizehints(c);
1188         updatewmhints(c);
1189         XSelectInput(dpy, w, EnterWindowMask|FocusChangeMask|PropertyChangeMask|StructureNotifyMask);
1190         grabbuttons(c, 0);
1191         if (!c->isfloating)
1192                 c->isfloating = c->oldstate = trans != None || c->isfixed;
1193         if (c->isfloating)
1194                 XRaiseWindow(dpy, c->win);
1195         attach(c);
1196         attachstack(c);
1197         XChangeProperty(dpy, root, netatom[NetClientList], XA_WINDOW, 32, PropModeAppend,
1198                 (unsigned char *) &(c->win), 1);
1199         XMoveResizeWindow(dpy, c->win, c->x + 2 * sw, c->y, c->w, c->h); /* some windows require this */
1200         setclientstate(c, NormalState);
1201         if (c->mon == selmon)
1202                 unfocus(selmon->sel, 0);
1203         c->mon->sel = c;
1204         arrange(c->mon);
1205         XMapWindow(dpy, c->win);
1206         if (term)
1207                 swallow(term, c);
1208         focus(NULL);
1209 }
1210
1211 void
1212 mappingnotify(XEvent *e)
1213 {
1214         XMappingEvent *ev = &e->xmapping;
1215
1216         XRefreshKeyboardMapping(ev);
1217         if (ev->request == MappingKeyboard)
1218                 grabkeys();
1219 }
1220
1221 void
1222 maprequest(XEvent *e)
1223 {
1224         static XWindowAttributes wa;
1225         XMapRequestEvent *ev = &e->xmaprequest;
1226
1227         if (!XGetWindowAttributes(dpy, ev->window, &wa))
1228                 return;
1229         if (wa.override_redirect)
1230                 return;
1231         if (!wintoclient(ev->window))
1232                 manage(ev->window, &wa);
1233 }
1234
1235 void
1236 monocle(Monitor *m)
1237 {
1238         unsigned int n = 0;
1239         Client *c;
1240
1241         for (c = m->clients; c; c = c->next)
1242                 if (ISVISIBLE(c))
1243                         n++;
1244         if (n > 0) /* override layout symbol */
1245                 snprintf(m->ltsymbol, sizeof m->ltsymbol, "[%d]", n);
1246         for (c = nexttiled(m->clients); c; c = nexttiled(c->next))
1247                 resize(c, m->wx, m->wy, m->ww - 2 * c->bw, m->wh - 2 * c->bw, 0);
1248 }
1249
1250 void
1251 motionnotify(XEvent *e)
1252 {
1253         static Monitor *mon = NULL;
1254         Monitor *m;
1255         XMotionEvent *ev = &e->xmotion;
1256
1257         if (ev->window != root)
1258                 return;
1259         if ((m = recttomon(ev->x_root, ev->y_root, 1, 1)) != mon && mon) {
1260                 unfocus(selmon->sel, 1);
1261                 selmon = m;
1262                 focus(NULL);
1263         }
1264         mon = m;
1265 }
1266
1267 void
1268 movemouse(const Arg *arg)
1269 {
1270         int x, y, ocx, ocy, nx, ny;
1271         Client *c;
1272         Monitor *m;
1273         XEvent ev;
1274         Time lasttime = 0;
1275
1276         if (!(c = selmon->sel))
1277                 return;
1278         restack(selmon);
1279         ocx = c->x;
1280         ocy = c->y;
1281         if (XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1282                 None, cursor[CurMove]->cursor, CurrentTime) != GrabSuccess)
1283                 return;
1284         if (!getrootptr(&x, &y))
1285                 return;
1286         do {
1287                 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
1288                 switch(ev.type) {
1289                 case ConfigureRequest:
1290                 case Expose:
1291                 case MapRequest:
1292                         handler[ev.type](&ev);
1293                         break;
1294                 case MotionNotify:
1295                         if ((ev.xmotion.time - lasttime) <= (1000 / 60))
1296                                 continue;
1297                         lasttime = ev.xmotion.time;
1298
1299                         nx = ocx + (ev.xmotion.x - x);
1300                         ny = ocy + (ev.xmotion.y - y);
1301                         if (abs(selmon->wx - nx) < snap)
1302                                 nx = selmon->wx;
1303                         else if (abs((selmon->wx + selmon->ww) - (nx + WIDTH(c))) < snap)
1304                                 nx = selmon->wx + selmon->ww - WIDTH(c);
1305                         if (abs(selmon->wy - ny) < snap)
1306                                 ny = selmon->wy;
1307                         else if (abs((selmon->wy + selmon->wh) - (ny + HEIGHT(c))) < snap)
1308                                 ny = selmon->wy + selmon->wh - HEIGHT(c);
1309                         if (!c->isfloating && selmon->lt[selmon->sellt]->arrange
1310                         && (abs(nx - c->x) > snap || abs(ny - c->y) > snap))
1311                                 togglefloating(NULL);
1312                         if (!selmon->lt[selmon->sellt]->arrange || c->isfloating)
1313                                 resize(c, nx, ny, c->w, c->h, 1);
1314                         break;
1315                 }
1316         } while (ev.type != ButtonRelease);
1317         XUngrabPointer(dpy, CurrentTime);
1318         if ((m = recttomon(c->x, c->y, c->w, c->h)) != selmon) {
1319                 sendmon(c, m);
1320                 selmon = m;
1321                 focus(NULL);
1322         }
1323 }
1324
1325 Client *
1326 nexttiled(Client *c)
1327 {
1328         for (; c && (c->isfloating || !ISVISIBLE(c)); c = c->next);
1329         return c;
1330 }
1331
1332 void
1333 pop(Client *c)
1334 {
1335         detach(c);
1336         attach(c);
1337         focus(c);
1338         arrange(c->mon);
1339 }
1340
1341 void
1342 propertynotify(XEvent *e)
1343 {
1344         Client *c;
1345         Window trans;
1346         XPropertyEvent *ev = &e->xproperty;
1347
1348         if ((ev->window == root) && (ev->atom == XA_WM_NAME))
1349                 updatestatus();
1350         else if (ev->state == PropertyDelete)
1351                 return; /* ignore */
1352         else if ((c = wintoclient(ev->window))) {
1353                 switch(ev->atom) {
1354                 default: break;
1355                 case XA_WM_TRANSIENT_FOR:
1356                         if (!c->isfloating && (XGetTransientForHint(dpy, c->win, &trans)) &&
1357                                 (c->isfloating = (wintoclient(trans)) != NULL))
1358                                 arrange(c->mon);
1359                         break;
1360                 case XA_WM_NORMAL_HINTS:
1361                         updatesizehints(c);
1362                         break;
1363                 case XA_WM_HINTS:
1364                         updatewmhints(c);
1365                         drawbars();
1366                         break;
1367                 }
1368                 if (ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
1369                         updatetitle(c);
1370                         if (c == c->mon->sel)
1371                                 drawbar(c->mon);
1372                 }
1373                 if (ev->atom == netatom[NetWMWindowType])
1374                         updatewindowtype(c);
1375         }
1376 }
1377
1378 void
1379 quit(const Arg *arg)
1380 {
1381         running = 0;
1382 }
1383
1384 Monitor *
1385 recttomon(int x, int y, int w, int h)
1386 {
1387         Monitor *m, *r = selmon;
1388         int a, area = 0;
1389
1390         for (m = mons; m; m = m->next)
1391                 if ((a = INTERSECT(x, y, w, h, m)) > area) {
1392                         area = a;
1393                         r = m;
1394                 }
1395         return r;
1396 }
1397
1398 void
1399 resize(Client *c, int x, int y, int w, int h, int interact)
1400 {
1401         if (applysizehints(c, &x, &y, &w, &h, interact))
1402                 resizeclient(c, x, y, w, h);
1403 }
1404
1405 void
1406 resizeclient(Client *c, int x, int y, int w, int h)
1407 {
1408         XWindowChanges wc;
1409
1410         c->oldx = c->x; c->x = wc.x = x;
1411         c->oldy = c->y; c->y = wc.y = y;
1412         c->oldw = c->w; c->w = wc.width = w;
1413         c->oldh = c->h; c->h = wc.height = h;
1414         wc.border_width = c->bw;
1415         XConfigureWindow(dpy, c->win, CWX|CWY|CWWidth|CWHeight|CWBorderWidth, &wc);
1416         configure(c);
1417         XSync(dpy, False);
1418 }
1419
1420 void
1421 resizemouse(const Arg *arg)
1422 {
1423         int ocx, ocy, nw, nh;
1424         Client *c;
1425         Monitor *m;
1426         XEvent ev;
1427         Time lasttime = 0;
1428
1429         if (!(c = selmon->sel))
1430                 return;
1431         restack(selmon);
1432         ocx = c->x;
1433         ocy = c->y;
1434         if (XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1435                 None, cursor[CurResize]->cursor, CurrentTime) != GrabSuccess)
1436                 return;
1437         XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->bw - 1, c->h + c->bw - 1);
1438         do {
1439                 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
1440                 switch(ev.type) {
1441                 case ConfigureRequest:
1442                 case Expose:
1443                 case MapRequest:
1444                         handler[ev.type](&ev);
1445                         break;
1446                 case MotionNotify:
1447                         if ((ev.xmotion.time - lasttime) <= (1000 / 60))
1448                                 continue;
1449                         lasttime = ev.xmotion.time;
1450
1451                         nw = MAX(ev.xmotion.x - ocx - 2 * c->bw + 1, 1);
1452                         nh = MAX(ev.xmotion.y - ocy - 2 * c->bw + 1, 1);
1453                         if (c->mon->wx + nw >= selmon->wx && c->mon->wx + nw <= selmon->wx + selmon->ww
1454                         && c->mon->wy + nh >= selmon->wy && c->mon->wy + nh <= selmon->wy + selmon->wh)
1455                         {
1456                                 if (!c->isfloating && selmon->lt[selmon->sellt]->arrange
1457                                 && (abs(nw - c->w) > snap || abs(nh - c->h) > snap))
1458                                         togglefloating(NULL);
1459                         }
1460                         if (!selmon->lt[selmon->sellt]->arrange || c->isfloating)
1461                                 resize(c, c->x, c->y, nw, nh, 1);
1462                         break;
1463                 }
1464         } while (ev.type != ButtonRelease);
1465         XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->bw - 1, c->h + c->bw - 1);
1466         XUngrabPointer(dpy, CurrentTime);
1467         while (XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1468         if ((m = recttomon(c->x, c->y, c->w, c->h)) != selmon) {
1469                 sendmon(c, m);
1470                 selmon = m;
1471                 focus(NULL);
1472         }
1473 }
1474
1475 void
1476 restack(Monitor *m)
1477 {
1478         Client *c;
1479         XEvent ev;
1480         XWindowChanges wc;
1481
1482         drawbar(m);
1483         if (!m->sel)
1484                 return;
1485         if (m->sel->isfloating || !m->lt[m->sellt]->arrange)
1486                 XRaiseWindow(dpy, m->sel->win);
1487         if (m->lt[m->sellt]->arrange) {
1488                 wc.stack_mode = Below;
1489                 wc.sibling = m->barwin;
1490                 for (c = m->stack; c; c = c->snext)
1491                         if (!c->isfloating && ISVISIBLE(c)) {
1492                                 XConfigureWindow(dpy, c->win, CWSibling|CWStackMode, &wc);
1493                                 wc.sibling = c->win;
1494                         }
1495         }
1496         XSync(dpy, False);
1497         while (XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1498 }
1499
1500 void
1501 run(void)
1502 {
1503         XEvent ev;
1504         /* main event loop */
1505         XSync(dpy, False);
1506         while (running && !XNextEvent(dpy, &ev))
1507                 if (handler[ev.type])
1508                         handler[ev.type](&ev); /* call handler */
1509 }
1510
1511 void
1512 runautostart(void)
1513 {
1514         char *pathpfx;
1515         char *path;
1516         char *xdgdatahome;
1517         char *home;
1518         struct stat sb;
1519
1520         if ((home = getenv("HOME")) == NULL)
1521                 /* this is almost impossible */
1522                 return;
1523
1524         /* if $XDG_DATA_HOME is set and not empty, use $XDG_DATA_HOME/dwm,
1525          * otherwise use ~/.local/share/dwm as autostart script directory
1526          */
1527         xdgdatahome = getenv("XDG_DATA_HOME");
1528         if (xdgdatahome != NULL && *xdgdatahome != '\0') {
1529                 /* space for path segments, separators and nul */
1530                 pathpfx = ecalloc(1, strlen(xdgdatahome) + strlen(dwmdir) + 2);
1531
1532                 if (sprintf(pathpfx, "%s/%s", xdgdatahome, dwmdir) <= 0) {
1533                         free(pathpfx);
1534                         return;
1535                 }
1536         } else {
1537                 /* space for path segments, separators and nul */
1538                 pathpfx = ecalloc(1, strlen(home) + strlen(localshare)
1539                                      + strlen(dwmdir) + 3);
1540
1541                 if (sprintf(pathpfx, "%s/%s/%s", home, localshare, dwmdir) < 0) {
1542                         free(pathpfx);
1543                         return;
1544                 }
1545         }
1546
1547         /* check if the autostart script directory exists */
1548         if (! (stat(pathpfx, &sb) == 0 && S_ISDIR(sb.st_mode))) {
1549                 /* the XDG conformant path does not exist or is no directory
1550                  * so we try ~/.dwm instead
1551                  */
1552                 char *pathpfx_new = realloc(pathpfx, strlen(home) + strlen(dwmdir) + 3);
1553                 if(pathpfx_new == NULL) {
1554                         free(pathpfx);
1555                         return;
1556                 }
1557    pathpfx = pathpfx_new;
1558
1559                 if (sprintf(pathpfx, "%s/.%s", home, dwmdir) <= 0) {
1560                         free(pathpfx);
1561                         return;
1562                 }
1563         }
1564
1565         /* try the blocking script first */
1566         path = ecalloc(1, strlen(pathpfx) + strlen(autostartblocksh) + 2);
1567         if (sprintf(path, "%s/%s", pathpfx, autostartblocksh) <= 0) {
1568                 free(path);
1569                 free(pathpfx);
1570         }
1571
1572         if (access(path, X_OK) == 0)
1573                 system(path);
1574
1575         /* now the non-blocking script */
1576         if (sprintf(path, "%s/%s", pathpfx, autostartsh) <= 0) {
1577                 free(path);
1578                 free(pathpfx);
1579         }
1580
1581         if (access(path, X_OK) == 0)
1582                 system(strcat(path, " &"));
1583
1584         free(pathpfx);
1585         free(path);
1586 }
1587
1588 void
1589 scan(void)
1590 {
1591         unsigned int i, num;
1592         Window d1, d2, *wins = NULL;
1593         XWindowAttributes wa;
1594
1595         if (XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1596                 for (i = 0; i < num; i++) {
1597                         if (!XGetWindowAttributes(dpy, wins[i], &wa)
1598                         || wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1599                                 continue;
1600                         if (wa.map_state == IsViewable || getstate(wins[i]) == IconicState)
1601                                 manage(wins[i], &wa);
1602                 }
1603                 for (i = 0; i < num; i++) { /* now the transients */
1604                         if (!XGetWindowAttributes(dpy, wins[i], &wa))
1605                                 continue;
1606                         if (XGetTransientForHint(dpy, wins[i], &d1)
1607                         && (wa.map_state == IsViewable || getstate(wins[i]) == IconicState))
1608                                 manage(wins[i], &wa);
1609                 }
1610                 if (wins)
1611                         XFree(wins);
1612         }
1613 }
1614
1615 void
1616 sendmon(Client *c, Monitor *m)
1617 {
1618         if (c->mon == m)
1619                 return;
1620         unfocus(c, 1);
1621         detach(c);
1622         detachstack(c);
1623         c->mon = m;
1624         c->tags = m->tagset[m->seltags]; /* assign tags of target monitor */
1625         attach(c);
1626         attachstack(c);
1627         focus(NULL);
1628         arrange(NULL);
1629 }
1630
1631 void
1632 setclientstate(Client *c, long state)
1633 {
1634         long data[] = { state, None };
1635
1636         XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1637                 PropModeReplace, (unsigned char *)data, 2);
1638 }
1639
1640 int
1641 sendevent(Client *c, Atom proto)
1642 {
1643         int n;
1644         Atom *protocols;
1645         int exists = 0;
1646         XEvent ev;
1647
1648         if (XGetWMProtocols(dpy, c->win, &protocols, &n)) {
1649                 while (!exists && n--)
1650                         exists = protocols[n] == proto;
1651                 XFree(protocols);
1652         }
1653         if (exists) {
1654                 ev.type = ClientMessage;
1655                 ev.xclient.window = c->win;
1656                 ev.xclient.message_type = wmatom[WMProtocols];
1657                 ev.xclient.format = 32;
1658                 ev.xclient.data.l[0] = proto;
1659                 ev.xclient.data.l[1] = CurrentTime;
1660                 XSendEvent(dpy, c->win, False, NoEventMask, &ev);
1661         }
1662         return exists;
1663 }
1664
1665 void
1666 setfocus(Client *c)
1667 {
1668         if (!c->neverfocus) {
1669                 XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
1670                 XChangeProperty(dpy, root, netatom[NetActiveWindow],
1671                         XA_WINDOW, 32, PropModeReplace,
1672                         (unsigned char *) &(c->win), 1);
1673         }
1674         sendevent(c, wmatom[WMTakeFocus]);
1675 }
1676
1677 void
1678 setfullscreen(Client *c, int fullscreen)
1679 {
1680         if (fullscreen && !c->isfullscreen) {
1681                 XChangeProperty(dpy, c->win, netatom[NetWMState], XA_ATOM, 32,
1682                         PropModeReplace, (unsigned char*)&netatom[NetWMFullscreen], 1);
1683                 c->isfullscreen = 1;
1684         } else if (!fullscreen && c->isfullscreen){
1685                 XChangeProperty(dpy, c->win, netatom[NetWMState], XA_ATOM, 32,
1686                         PropModeReplace, (unsigned char*)0, 0);
1687                 c->isfullscreen = 0;
1688         }
1689 }
1690
1691 void
1692 setgaps(const Arg *arg)
1693 {
1694         if ((arg->i == 0) || (selmon->gappx + arg->i < 0))
1695                 selmon->gappx = 0;
1696         else
1697                 selmon->gappx += arg->i;
1698         arrange(selmon);
1699 }
1700
1701 void
1702 setlayout(const Arg *arg)
1703 {
1704         unsigned int i;
1705         if (!arg || !arg->v || arg->v != selmon->lt[selmon->sellt])
1706                 selmon->sellt ^= 1;
1707         if (arg && arg->v)
1708                 selmon->lt[selmon->sellt] = (Layout *)arg->v;
1709         strncpy(selmon->ltsymbol, selmon->lt[selmon->sellt]->symbol, sizeof selmon->ltsymbol);
1710
1711         for(i=0; i<LENGTH(tags); ++i)
1712                 if(selmon->tagset[selmon->seltags] & 1<<i)
1713                 {
1714                         selmon->pertag->ltidxs[i+1][selmon->sellt] = selmon->lt[selmon->sellt];
1715                         selmon->pertag->sellts[i+1] = selmon->sellt;
1716                 }
1717
1718         if(selmon->pertag->curtag == 0)
1719         {
1720                 selmon->pertag->ltidxs[0][selmon->sellt] = selmon->lt[selmon->sellt];
1721                 selmon->pertag->sellts[0] = selmon->sellt;
1722         }
1723
1724         if (selmon->sel)
1725                 arrange(selmon);
1726         else
1727                 drawbar(selmon);
1728 }
1729
1730 /* arg > 1.0 will set mfact absolutely */
1731 void
1732 setmfact(const Arg *arg)
1733 {
1734         float f;
1735         unsigned int i;
1736
1737         if (!arg || !selmon->lt[selmon->sellt]->arrange)
1738                 return;
1739         f = arg->f < 1.0 ? arg->f + selmon->mfact : arg->f - 1.0;
1740         if (arg->f == 0.0)
1741                 f = mfact;
1742         if (f < 0.05 || f > 0.95)
1743                 return;
1744         selmon->mfact = f;
1745         for(i=0; i<LENGTH(tags); ++i)
1746                 if(selmon->tagset[selmon->seltags] & 1<<i)
1747                         selmon->pertag->mfacts[i+1] = f;
1748
1749         if(selmon->pertag->curtag == 0)
1750         {
1751                 selmon->pertag->mfacts[0] = f;
1752         }
1753         arrange(selmon);
1754 }
1755
1756 void
1757 setup(void)
1758 {
1759         int i;
1760         XSetWindowAttributes wa;
1761         Atom utf8string;
1762
1763         /* clean up any zombies immediately */
1764         sigchld(0);
1765
1766         /* init screen */
1767         screen = DefaultScreen(dpy);
1768         sw = DisplayWidth(dpy, screen);
1769         sh = DisplayHeight(dpy, screen);
1770         root = RootWindow(dpy, screen);
1771         drw = drw_create(dpy, screen, root, sw, sh);
1772         if (!drw_fontset_create(drw, fonts, LENGTH(fonts)))
1773                 die("no fonts could be loaded.");
1774         lrpad = drw->fonts->h;
1775         bh = drw->fonts->h + 2;
1776         updategeom();
1777         sp = sidepad;
1778         vp = (topbar == 1) ? vertpad : - vertpad;
1779
1780         /* init atoms */
1781         utf8string = XInternAtom(dpy, "UTF8_STRING", False);
1782         wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1783         wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1784         wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1785         wmatom[WMTakeFocus] = XInternAtom(dpy, "WM_TAKE_FOCUS", False);
1786         netatom[NetActiveWindow] = XInternAtom(dpy, "_NET_ACTIVE_WINDOW", False);
1787         netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1788         netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1789         netatom[NetWMState] = XInternAtom(dpy, "_NET_WM_STATE", False);
1790         netatom[NetWMCheck] = XInternAtom(dpy, "_NET_SUPPORTING_WM_CHECK", False);
1791         netatom[NetWMFullscreen] = XInternAtom(dpy, "_NET_WM_STATE_FULLSCREEN", False);
1792         netatom[NetWMWindowType] = XInternAtom(dpy, "_NET_WM_WINDOW_TYPE", False);
1793         netatom[NetWMWindowTypeDialog] = XInternAtom(dpy, "_NET_WM_WINDOW_TYPE_DIALOG", False);
1794         netatom[NetClientList] = XInternAtom(dpy, "_NET_CLIENT_LIST", False);
1795         /* init cursors */
1796         cursor[CurNormal] = drw_cur_create(drw, XC_left_ptr);
1797         cursor[CurResize] = drw_cur_create(drw, XC_sizing);
1798         cursor[CurMove] = drw_cur_create(drw, XC_fleur);
1799         /* init appearance */
1800         scheme = ecalloc(LENGTH(colors), sizeof(Clr *));
1801         for (i = 0; i < LENGTH(colors); i++)
1802                 scheme[i] = drw_scm_create(drw, colors[i], 3);
1803         /* init bars */
1804         updatebars();
1805         updatestatus();
1806         updatebarpos(selmon);
1807         /* supporting window for NetWMCheck */
1808         wmcheckwin = XCreateSimpleWindow(dpy, root, 0, 0, 1, 1, 0, 0, 0);
1809         XChangeProperty(dpy, wmcheckwin, netatom[NetWMCheck], XA_WINDOW, 32,
1810                 PropModeReplace, (unsigned char *) &wmcheckwin, 1);
1811         XChangeProperty(dpy, wmcheckwin, netatom[NetWMName], utf8string, 8,
1812                 PropModeReplace, (unsigned char *) "dwm", 3);
1813         XChangeProperty(dpy, root, netatom[NetWMCheck], XA_WINDOW, 32,
1814                 PropModeReplace, (unsigned char *) &wmcheckwin, 1);
1815         /* EWMH support per view */
1816         XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1817                 PropModeReplace, (unsigned char *) netatom, NetLast);
1818         XDeleteProperty(dpy, root, netatom[NetClientList]);
1819         /* select events */
1820         wa.cursor = cursor[CurNormal]->cursor;
1821         wa.event_mask = SubstructureRedirectMask|SubstructureNotifyMask
1822                 |ButtonPressMask|PointerMotionMask|EnterWindowMask
1823                 |LeaveWindowMask|StructureNotifyMask|PropertyChangeMask;
1824         XChangeWindowAttributes(dpy, root, CWEventMask|CWCursor, &wa);
1825         XSelectInput(dpy, root, wa.event_mask);
1826         grabkeys();
1827         focus(NULL);
1828 }
1829
1830
1831 void
1832 seturgent(Client *c, int urg)
1833 {
1834         XWMHints *wmh;
1835
1836         c->isurgent = urg;
1837         if (!(wmh = XGetWMHints(dpy, c->win)))
1838                 return;
1839         wmh->flags = urg ? (wmh->flags | XUrgencyHint) : (wmh->flags & ~XUrgencyHint);
1840         XSetWMHints(dpy, c->win, wmh);
1841         XFree(wmh);
1842 }
1843
1844 void
1845 showhide(Client *c)
1846 {
1847         if (!c)
1848                 return;
1849         if (ISVISIBLE(c)) {
1850                 /* show clients top down */
1851                 XMoveWindow(dpy, c->win, c->x, c->y);
1852                 if (!c->mon->lt[c->mon->sellt]->arrange || c->isfloating)
1853                         resize(c, c->x, c->y, c->w, c->h, 0);
1854                 showhide(c->snext);
1855         } else {
1856                 /* hide clients bottom up */
1857                 showhide(c->snext);
1858                 XMoveWindow(dpy, c->win, WIDTH(c) * -2, c->y);
1859         }
1860 }
1861
1862 void
1863 sigchld(int unused)
1864 {
1865         if (signal(SIGCHLD, sigchld) == SIG_ERR)
1866                 die("can't install SIGCHLD handler:");
1867         while (0 < waitpid(-1, NULL, WNOHANG));
1868 }
1869
1870 void
1871 spawn(const Arg *arg)
1872 {
1873         if (arg->v == dmenucmd)
1874                 dmenumon[0] = '0' + selmon->num;
1875         if (fork() == 0) {
1876                 if (dpy)
1877                         close(ConnectionNumber(dpy));
1878                 setsid();
1879                 execvp(((char **)arg->v)[0], (char **)arg->v);
1880                 fprintf(stderr, "dwm: execvp %s", ((char **)arg->v)[0]);
1881                 perror(" failed");
1882                 exit(EXIT_SUCCESS);
1883         }
1884 }
1885
1886 void
1887 tag(const Arg *arg)
1888 {
1889         if (selmon->sel && arg->ui & TAGMASK) {
1890                 selmon->sel->tags = arg->ui & TAGMASK;
1891                 focus(NULL);
1892                 arrange(selmon);
1893         }
1894 }
1895
1896 void
1897 tagmon(const Arg *arg)
1898 {
1899         if (!selmon->sel || !mons->next)
1900                 return;
1901         sendmon(selmon->sel, dirtomon(arg->i));
1902 }
1903
1904 void
1905 tile(Monitor *m)
1906 {
1907         unsigned int i, n, h, mw, my, ty;
1908         Client *c;
1909
1910         for (n = 0, c = nexttiled(m->clients); c; c = nexttiled(c->next), n++);
1911         if (n == 0)
1912                 return;
1913
1914         if (n > m->nmaster)
1915                 mw = m->nmaster ? m->ww * m->mfact : 0;
1916         else
1917                 mw = m->ww - m->gappx;
1918         for (i = 0, my = ty = m->gappx, c = nexttiled(m->clients); c; c = nexttiled(c->next), i++)
1919                 if (i < m->nmaster) {
1920                         h = (m->wh - my) / (MIN(n, m->nmaster) - i) - m->gappx;
1921                         resize(c, m->wx + m->gappx, m->wy + my, mw - (2*c->bw) - m->gappx, h - (2*c->bw), 0);
1922                         if (my + HEIGHT(c) + m->gappx < m->wh)
1923                                 my += HEIGHT(c) + m->gappx;
1924                 } else {
1925                         h = (m->wh - ty) / (n - i) - m->gappx;
1926                         resize(c, m->wx + mw + m->gappx, m->wy + ty, m->ww - mw - (2*c->bw) - 2*m->gappx, h - (2*c->bw), 0);
1927                         if (ty + HEIGHT(c) + m->gappx < m->wh)
1928                                 ty += HEIGHT(c) + m->gappx;
1929                 }
1930 }
1931
1932 void
1933 togglebar(const Arg *arg)
1934 {
1935         unsigned int i;
1936         selmon->showbar = !selmon->showbar;
1937         for(i=0; i<LENGTH(tags); ++i)
1938                 if(selmon->tagset[selmon->seltags] & 1<<i)
1939                         selmon->pertag->showbars[i+1] = selmon->showbar;
1940
1941         if(selmon->pertag->curtag == 0)
1942         {
1943                 selmon->pertag->showbars[0] = selmon->showbar;
1944         }
1945         updatebarpos(selmon);
1946         XMoveResizeWindow(dpy, selmon->barwin, selmon->wx + sp, selmon->by + vp, selmon->ww - 2 * sp, bh);
1947         arrange(selmon);
1948 }
1949
1950 void
1951 togglefloating(const Arg *arg)
1952 {
1953         if (!selmon->sel)
1954                 return;
1955         selmon->sel->isfloating = !selmon->sel->isfloating || selmon->sel->isfixed;
1956         if (selmon->sel->isfloating)
1957                 resize(selmon->sel, selmon->sel->x, selmon->sel->y,
1958                         selmon->sel->w, selmon->sel->h, 0);
1959         arrange(selmon);
1960 }
1961
1962 void
1963 toggletag(const Arg *arg)
1964 {
1965         unsigned int newtags;
1966
1967         if (!selmon->sel)
1968                 return;
1969         newtags = selmon->sel->tags ^ (arg->ui & TAGMASK);
1970         if (newtags) {
1971                 selmon->sel->tags = newtags;
1972                 focus(NULL);
1973                 arrange(selmon);
1974         }
1975 }
1976
1977 void
1978 toggleview(const Arg *arg)
1979 {
1980         unsigned int newtagset = selmon->tagset[selmon->seltags] ^ (arg->ui & TAGMASK);
1981         int i;
1982
1983         if (newtagset) {
1984                 selmon->tagset[selmon->seltags] = newtagset;
1985
1986                 if (newtagset == ~0) {
1987                         selmon->pertag->prevtag = selmon->pertag->curtag;
1988                         selmon->pertag->curtag = 0;
1989                 }
1990
1991                 /* test if the user did not select the same tag */
1992                 if (!(newtagset & 1 << (selmon->pertag->curtag - 1))) {
1993                         selmon->pertag->prevtag = selmon->pertag->curtag;
1994                         for (i = 0; !(newtagset & 1 << i); i++) ;
1995                         selmon->pertag->curtag = i + 1;
1996                 }
1997
1998                 /* apply settings for this view */
1999                 selmon->nmaster = selmon->pertag->nmasters[selmon->pertag->curtag];
2000                 selmon->mfact = selmon->pertag->mfacts[selmon->pertag->curtag];
2001                 selmon->sellt = selmon->pertag->sellts[selmon->pertag->curtag];
2002                 selmon->lt[selmon->sellt] = selmon->pertag->ltidxs[selmon->pertag->curtag][selmon->sellt];
2003                 selmon->lt[selmon->sellt^1] = selmon->pertag->ltidxs[selmon->pertag->curtag][selmon->sellt^1];
2004
2005                 if (selmon->showbar != selmon->pertag->showbars[selmon->pertag->curtag])
2006                         togglebar(NULL);
2007
2008                 focus(NULL);
2009                 arrange(selmon);
2010         }
2011 }
2012
2013 void
2014 unfocus(Client *c, int setfocus)
2015 {
2016         if (!c)
2017                 return;
2018         grabbuttons(c, 0);
2019         XSetWindowBorder(dpy, c->win, scheme[SchemeNorm][ColBorder].pixel);
2020         if (setfocus) {
2021                 XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
2022                 XDeleteProperty(dpy, root, netatom[NetActiveWindow]);
2023         }
2024 }
2025
2026 void
2027 unmanage(Client *c, int destroyed)
2028 {
2029         Monitor *m = c->mon;
2030         XWindowChanges wc;
2031
2032         if (c->swallowing) {
2033                 unswallow(c);
2034                 return;
2035         }
2036
2037         Client *s = swallowingclient(c->win);
2038         if (s) {
2039                 free(s->swallowing);
2040                 s->swallowing = NULL;
2041                 arrange(m);
2042                 focus(NULL);
2043                 return;
2044         }
2045
2046         detach(c);
2047         detachstack(c);
2048         if (!destroyed) {
2049                 wc.border_width = c->oldbw;
2050                 XGrabServer(dpy); /* avoid race conditions */
2051                 XSetErrorHandler(xerrordummy);
2052                 XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
2053                 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
2054                 setclientstate(c, WithdrawnState);
2055                 XSync(dpy, False);
2056                 XSetErrorHandler(xerror);
2057                 XUngrabServer(dpy);
2058         }
2059         free(c);
2060
2061         if (!s) {
2062                 arrange(m);
2063                 focus(NULL);
2064                 updateclientlist();
2065         }
2066 }
2067
2068 void
2069 unmapnotify(XEvent *e)
2070 {
2071         Client *c;
2072         XUnmapEvent *ev = &e->xunmap;
2073
2074         if ((c = wintoclient(ev->window))) {
2075                 if (ev->send_event)
2076                         setclientstate(c, WithdrawnState);
2077                 else
2078                         unmanage(c, 0);
2079         }
2080 }
2081
2082 void
2083 updatebars(void)
2084 {
2085         Monitor *m;
2086         XSetWindowAttributes wa = {
2087                 .override_redirect = True,
2088                 .background_pixmap = ParentRelative,
2089                 .event_mask = ButtonPressMask|ExposureMask
2090         };
2091         XClassHint ch = {"dwm", "dwm"};
2092         for (m = mons; m; m = m->next) {
2093                 if (m->barwin)
2094                         continue;
2095                 m->barwin = XCreateWindow(dpy, root, m->wx + sp, m->by + vp, m->ww - 2 * sp, bh, 0, DefaultDepth(dpy, screen),
2096                                 CopyFromParent, DefaultVisual(dpy, screen),
2097                                 CWOverrideRedirect|CWBackPixmap|CWEventMask, &wa);
2098                 XDefineCursor(dpy, m->barwin, cursor[CurNormal]->cursor);
2099                 XMapRaised(dpy, m->barwin);
2100                 XSetClassHint(dpy, m->barwin, &ch);
2101         }
2102 }
2103
2104 void
2105 updatebarpos(Monitor *m)
2106 {
2107         m->wy = m->my;
2108         m->wh = m->mh;
2109         if (m->showbar) {
2110                 m->wh = m->wh - vertpad - bh;
2111                 m->by = m->topbar ? m->wy : m->wy + m->wh + vertpad;
2112                 m->wy = m->topbar ? m->wy + bh + vp : m->wy;
2113         } else
2114                 m->by = -bh - vp;
2115 }
2116
2117 void
2118 updateclientlist()
2119 {
2120         Client *c;
2121         Monitor *m;
2122
2123         XDeleteProperty(dpy, root, netatom[NetClientList]);
2124         for (m = mons; m; m = m->next)
2125                 for (c = m->clients; c; c = c->next)
2126                         XChangeProperty(dpy, root, netatom[NetClientList],
2127                                 XA_WINDOW, 32, PropModeAppend,
2128                                 (unsigned char *) &(c->win), 1);
2129 }
2130
2131 int
2132 updategeom(void)
2133 {
2134         int dirty = 0;
2135
2136 #ifdef XINERAMA
2137         if (XineramaIsActive(dpy)) {
2138                 int i, j, n, nn;
2139                 Client *c;
2140                 Monitor *m;
2141                 XineramaScreenInfo *info = XineramaQueryScreens(dpy, &nn);
2142                 XineramaScreenInfo *unique = NULL;
2143
2144                 for (n = 0, m = mons; m; m = m->next, n++);
2145                 /* only consider unique geometries as separate screens */
2146                 unique = ecalloc(nn, sizeof(XineramaScreenInfo));
2147                 for (i = 0, j = 0; i < nn; i++)
2148                         if (isuniquegeom(unique, j, &info[i]))
2149                                 memcpy(&unique[j++], &info[i], sizeof(XineramaScreenInfo));
2150                 XFree(info);
2151                 nn = j;
2152                 if (n <= nn) { /* new monitors available */
2153                         for (i = 0; i < (nn - n); i++) {
2154                                 for (m = mons; m && m->next; m = m->next);
2155                                 if (m)
2156                                         m->next = createmon();
2157                                 else
2158                                         mons = createmon();
2159                         }
2160                         for (i = 0, m = mons; i < nn && m; m = m->next, i++)
2161                                 if (i >= n
2162                                 || unique[i].x_org != m->mx || unique[i].y_org != m->my
2163                                 || unique[i].width != m->mw || unique[i].height != m->mh)
2164                                 {
2165                                         dirty = 1;
2166                                         m->num = i;
2167                                         m->mx = m->wx = unique[i].x_org;
2168                                         m->my = m->wy = unique[i].y_org;
2169                                         m->mw = m->ww = unique[i].width;
2170                                         m->mh = m->wh = unique[i].height;
2171                                         updatebarpos(m);
2172                                 }
2173                 } else { /* less monitors available nn < n */
2174                         for (i = nn; i < n; i++) {
2175                                 for (m = mons; m && m->next; m = m->next);
2176                                 while ((c = m->clients)) {
2177                                         dirty = 1;
2178                                         m->clients = c->next;
2179                                         detachstack(c);
2180                                         c->mon = mons;
2181                                         attach(c);
2182                                         attachstack(c);
2183                                 }
2184                                 if (m == selmon)
2185                                         selmon = mons;
2186                                 cleanupmon(m);
2187                         }
2188                 }
2189                 free(unique);
2190         } else
2191 #endif /* XINERAMA */
2192         { /* default monitor setup */
2193                 if (!mons)
2194                         mons = createmon();
2195                 if (mons->mw != sw || mons->mh != sh) {
2196                         dirty = 1;
2197                         mons->mw = mons->ww = sw;
2198                         mons->mh = mons->wh = sh;
2199                         updatebarpos(mons);
2200                 }
2201         }
2202         if (dirty) {
2203                 selmon = mons;
2204                 selmon = wintomon(root);
2205         }
2206         return dirty;
2207 }
2208
2209 void
2210 updatenumlockmask(void)
2211 {
2212         unsigned int i, j;
2213         XModifierKeymap *modmap;
2214
2215         numlockmask = 0;
2216         modmap = XGetModifierMapping(dpy);
2217         for (i = 0; i < 8; i++)
2218                 for (j = 0; j < modmap->max_keypermod; j++)
2219                         if (modmap->modifiermap[i * modmap->max_keypermod + j]
2220                                 == XKeysymToKeycode(dpy, XK_Num_Lock))
2221                                 numlockmask = (1 << i);
2222         XFreeModifiermap(modmap);
2223 }
2224
2225 void
2226 updatesizehints(Client *c)
2227 {
2228         long msize;
2229         XSizeHints size;
2230
2231         if (!XGetWMNormalHints(dpy, c->win, &size, &msize))
2232                 /* size is uninitialized, ensure that size.flags aren't used */
2233                 size.flags = PSize;
2234         if (size.flags & PBaseSize) {
2235                 c->basew = size.base_width;
2236                 c->baseh = size.base_height;
2237         } else if (size.flags & PMinSize) {
2238                 c->basew = size.min_width;
2239                 c->baseh = size.min_height;
2240         } else
2241                 c->basew = c->baseh = 0;
2242         if (size.flags & PResizeInc) {
2243                 c->incw = size.width_inc;
2244                 c->inch = size.height_inc;
2245         } else
2246                 c->incw = c->inch = 0;
2247         if (size.flags & PMaxSize) {
2248                 c->maxw = size.max_width;
2249                 c->maxh = size.max_height;
2250         } else
2251                 c->maxw = c->maxh = 0;
2252         if (size.flags & PMinSize) {
2253                 c->minw = size.min_width;
2254                 c->minh = size.min_height;
2255         } else if (size.flags & PBaseSize) {
2256                 c->minw = size.base_width;
2257                 c->minh = size.base_height;
2258         } else
2259                 c->minw = c->minh = 0;
2260         if (size.flags & PAspect) {
2261                 c->mina = (float)size.min_aspect.y / size.min_aspect.x;
2262                 c->maxa = (float)size.max_aspect.x / size.max_aspect.y;
2263         } else
2264                 c->maxa = c->mina = 0.0;
2265         c->isfixed = (c->maxw && c->maxh && c->maxw == c->minw && c->maxh == c->minh);
2266 }
2267
2268 void
2269 updatestatus(void)
2270 {
2271         if (!gettextprop(root, XA_WM_NAME, stext, sizeof(stext)))
2272                 strcpy(stext, "dwm-"VERSION);
2273         drawbar(selmon);
2274 }
2275
2276 void
2277 updatetitle(Client *c)
2278 {
2279         if (!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
2280                 gettextprop(c->win, XA_WM_NAME, c->name, sizeof c->name);
2281         if (c->name[0] == '\0') /* hack to mark broken clients */
2282                 strcpy(c->name, broken);
2283 }
2284
2285 void
2286 updatewindowtype(Client *c)
2287 {
2288         Atom state = getatomprop(c, netatom[NetWMState]);
2289         Atom wtype = getatomprop(c, netatom[NetWMWindowType]);
2290
2291         if (state == netatom[NetWMFullscreen])
2292                 setfullscreen(c, 1);
2293         if (wtype == netatom[NetWMWindowTypeDialog])
2294                 c->isfloating = 1;
2295 }
2296
2297 void
2298 updatewmhints(Client *c)
2299 {
2300         XWMHints *wmh;
2301
2302         if ((wmh = XGetWMHints(dpy, c->win))) {
2303                 if (c == selmon->sel && wmh->flags & XUrgencyHint) {
2304                         wmh->flags &= ~XUrgencyHint;
2305                         XSetWMHints(dpy, c->win, wmh);
2306                 } else
2307                         c->isurgent = (wmh->flags & XUrgencyHint) ? 1 : 0;
2308                 if (wmh->flags & InputHint)
2309                         c->neverfocus = !wmh->input;
2310                 else
2311                         c->neverfocus = 0;
2312                 XFree(wmh);
2313         }
2314 }
2315
2316 void
2317 view(const Arg *arg)
2318 {
2319         int i;
2320         unsigned int tmptag;
2321
2322         if ((arg->ui & TAGMASK) == selmon->tagset[selmon->seltags])
2323                 return;
2324         selmon->seltags ^= 1; /* toggle sel tagset */
2325         if (arg->ui & TAGMASK) {
2326                 selmon->tagset[selmon->seltags] = arg->ui & TAGMASK;
2327                 selmon->pertag->prevtag = selmon->pertag->curtag;
2328
2329                 if (arg->ui == ~0)
2330                         selmon->pertag->curtag = 0;
2331                 else {
2332                         for (i = 0; !(arg->ui & 1 << i); i++) ;
2333                         selmon->pertag->curtag = i + 1;
2334                 }
2335         } else {
2336                 tmptag = selmon->pertag->prevtag;
2337                 selmon->pertag->prevtag = selmon->pertag->curtag;
2338                 selmon->pertag->curtag = tmptag;
2339         }
2340
2341         selmon->nmaster = selmon->pertag->nmasters[selmon->pertag->curtag];
2342         selmon->mfact = selmon->pertag->mfacts[selmon->pertag->curtag];
2343         selmon->sellt = selmon->pertag->sellts[selmon->pertag->curtag];
2344         selmon->lt[selmon->sellt] = selmon->pertag->ltidxs[selmon->pertag->curtag][selmon->sellt];
2345         selmon->lt[selmon->sellt^1] = selmon->pertag->ltidxs[selmon->pertag->curtag][selmon->sellt^1];
2346
2347         if (selmon->showbar != selmon->pertag->showbars[selmon->pertag->curtag])
2348                 togglebar(NULL);
2349
2350         focus(NULL);
2351         arrange(selmon);
2352 }
2353
2354 pid_t
2355 winpid(Window w)
2356 {
2357
2358         pid_t result = 0;
2359
2360         #ifdef __linux__
2361         xcb_res_client_id_spec_t spec = {0};
2362         spec.client = w;
2363         spec.mask = XCB_RES_CLIENT_ID_MASK_LOCAL_CLIENT_PID;
2364
2365         xcb_generic_error_t *e = NULL;
2366         xcb_res_query_client_ids_cookie_t c = xcb_res_query_client_ids(xcon, 1, &spec);
2367         xcb_res_query_client_ids_reply_t *r = xcb_res_query_client_ids_reply(xcon, c, &e);
2368
2369         if (!r)
2370                 return (pid_t)0;
2371
2372         xcb_res_client_id_value_iterator_t i = xcb_res_query_client_ids_ids_iterator(r);
2373         for (; i.rem; xcb_res_client_id_value_next(&i)) {
2374                 spec = i.data->spec;
2375                 if (spec.mask & XCB_RES_CLIENT_ID_MASK_LOCAL_CLIENT_PID) {
2376                         uint32_t *t = xcb_res_client_id_value_value(i.data);
2377                         result = *t;
2378                         break;
2379                 }
2380         }
2381
2382         free(r);
2383
2384         if (result == (pid_t)-1)
2385                 result = 0;
2386
2387         #endif /* __linux__ */
2388
2389         #ifdef __OpenBSD__
2390         Atom type;
2391         int format;
2392         unsigned long len, bytes;
2393         unsigned char *prop;
2394         pid_t ret;
2395
2396         if (XGetWindowProperty(dpy, w, XInternAtom(dpy, "_NET_WM_PID", 1), 0, 1, False, AnyPropertyType, &type, &format, &len, &bytes, &prop) != Success || !prop)
2397                return 0;
2398
2399         ret = *(pid_t*)prop;
2400         XFree(prop);
2401         result = ret;
2402
2403         #endif /* __OpenBSD__ */
2404         return result;
2405 }
2406
2407 pid_t
2408 getparentprocess(pid_t p)
2409 {
2410         unsigned int v = 0;
2411
2412 #ifdef __linux__
2413         FILE *f;
2414         char buf[256];
2415         snprintf(buf, sizeof(buf) - 1, "/proc/%u/stat", (unsigned)p);
2416
2417         if (!(f = fopen(buf, "r")))
2418                 return 0;
2419
2420         fscanf(f, "%*u %*s %*c %u", &v);
2421         fclose(f);
2422 #endif /* __linux__*/
2423
2424 #ifdef __OpenBSD__
2425         int n;
2426         kvm_t *kd;
2427         struct kinfo_proc *kp;
2428
2429         kd = kvm_openfiles(NULL, NULL, NULL, KVM_NO_FILES, NULL);
2430         if (!kd)
2431                 return 0;
2432
2433         kp = kvm_getprocs(kd, KERN_PROC_PID, p, sizeof(*kp), &n);
2434         v = kp->p_ppid;
2435 #endif /* __OpenBSD__ */
2436
2437         return (pid_t)v;
2438 }
2439
2440 int
2441 isdescprocess(pid_t p, pid_t c)
2442 {
2443         while (p != c && c != 0)
2444                 c = getparentprocess(c);
2445
2446         return (int)c;
2447 }
2448
2449 Client *
2450 termforwin(const Client *w)
2451 {
2452         Client *c;
2453         Monitor *m;
2454
2455         if (!w->pid || w->isterminal)
2456                 return NULL;
2457
2458         for (m = mons; m; m = m->next) {
2459                 for (c = m->clients; c; c = c->next) {
2460                         if (c->isterminal && !c->swallowing && c->pid && isdescprocess(c->pid, w->pid))
2461                                 return c;
2462                 }
2463         }
2464
2465         return NULL;
2466 }
2467
2468 Client *
2469 swallowingclient(Window w)
2470 {
2471         Client *c;
2472         Monitor *m;
2473
2474         for (m = mons; m; m = m->next) {
2475                 for (c = m->clients; c; c = c->next) {
2476                         if (c->swallowing && c->swallowing->win == w)
2477                                 return c;
2478                 }
2479         }
2480
2481         return NULL;
2482 }
2483
2484 Client *
2485 wintoclient(Window w)
2486 {
2487         Client *c;
2488         Monitor *m;
2489
2490         for (m = mons; m; m = m->next)
2491                 for (c = m->clients; c; c = c->next)
2492                         if (c->win == w)
2493                                 return c;
2494         return NULL;
2495 }
2496
2497 Monitor *
2498 wintomon(Window w)
2499 {
2500         int x, y;
2501         Client *c;
2502         Monitor *m;
2503
2504         if (w == root && getrootptr(&x, &y))
2505                 return recttomon(x, y, 1, 1);
2506         for (m = mons; m; m = m->next)
2507                 if (w == m->barwin)
2508                         return m;
2509         if ((c = wintoclient(w)))
2510                 return c->mon;
2511         return selmon;
2512 }
2513
2514 /* There's no way to check accesses to destroyed windows, thus those cases are
2515  * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
2516  * default error handler, which may call exit. */
2517 int
2518 xerror(Display *dpy, XErrorEvent *ee)
2519 {
2520         if (ee->error_code == BadWindow
2521         || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
2522         || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
2523         || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
2524         || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
2525         || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
2526         || (ee->request_code == X_GrabButton && ee->error_code == BadAccess)
2527         || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
2528         || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
2529                 return 0;
2530         fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
2531                 ee->request_code, ee->error_code);
2532         return xerrorxlib(dpy, ee); /* may call exit */
2533 }
2534
2535 int
2536 xerrordummy(Display *dpy, XErrorEvent *ee)
2537 {
2538         return 0;
2539 }
2540
2541 /* Startup Error handler to check if another window manager
2542  * is already running. */
2543 int
2544 xerrorstart(Display *dpy, XErrorEvent *ee)
2545 {
2546         die("dwm: another window manager is already running");
2547         return -1;
2548 }
2549
2550 void
2551 zoom(const Arg *arg)
2552 {
2553         Client *c = selmon->sel;
2554
2555         if (!selmon->lt[selmon->sellt]->arrange
2556         || (selmon->sel && selmon->sel->isfloating))
2557                 return;
2558         if (c == nexttiled(selmon->clients))
2559                 if (!c || !(c = nexttiled(c->next)))
2560                         return;
2561         pop(c);
2562 }
2563
2564 void
2565 resource_load(XrmDatabase db, char *name, enum resource_type rtype, void *dst)
2566 {
2567         char *sdst = NULL;
2568         int *idst = NULL;
2569         float *fdst = NULL;
2570
2571         sdst = dst;
2572         idst = dst;
2573         fdst = dst;
2574
2575         char fullname[256];
2576         char *type;
2577         XrmValue ret;
2578
2579         snprintf(fullname, sizeof(fullname), "%s.%s", "dwm", name);
2580         fullname[sizeof(fullname) - 1] = '\0';
2581
2582         XrmGetResource(db, fullname, "*", &type, &ret);
2583         if (!(ret.addr == NULL || strncmp("String", type, 64)))
2584         {
2585                 switch (rtype) {
2586                 case STRING:
2587                         strcpy(sdst, ret.addr);
2588                         break;
2589                 case INTEGER:
2590                         *idst = strtoul(ret.addr, NULL, 10);
2591                         break;
2592                 case FLOAT:
2593                         *fdst = strtof(ret.addr, NULL);
2594                         break;
2595                 }
2596         }
2597 }
2598
2599 void
2600 load_xresources(void)
2601 {
2602         Display *display;
2603         char *resm;
2604         XrmDatabase db;
2605         ResourcePref *p;
2606
2607         display = XOpenDisplay(NULL);
2608         resm = XResourceManagerString(display);
2609         if (!resm)
2610                 return;
2611
2612         db = XrmGetStringDatabase(resm);
2613         for (p = resources; p < resources + LENGTH(resources); p++)
2614                 resource_load(db, p->name, p->type, p->dst);
2615         XCloseDisplay(display);
2616 }
2617
2618 int
2619 main(int argc, char *argv[])
2620 {
2621         if (argc == 2 && !strcmp("-v", argv[1]))
2622                 die("dwm-"VERSION);
2623         else if (argc != 1)
2624                 die("usage: dwm [-v]");
2625         if (!setlocale(LC_CTYPE, "") || !XSupportsLocale())
2626                 fputs("warning: no locale support\n", stderr);
2627         if (!(dpy = XOpenDisplay(NULL)))
2628                 die("dwm: cannot open display");
2629         if (!(xcon = XGetXCBConnection(dpy)))
2630                 die("dwm: cannot get xcb connection\n");
2631         checkotherwm();
2632         XrmInitialize();
2633         load_xresources();
2634         setup();
2635 #ifdef __OpenBSD__
2636         if (pledge("stdio rpath proc exec ps", NULL) == -1)
2637                 die("pledge");
2638 #endif /* __OpenBSD__ */
2639         scan();
2640         runautostart();
2641         run();
2642         cleanup();
2643         XCloseDisplay(dpy);
2644         return EXIT_SUCCESS;
2645 }