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