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