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