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