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