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