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