]> git.armaanb.net Git - dwm.git/blob - dwm.c
Apply resizecorners patch
[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         if (selmon->sel)
907                 XWarpPointer(dpy, None, selmon->sel->win, 0, 0, 0, 0, selmon->sel->w/2, selmon->sel->h/2);
908 }
909
910 void
911 focusstack(const Arg *arg)
912 {
913         Client *c = NULL, *i;
914
915         if (!selmon->sel)
916                 return;
917         if (arg->i > 0) {
918                 for (c = selmon->sel->next; c && !ISVISIBLE(c); c = c->next);
919                 if (!c)
920                         for (c = selmon->clients; c && !ISVISIBLE(c); c = c->next);
921         } else {
922                 for (i = selmon->clients; i != selmon->sel; i = i->next)
923                         if (ISVISIBLE(i))
924                                 c = i;
925                 if (!c)
926                         for (; i; i = i->next)
927                                 if (ISVISIBLE(i))
928                                         c = i;
929         }
930         if (c) {
931                 focus(c);
932                 restack(selmon);
933                 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w/2, c->h/2);
934         }
935 }
936
937 Atom
938 getatomprop(Client *c, Atom prop)
939 {
940         int di;
941         unsigned long dl;
942         unsigned char *p = NULL;
943         Atom da, atom = None;
944
945         if (XGetWindowProperty(dpy, c->win, prop, 0L, sizeof atom, False, XA_ATOM,
946                 &da, &di, &dl, &dl, &p) == Success && p) {
947                 atom = *(Atom *)p;
948                 XFree(p);
949         }
950         return atom;
951 }
952
953 int
954 getrootptr(int *x, int *y)
955 {
956         int di;
957         unsigned int dui;
958         Window dummy;
959
960         return XQueryPointer(dpy, root, &dummy, &dummy, x, y, &di, &di, &dui);
961 }
962
963 long
964 getstate(Window w)
965 {
966         int format;
967         long result = -1;
968         unsigned char *p = NULL;
969         unsigned long n, extra;
970         Atom real;
971
972         if (XGetWindowProperty(dpy, w, wmatom[WMState], 0L, 2L, False, wmatom[WMState],
973                 &real, &format, &n, &extra, (unsigned char **)&p) != Success)
974                 return -1;
975         if (n != 0)
976                 result = *p;
977         XFree(p);
978         return result;
979 }
980
981 int
982 gettextprop(Window w, Atom atom, char *text, unsigned int size)
983 {
984         char **list = NULL;
985         int n;
986         XTextProperty name;
987
988         if (!text || size == 0)
989                 return 0;
990         text[0] = '\0';
991         if (!XGetTextProperty(dpy, w, &name, atom) || !name.nitems)
992                 return 0;
993         if (name.encoding == XA_STRING)
994                 strncpy(text, (char *)name.value, size - 1);
995         else {
996                 if (XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success && n > 0 && *list) {
997                         strncpy(text, *list, size - 1);
998                         XFreeStringList(list);
999                 }
1000         }
1001         text[size - 1] = '\0';
1002         XFree(name.value);
1003         return 1;
1004 }
1005
1006 void
1007 grabbuttons(Client *c, int focused)
1008 {
1009         updatenumlockmask();
1010         {
1011                 unsigned int i, j;
1012                 unsigned int modifiers[] = { 0, LockMask, numlockmask, numlockmask|LockMask };
1013                 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1014                 if (!focused)
1015                         XGrabButton(dpy, AnyButton, AnyModifier, c->win, False,
1016                                 BUTTONMASK, GrabModeSync, GrabModeSync, None, None);
1017                 for (i = 0; i < LENGTH(buttons); i++)
1018                         if (buttons[i].click == ClkClientWin)
1019                                 for (j = 0; j < LENGTH(modifiers); j++)
1020                                         XGrabButton(dpy, buttons[i].button,
1021                                                 buttons[i].mask | modifiers[j],
1022                                                 c->win, False, BUTTONMASK,
1023                                                 GrabModeAsync, GrabModeSync, None, None);
1024         }
1025 }
1026
1027 void
1028 grabkeys(void)
1029 {
1030         updatenumlockmask();
1031         {
1032                 unsigned int i, j;
1033                 unsigned int modifiers[] = { 0, LockMask, numlockmask, numlockmask|LockMask };
1034                 KeyCode code;
1035
1036                 XUngrabKey(dpy, AnyKey, AnyModifier, root);
1037                 for (i = 0; i < LENGTH(keys); i++)
1038                         if ((code = XKeysymToKeycode(dpy, keys[i].keysym)))
1039                                 for (j = 0; j < LENGTH(modifiers); j++)
1040                                         XGrabKey(dpy, code, keys[i].mod | modifiers[j], root,
1041                                                 True, GrabModeAsync, GrabModeAsync);
1042         }
1043 }
1044
1045 void
1046 incnmaster(const Arg *arg)
1047 {
1048         selmon->nmaster = selmon->pertag->nmasters[selmon->pertag->curtag] = MAX(selmon->nmaster + arg->i, 0);
1049         arrange(selmon);
1050 }
1051
1052 #ifdef XINERAMA
1053 static int
1054 isuniquegeom(XineramaScreenInfo *unique, size_t n, XineramaScreenInfo *info)
1055 {
1056         while (n--)
1057                 if (unique[n].x_org == info->x_org && unique[n].y_org == info->y_org
1058                 && unique[n].width == info->width && unique[n].height == info->height)
1059                         return 0;
1060         return 1;
1061 }
1062 #endif /* XINERAMA */
1063
1064 void
1065 keypress(XEvent *e)
1066 {
1067         unsigned int i;
1068         KeySym keysym;
1069         XKeyEvent *ev;
1070
1071         ev = &e->xkey;
1072         keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
1073         for (i = 0; i < LENGTH(keys); i++)
1074                 if (keysym == keys[i].keysym
1075                 && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state)
1076                 && keys[i].func)
1077                         keys[i].func(&(keys[i].arg));
1078 }
1079
1080 void
1081 killclient(const Arg *arg)
1082 {
1083         if (!selmon->sel)
1084                 return;
1085         if (!sendevent(selmon->sel, wmatom[WMDelete])) {
1086                 XGrabServer(dpy);
1087                 XSetErrorHandler(xerrordummy);
1088                 XSetCloseDownMode(dpy, DestroyAll);
1089                 XKillClient(dpy, selmon->sel->win);
1090                 XSync(dpy, False);
1091                 XSetErrorHandler(xerror);
1092                 XUngrabServer(dpy);
1093         }
1094 }
1095
1096 void
1097 manage(Window w, XWindowAttributes *wa)
1098 {
1099         Client *c, *t = NULL;
1100         Window trans = None;
1101         XWindowChanges wc;
1102
1103         c = ecalloc(1, sizeof(Client));
1104         c->win = w;
1105         /* geometry */
1106         c->x = c->oldx = wa->x;
1107         c->y = c->oldy = wa->y;
1108         c->w = c->oldw = wa->width;
1109         c->h = c->oldh = wa->height;
1110         c->oldbw = wa->border_width;
1111
1112         updatetitle(c);
1113         if (XGetTransientForHint(dpy, w, &trans) && (t = wintoclient(trans))) {
1114                 c->mon = t->mon;
1115                 c->tags = t->tags;
1116         } else {
1117                 c->mon = selmon;
1118                 applyrules(c);
1119         }
1120
1121         if (c->x + WIDTH(c) > c->mon->mx + c->mon->mw)
1122                 c->x = c->mon->mx + c->mon->mw - WIDTH(c);
1123         if (c->y + HEIGHT(c) > c->mon->my + c->mon->mh)
1124                 c->y = c->mon->my + c->mon->mh - HEIGHT(c);
1125         c->x = MAX(c->x, c->mon->mx);
1126         /* only fix client y-offset, if the client center might cover the bar */
1127         c->y = MAX(c->y, ((c->mon->by == c->mon->my) && (c->x + (c->w / 2) >= c->mon->wx)
1128                 && (c->x + (c->w / 2) < c->mon->wx + c->mon->ww)) ? bh : c->mon->my);
1129         c->bw = borderpx;
1130
1131         wc.border_width = c->bw;
1132         XConfigureWindow(dpy, w, CWBorderWidth, &wc);
1133         XSetWindowBorder(dpy, w, scheme[SchemeNorm][ColBorder].pixel);
1134         configure(c); /* propagates border_width, if size doesn't change */
1135         updatewindowtype(c);
1136         updatesizehints(c);
1137         updatewmhints(c);
1138         XSelectInput(dpy, w, EnterWindowMask|FocusChangeMask|PropertyChangeMask|StructureNotifyMask);
1139         grabbuttons(c, 0);
1140         if (!c->isfloating)
1141                 c->isfloating = c->oldstate = trans != None || c->isfixed;
1142         if (c->isfloating)
1143                 XRaiseWindow(dpy, c->win);
1144         attachbottom(c);
1145         attachstack(c);
1146         XChangeProperty(dpy, root, netatom[NetClientList], XA_WINDOW, 32, PropModeAppend,
1147                 (unsigned char *) &(c->win), 1);
1148         XMoveResizeWindow(dpy, c->win, c->x + 2 * sw, c->y, c->w, c->h); /* some windows require this */
1149         setclientstate(c, NormalState);
1150         if (c->mon == selmon)
1151                 unfocus(selmon->sel, 0);
1152         c->mon->sel = c;
1153         arrange(c->mon);
1154         XMapWindow(dpy, c->win);
1155         focus(NULL);
1156 }
1157
1158 void
1159 mappingnotify(XEvent *e)
1160 {
1161         XMappingEvent *ev = &e->xmapping;
1162
1163         XRefreshKeyboardMapping(ev);
1164         if (ev->request == MappingKeyboard)
1165                 grabkeys();
1166 }
1167
1168 void
1169 maprequest(XEvent *e)
1170 {
1171         static XWindowAttributes wa;
1172         XMapRequestEvent *ev = &e->xmaprequest;
1173
1174         if (!XGetWindowAttributes(dpy, ev->window, &wa))
1175                 return;
1176         if (wa.override_redirect)
1177                 return;
1178         if (!wintoclient(ev->window))
1179                 manage(ev->window, &wa);
1180 }
1181
1182 void
1183 monocle(Monitor *m)
1184 {
1185         unsigned int n = 0;
1186         Client *c;
1187
1188         for (c = m->clients; c; c = c->next)
1189                 if (ISVISIBLE(c))
1190                         n++;
1191         if (n > 0) /* override layout symbol */
1192                 snprintf(m->ltsymbol, sizeof m->ltsymbol, "[%d]", n);
1193         for (c = nexttiled(m->clients); c; c = nexttiled(c->next))
1194                 resize(c, m->wx, m->wy, m->ww - 2 * c->bw, m->wh - 2 * c->bw, 0);
1195 }
1196
1197 void
1198 motionnotify(XEvent *e)
1199 {
1200         static Monitor *mon = NULL;
1201         Monitor *m;
1202         XMotionEvent *ev = &e->xmotion;
1203
1204         if (ev->window != root)
1205                 return;
1206         if ((m = recttomon(ev->x_root, ev->y_root, 1, 1)) != mon && mon) {
1207                 unfocus(selmon->sel, 1);
1208                 selmon = m;
1209                 focus(NULL);
1210         }
1211         mon = m;
1212 }
1213
1214 void
1215 movemouse(const Arg *arg)
1216 {
1217         int x, y, ocx, ocy, nx, ny;
1218         Client *c;
1219         Monitor *m;
1220         XEvent ev;
1221         Time lasttime = 0;
1222
1223         if (!(c = selmon->sel))
1224                 return;
1225         restack(selmon);
1226         ocx = c->x;
1227         ocy = c->y;
1228         if (XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1229                 None, cursor[CurMove]->cursor, CurrentTime) != GrabSuccess)
1230                 return;
1231         if (!getrootptr(&x, &y))
1232                 return;
1233         do {
1234                 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
1235                 switch(ev.type) {
1236                 case ConfigureRequest:
1237                 case Expose:
1238                 case MapRequest:
1239                         handler[ev.type](&ev);
1240                         break;
1241                 case MotionNotify:
1242                         if ((ev.xmotion.time - lasttime) <= (1000 / 60))
1243                                 continue;
1244                         lasttime = ev.xmotion.time;
1245
1246                         nx = ocx + (ev.xmotion.x - x);
1247                         ny = ocy + (ev.xmotion.y - y);
1248                         if (abs(selmon->wx - nx) < snap)
1249                                 nx = selmon->wx;
1250                         else if (abs((selmon->wx + selmon->ww) - (nx + WIDTH(c))) < snap)
1251                                 nx = selmon->wx + selmon->ww - WIDTH(c);
1252                         if (abs(selmon->wy - ny) < snap)
1253                                 ny = selmon->wy;
1254                         else if (abs((selmon->wy + selmon->wh) - (ny + HEIGHT(c))) < snap)
1255                                 ny = selmon->wy + selmon->wh - HEIGHT(c);
1256                         if (!c->isfloating && selmon->lt[selmon->sellt]->arrange
1257                         && (abs(nx - c->x) > snap || abs(ny - c->y) > snap))
1258                                 togglefloating(NULL);
1259                         if (!selmon->lt[selmon->sellt]->arrange || c->isfloating)
1260                                 resize(c, nx, ny, c->w, c->h, 1);
1261                         break;
1262                 }
1263         } while (ev.type != ButtonRelease);
1264         XUngrabPointer(dpy, CurrentTime);
1265         if ((m = recttomon(c->x, c->y, c->w, c->h)) != selmon) {
1266                 sendmon(c, m);
1267                 selmon = m;
1268                 focus(NULL);
1269         }
1270 }
1271
1272 Client *
1273 nexttiled(Client *c)
1274 {
1275         for (; c && (c->isfloating || !ISVISIBLE(c)); c = c->next);
1276         return c;
1277 }
1278
1279 Client *
1280 prevtiled(Client *c) {
1281         Client *p, *r;
1282
1283         for(p = selmon->clients, r = NULL; p && p != c; p = p->next)
1284                 if(!p->isfloating && ISVISIBLE(p))
1285                         r = p;
1286         return r;
1287 }
1288
1289 void
1290 propertynotify(XEvent *e)
1291 {
1292         Client *c;
1293         Window trans;
1294         XPropertyEvent *ev = &e->xproperty;
1295
1296         if ((ev->window == root) && (ev->atom == XA_WM_NAME))
1297                 updatestatus();
1298         else if (ev->state == PropertyDelete)
1299                 return; /* ignore */
1300         else if ((c = wintoclient(ev->window))) {
1301                 switch(ev->atom) {
1302                 default: break;
1303                 case XA_WM_TRANSIENT_FOR:
1304                         if (!c->isfloating && (XGetTransientForHint(dpy, c->win, &trans)) &&
1305                                 (c->isfloating = (wintoclient(trans)) != NULL))
1306                                 arrange(c->mon);
1307                         break;
1308                 case XA_WM_NORMAL_HINTS:
1309                         updatesizehints(c);
1310                         break;
1311                 case XA_WM_HINTS:
1312                         updatewmhints(c);
1313                         drawbars();
1314                         break;
1315                 }
1316                 if (ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
1317                         updatetitle(c);
1318                         if (c == c->mon->sel)
1319                                 drawbar(c->mon);
1320                 }
1321                 if (ev->atom == netatom[NetWMWindowType])
1322                         updatewindowtype(c);
1323         }
1324 }
1325
1326 void
1327 pushdown(const Arg *arg) {
1328         Client *sel = selmon->sel, *c;
1329
1330         if(!sel || sel->isfloating)
1331                 return;
1332         if((c = nexttiled(sel->next))) {
1333                 detach(sel);
1334                 sel->next = c->next;
1335                 c->next = sel;
1336         } else {
1337                 detach(sel);
1338                 attach(sel);
1339         }
1340         focus(sel);
1341         arrange(selmon);
1342 }
1343
1344 void
1345 pushup(const Arg *arg) {
1346         Client *sel = selmon->sel, *c;
1347
1348         if(!sel || sel->isfloating)
1349                 return;
1350         if((c = prevtiled(sel))) {
1351                 detach(sel);
1352                 sel->next = c;
1353                 if(selmon->clients == c)
1354                         selmon->clients = sel;
1355                 else {
1356                         for(c = selmon->clients; c->next != sel->next; c = c->next);
1357                         c->next = sel;
1358                 }
1359         } else {
1360                 for(c = sel; c->next; c = c->next);
1361                 detach(sel);
1362                 sel->next = NULL;
1363                 c->next = sel;
1364         }
1365         focus(sel);
1366         arrange(selmon);
1367 }
1368
1369 void
1370 quit(const Arg *arg)
1371 {
1372         size_t i;
1373
1374         /* kill child processes */
1375         for (i = 0; i < autostart_len; i++) {
1376                 if (0 < autostart_pids[i]) {
1377                         kill(autostart_pids[i], SIGTERM);
1378                         waitpid(autostart_pids[i], NULL, 0);
1379                 }
1380         }
1381
1382         running = 0;
1383 }
1384
1385 Monitor *
1386 recttomon(int x, int y, int w, int h)
1387 {
1388         Monitor *m, *r = selmon;
1389         int a, area = 0;
1390
1391         for (m = mons; m; m = m->next)
1392                 if ((a = INTERSECT(x, y, w, h, m)) > area) {
1393                         area = a;
1394                         r = m;
1395                 }
1396         return r;
1397 }
1398
1399 void
1400 resize(Client *c, int x, int y, int w, int h, int interact)
1401 {
1402         if (applysizehints(c, &x, &y, &w, &h, interact))
1403                 resizeclient(c, x, y, w, h);
1404 }
1405
1406 void
1407 resizeclient(Client *c, int x, int y, int w, int h)
1408 {
1409         XWindowChanges wc;
1410
1411         c->oldx = c->x; c->x = wc.x = x;
1412         c->oldy = c->y; c->y = wc.y = y;
1413         c->oldw = c->w; c->w = wc.width = w;
1414         c->oldh = c->h; c->h = wc.height = h;
1415         wc.border_width = c->bw;
1416         XConfigureWindow(dpy, c->win, CWX|CWY|CWWidth|CWHeight|CWBorderWidth, &wc);
1417         configure(c);
1418         XSync(dpy, False);
1419 }
1420
1421 void
1422 resizemouse(const Arg *arg)
1423 {
1424         int ocx, ocy, nw, nh;
1425         int ocx2, ocy2, nx, ny;
1426         Client *c;
1427         Monitor *m;
1428         XEvent ev;
1429         int horizcorner, vertcorner;
1430         int di;
1431         unsigned int dui;
1432         Window dummy;
1433         Time lasttime = 0;
1434
1435         if (!(c = selmon->sel))
1436                 return;
1437         restack(selmon);
1438         ocx = c->x;
1439         ocy = c->y;
1440         ocx2 = c->x + c->w;
1441         ocy2 = c->y + c->h;
1442         if (XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1443                 None, cursor[CurResize]->cursor, CurrentTime) != GrabSuccess)
1444                 return;
1445         if (!XQueryPointer (dpy, c->win, &dummy, &dummy, &di, &di, &nx, &ny, &dui))
1446                 return;
1447         horizcorner = nx < c->w / 2;
1448         vertcorner  = ny < c->h / 2;
1449         XWarpPointer (dpy, None, c->win, 0, 0, 0, 0,
1450                         horizcorner ? (-c->bw) : (c->w + c->bw -1),
1451                         vertcorner  ? (-c->bw) : (c->h + c->bw -1));
1452         do {
1453                 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
1454                 switch(ev.type) {
1455                 case ConfigureRequest:
1456                 case Expose:
1457                 case MapRequest:
1458                         handler[ev.type](&ev);
1459                         break;
1460                 case MotionNotify:
1461                         if ((ev.xmotion.time - lasttime) <= (1000 / 60))
1462                                 continue;
1463                         lasttime = ev.xmotion.time;
1464
1465                         nw = MAX(ev.xmotion.x - ocx - 2 * c->bw + 1, 1);
1466                         nh = MAX(ev.xmotion.y - ocy - 2 * c->bw + 1, 1);
1467                         nx = horizcorner ? ev.xmotion.x : c->x;
1468                         ny = vertcorner ? ev.xmotion.y : c->y;
1469                         nw = MAX(horizcorner ? (ocx2 - nx) : (ev.xmotion.x - ocx - 2 * c->bw + 1), 1);
1470                         nh = MAX(vertcorner ? (ocy2 - ny) : (ev.xmotion.y - ocy - 2 * c->bw + 1), 1);
1471
1472                         if (c->mon->wx + nw >= selmon->wx && c->mon->wx + nw <= selmon->wx + selmon->ww
1473                         && c->mon->wy + nh >= selmon->wy && c->mon->wy + nh <= selmon->wy + selmon->wh)
1474                         {
1475                                 if (!c->isfloating && selmon->lt[selmon->sellt]->arrange
1476                                 && (abs(nw - c->w) > snap || abs(nh - c->h) > snap))
1477                                         togglefloating(NULL);
1478                         }
1479                         if (!selmon->lt[selmon->sellt]->arrange || c->isfloating)
1480                                 resize(c, nx, ny, nw, nh, 1);
1481                         break;
1482                 }
1483         } while (ev.type != ButtonRelease);
1484         XWarpPointer(dpy, None, c->win, 0, 0, 0, 0,
1485                       horizcorner ? (-c->bw) : (c->w + c->bw - 1),
1486                       vertcorner ? (-c->bw) : (c->h + c->bw - 1));
1487         XUngrabPointer(dpy, CurrentTime);
1488         while (XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1489         if ((m = recttomon(c->x, c->y, c->w, c->h)) != selmon) {
1490                 sendmon(c, m);
1491                 selmon = m;
1492                 focus(NULL);
1493         }
1494 }
1495
1496 void
1497 restack(Monitor *m)
1498 {
1499         Client *c;
1500         XEvent ev;
1501         XWindowChanges wc;
1502
1503         drawbar(m);
1504         if (!m->sel)
1505                 return;
1506         if (m->sel->isfloating || !m->lt[m->sellt]->arrange)
1507                 XRaiseWindow(dpy, m->sel->win);
1508         if (m->lt[m->sellt]->arrange) {
1509                 wc.stack_mode = Below;
1510                 wc.sibling = m->barwin;
1511                 for (c = m->stack; c; c = c->snext)
1512                         if (!c->isfloating && ISVISIBLE(c)) {
1513                                 XConfigureWindow(dpy, c->win, CWSibling|CWStackMode, &wc);
1514                                 wc.sibling = c->win;
1515                         }
1516         }
1517         XSync(dpy, False);
1518         while (XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1519 }
1520
1521 void
1522 run(void)
1523 {
1524         XEvent ev;
1525         /* main event loop */
1526         XSync(dpy, False);
1527         while (running && !XNextEvent(dpy, &ev))
1528                 if (handler[ev.type])
1529                         handler[ev.type](&ev); /* call handler */
1530 }
1531
1532 void
1533 scan(void)
1534 {
1535         unsigned int i, num;
1536         Window d1, d2, *wins = NULL;
1537         XWindowAttributes wa;
1538
1539         if (XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1540                 for (i = 0; i < num; i++) {
1541                         if (!XGetWindowAttributes(dpy, wins[i], &wa)
1542                         || wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1543                                 continue;
1544                         if (wa.map_state == IsViewable || getstate(wins[i]) == IconicState)
1545                                 manage(wins[i], &wa);
1546                 }
1547                 for (i = 0; i < num; i++) { /* now the transients */
1548                         if (!XGetWindowAttributes(dpy, wins[i], &wa))
1549                                 continue;
1550                         if (XGetTransientForHint(dpy, wins[i], &d1)
1551                         && (wa.map_state == IsViewable || getstate(wins[i]) == IconicState))
1552                                 manage(wins[i], &wa);
1553                 }
1554                 if (wins)
1555                         XFree(wins);
1556         }
1557 }
1558
1559 void
1560 sendmon(Client *c, Monitor *m)
1561 {
1562         if (c->mon == m)
1563                 return;
1564         unfocus(c, 1);
1565         detach(c);
1566         detachstack(c);
1567         c->mon = m;
1568         c->tags = m->tagset[m->seltags]; /* assign tags of target monitor */
1569         attachbottom(c);
1570         attachstack(c);
1571         focus(NULL);
1572         arrange(NULL);
1573 }
1574
1575 void
1576 setclientstate(Client *c, long state)
1577 {
1578         long data[] = { state, None };
1579
1580         XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1581                 PropModeReplace, (unsigned char *)data, 2);
1582 }
1583
1584 int
1585 sendevent(Client *c, Atom proto)
1586 {
1587         int n;
1588         Atom *protocols;
1589         int exists = 0;
1590         XEvent ev;
1591
1592         if (XGetWMProtocols(dpy, c->win, &protocols, &n)) {
1593                 while (!exists && n--)
1594                         exists = protocols[n] == proto;
1595                 XFree(protocols);
1596         }
1597         if (exists) {
1598                 ev.type = ClientMessage;
1599                 ev.xclient.window = c->win;
1600                 ev.xclient.message_type = wmatom[WMProtocols];
1601                 ev.xclient.format = 32;
1602                 ev.xclient.data.l[0] = proto;
1603                 ev.xclient.data.l[1] = CurrentTime;
1604                 XSendEvent(dpy, c->win, False, NoEventMask, &ev);
1605         }
1606         return exists;
1607 }
1608
1609 void
1610 setfocus(Client *c)
1611 {
1612         if (!c->neverfocus) {
1613                 XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
1614                 XChangeProperty(dpy, root, netatom[NetActiveWindow],
1615                         XA_WINDOW, 32, PropModeReplace,
1616                         (unsigned char *) &(c->win), 1);
1617         }
1618         sendevent(c, wmatom[WMTakeFocus]);
1619 }
1620
1621 void
1622 setfullscreen(Client *c, int fullscreen)
1623 {
1624         if (fullscreen && !c->isfullscreen) {
1625                 XChangeProperty(dpy, c->win, netatom[NetWMState], XA_ATOM, 32,
1626                         PropModeReplace, (unsigned char*)&netatom[NetWMFullscreen], 1);
1627                 c->isfullscreen = 1;
1628         } else if (!fullscreen && c->isfullscreen){
1629                 XChangeProperty(dpy, c->win, netatom[NetWMState], XA_ATOM, 32,
1630                         PropModeReplace, (unsigned char*)0, 0);
1631                 c->isfullscreen = 0;
1632         }
1633 }
1634
1635 void
1636 setlayout(const Arg *arg)
1637 {
1638         if (!arg || !arg->v || arg->v != selmon->lt[selmon->sellt])
1639                 selmon->sellt = selmon->pertag->sellts[selmon->pertag->curtag] ^= 1;
1640         if (arg && arg->v)
1641                 selmon->lt[selmon->sellt] = selmon->pertag->ltidxs[selmon->pertag->curtag][selmon->sellt] = (Layout *)arg->v;
1642         strncpy(selmon->ltsymbol, selmon->lt[selmon->sellt]->symbol, sizeof selmon->ltsymbol);
1643         if (selmon->sel)
1644                 arrange(selmon);
1645         else
1646                 drawbar(selmon);
1647 }
1648
1649 /* arg > 1.0 will set mfact absolutely */
1650 void
1651 setmfact(const Arg *arg)
1652 {
1653         float f;
1654
1655         if (!arg || !selmon->lt[selmon->sellt]->arrange)
1656                 return;
1657         f = arg->f < 1.0 ? arg->f + selmon->mfact : arg->f - 1.0;
1658         if (f < 0.05 || f > 0.95)
1659                 return;
1660         selmon->mfact = selmon->pertag->mfacts[selmon->pertag->curtag] = f;
1661         arrange(selmon);
1662 }
1663
1664 void
1665 setup(void)
1666 {
1667         int i;
1668         XSetWindowAttributes wa;
1669         Atom utf8string;
1670
1671         /* clean up any zombies immediately */
1672         sigchld(0);
1673
1674         /* init screen */
1675         screen = DefaultScreen(dpy);
1676         sw = DisplayWidth(dpy, screen);
1677         sh = DisplayHeight(dpy, screen);
1678         root = RootWindow(dpy, screen);
1679         drw = drw_create(dpy, screen, root, sw, sh);
1680         if (!drw_fontset_create(drw, fonts, LENGTH(fonts)))
1681                 die("no fonts could be loaded.");
1682         lrpad = drw->fonts->h;
1683         bh = drw->fonts->h + 2;
1684         updategeom();
1685         /* init atoms */
1686         utf8string = XInternAtom(dpy, "UTF8_STRING", False);
1687         wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1688         wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1689         wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1690         wmatom[WMTakeFocus] = XInternAtom(dpy, "WM_TAKE_FOCUS", False);
1691         netatom[NetActiveWindow] = XInternAtom(dpy, "_NET_ACTIVE_WINDOW", False);
1692         netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1693         netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1694         netatom[NetWMState] = XInternAtom(dpy, "_NET_WM_STATE", False);
1695         netatom[NetWMCheck] = XInternAtom(dpy, "_NET_SUPPORTING_WM_CHECK", False);
1696         netatom[NetWMFullscreen] = XInternAtom(dpy, "_NET_WM_STATE_FULLSCREEN", False);
1697         netatom[NetWMWindowType] = XInternAtom(dpy, "_NET_WM_WINDOW_TYPE", False);
1698         netatom[NetWMWindowTypeDialog] = XInternAtom(dpy, "_NET_WM_WINDOW_TYPE_DIALOG", False);
1699         netatom[NetClientList] = XInternAtom(dpy, "_NET_CLIENT_LIST", False);
1700         /* init cursors */
1701         cursor[CurNormal] = drw_cur_create(drw, XC_left_ptr);
1702         cursor[CurResize] = drw_cur_create(drw, XC_sizing);
1703         cursor[CurMove] = drw_cur_create(drw, XC_fleur);
1704         /* init appearance */
1705         scheme = ecalloc(LENGTH(colors), sizeof(Clr *));
1706         for (i = 0; i < LENGTH(colors); i++)
1707                 scheme[i] = drw_scm_create(drw, colors[i], 3);
1708         /* init bars */
1709         updatebars();
1710         updatestatus();
1711         /* supporting window for NetWMCheck */
1712         wmcheckwin = XCreateSimpleWindow(dpy, root, 0, 0, 1, 1, 0, 0, 0);
1713         XChangeProperty(dpy, wmcheckwin, netatom[NetWMCheck], XA_WINDOW, 32,
1714                 PropModeReplace, (unsigned char *) &wmcheckwin, 1);
1715         XChangeProperty(dpy, wmcheckwin, netatom[NetWMName], utf8string, 8,
1716                 PropModeReplace, (unsigned char *) "dwm", 3);
1717         XChangeProperty(dpy, root, netatom[NetWMCheck], XA_WINDOW, 32,
1718                 PropModeReplace, (unsigned char *) &wmcheckwin, 1);
1719         /* EWMH support per view */
1720         XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1721                 PropModeReplace, (unsigned char *) netatom, NetLast);
1722         XDeleteProperty(dpy, root, netatom[NetClientList]);
1723         /* select events */
1724         wa.cursor = cursor[CurNormal]->cursor;
1725         wa.event_mask = SubstructureRedirectMask|SubstructureNotifyMask
1726                 |ButtonPressMask|PointerMotionMask|EnterWindowMask
1727                 |LeaveWindowMask|StructureNotifyMask|PropertyChangeMask;
1728         XChangeWindowAttributes(dpy, root, CWEventMask|CWCursor, &wa);
1729         XSelectInput(dpy, root, wa.event_mask);
1730         grabkeys();
1731         focus(NULL);
1732 }
1733
1734
1735 void
1736 seturgent(Client *c, int urg)
1737 {
1738         XWMHints *wmh;
1739
1740         c->isurgent = urg;
1741         if (!(wmh = XGetWMHints(dpy, c->win)))
1742                 return;
1743         wmh->flags = urg ? (wmh->flags | XUrgencyHint) : (wmh->flags & ~XUrgencyHint);
1744         XSetWMHints(dpy, c->win, wmh);
1745         XFree(wmh);
1746 }
1747
1748 void
1749 showhide(Client *c)
1750 {
1751         if (!c)
1752                 return;
1753         if (ISVISIBLE(c)) {
1754                 /* show clients top down */
1755                 XMoveWindow(dpy, c->win, c->x, c->y);
1756                 if (!c->mon->lt[c->mon->sellt]->arrange || c->isfloating)
1757                         resize(c, c->x, c->y, c->w, c->h, 0);
1758                 showhide(c->snext);
1759         } else {
1760                 /* hide clients bottom up */
1761                 showhide(c->snext);
1762                 XMoveWindow(dpy, c->win, WIDTH(c) * -2, c->y);
1763         }
1764 }
1765
1766 void
1767 sigchld(int unused)
1768 {
1769         pid_t pid;
1770
1771         if (signal(SIGCHLD, sigchld) == SIG_ERR)
1772                 die("can't install SIGCHLD handler:");
1773         while (0 < (pid = waitpid(-1, NULL, WNOHANG))) {
1774                 pid_t *p, *lim;
1775
1776                 if (!(p = autostart_pids))
1777                         continue;
1778                 lim = &p[autostart_len];
1779
1780                 for (; p < lim; p++) {
1781                         if (*p == pid) {
1782                                 *p = -1;
1783                                 break;
1784                         }
1785                 }
1786
1787         }
1788 }
1789
1790 void
1791 spawn(const Arg *arg)
1792 {
1793         if (arg->v == dmenucmd)
1794                 dmenumon[0] = '0' + selmon->num;
1795         if (fork() == 0) {
1796                 if (dpy)
1797                         close(ConnectionNumber(dpy));
1798                 setsid();
1799                 execvp(((char **)arg->v)[0], (char **)arg->v);
1800                 fprintf(stderr, "dwm: execvp %s", ((char **)arg->v)[0]);
1801                 perror(" failed");
1802                 exit(EXIT_SUCCESS);
1803         }
1804 }
1805
1806 void
1807 tag(const Arg *arg)
1808 {
1809         if (selmon->sel && arg->ui & TAGMASK) {
1810                 selmon->sel->tags = arg->ui & TAGMASK;
1811                 focus(NULL);
1812                 arrange(selmon);
1813         }
1814 }
1815
1816 void
1817 tagmon(const Arg *arg)
1818 {
1819         if (!selmon->sel || !mons->next)
1820                 return;
1821         sendmon(selmon->sel, dirtomon(arg->i));
1822 }
1823
1824 void
1825 tile(Monitor *m)
1826 {
1827         unsigned int i, n, h, mw, my, ty;
1828         Client *c;
1829
1830         for (n = 0, c = nexttiled(m->clients); c; c = nexttiled(c->next), n++);
1831         if (n == 0)
1832                 return;
1833
1834         if (n > m->nmaster)
1835                 mw = m->nmaster ? m->ww * m->mfact : 0;
1836         else
1837                 mw = m->ww;
1838         for (i = my = ty = 0, c = nexttiled(m->clients); c; c = nexttiled(c->next), i++)
1839                 if (i < m->nmaster) {
1840                         h = (m->wh - my) / (MIN(n, m->nmaster) - i);
1841                         resize(c, m->wx, m->wy + my, mw - (2*c->bw), h - (2*c->bw), 0);
1842                         if (my + HEIGHT(c) < m->wh)
1843                                 my += HEIGHT(c);
1844                 } else {
1845                         h = (m->wh - ty) / (n - i);
1846                         resize(c, m->wx + mw, m->wy + ty, m->ww - mw - (2*c->bw), h - (2*c->bw), 0);
1847                         if (ty + HEIGHT(c) < m->wh)
1848                                 ty += HEIGHT(c);
1849                 }
1850 }
1851
1852 void
1853 togglebar(const Arg *arg)
1854 {
1855         selmon->showbar = selmon->pertag->showbars[selmon->pertag->curtag] = !selmon->showbar;
1856         updatebarpos(selmon);
1857         XMoveResizeWindow(dpy, selmon->barwin, selmon->wx, selmon->by, selmon->ww, bh);
1858         arrange(selmon);
1859 }
1860
1861 void
1862 togglefloating(const Arg *arg)
1863 {
1864         if (!selmon->sel)
1865                 return;
1866         selmon->sel->isfloating = !selmon->sel->isfloating || selmon->sel->isfixed;
1867         if (selmon->sel->isfloating)
1868                 resize(selmon->sel, selmon->sel->x, selmon->sel->y,
1869                         selmon->sel->w, selmon->sel->h, 0);
1870         arrange(selmon);
1871 }
1872
1873 void
1874 toggletag(const Arg *arg)
1875 {
1876         unsigned int newtags;
1877
1878         if (!selmon->sel)
1879                 return;
1880         newtags = selmon->sel->tags ^ (arg->ui & TAGMASK);
1881         if (newtags) {
1882                 selmon->sel->tags = newtags;
1883                 focus(NULL);
1884                 arrange(selmon);
1885         }
1886 }
1887
1888 void
1889 toggleview(const Arg *arg)
1890 {
1891         unsigned int newtagset = selmon->tagset[selmon->seltags] ^ (arg->ui & TAGMASK);
1892         int i;
1893
1894         if (newtagset) {
1895                 selmon->tagset[selmon->seltags] = newtagset;
1896
1897                 if (newtagset == ~0) {
1898                         selmon->pertag->prevtag = selmon->pertag->curtag;
1899                         selmon->pertag->curtag = 0;
1900                 }
1901
1902                 /* test if the user did not select the same tag */
1903                 if (!(newtagset & 1 << (selmon->pertag->curtag - 1))) {
1904                         selmon->pertag->prevtag = selmon->pertag->curtag;
1905                         for (i = 0; !(newtagset & 1 << i); i++) ;
1906                         selmon->pertag->curtag = i + 1;
1907                 }
1908
1909                 /* apply settings for this view */
1910                 selmon->nmaster = selmon->pertag->nmasters[selmon->pertag->curtag];
1911                 selmon->mfact = selmon->pertag->mfacts[selmon->pertag->curtag];
1912                 selmon->sellt = selmon->pertag->sellts[selmon->pertag->curtag];
1913                 selmon->lt[selmon->sellt] = selmon->pertag->ltidxs[selmon->pertag->curtag][selmon->sellt];
1914                 selmon->lt[selmon->sellt^1] = selmon->pertag->ltidxs[selmon->pertag->curtag][selmon->sellt^1];
1915
1916                 if (selmon->showbar != selmon->pertag->showbars[selmon->pertag->curtag])
1917                         togglebar(NULL);
1918
1919                 focus(NULL);
1920                 arrange(selmon);
1921         }
1922 }
1923
1924 void
1925 unfocus(Client *c, int setfocus)
1926 {
1927         if (!c)
1928                 return;
1929         grabbuttons(c, 0);
1930         XSetWindowBorder(dpy, c->win, scheme[SchemeNorm][ColBorder].pixel);
1931         if (setfocus) {
1932                 XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
1933                 XDeleteProperty(dpy, root, netatom[NetActiveWindow]);
1934         }
1935 }
1936
1937 void
1938 unmanage(Client *c, int destroyed)
1939 {
1940         Monitor *m = c->mon;
1941         XWindowChanges wc;
1942
1943         detach(c);
1944         detachstack(c);
1945         if (!destroyed) {
1946                 wc.border_width = c->oldbw;
1947                 XGrabServer(dpy); /* avoid race conditions */
1948                 XSetErrorHandler(xerrordummy);
1949                 XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
1950                 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1951                 setclientstate(c, WithdrawnState);
1952                 XSync(dpy, False);
1953                 XSetErrorHandler(xerror);
1954                 XUngrabServer(dpy);
1955         }
1956         free(c);
1957
1958         focus(NULL);
1959         updateclientlist();
1960         arrange(m);
1961 }
1962
1963 void
1964 unmapnotify(XEvent *e)
1965 {
1966         Client *c;
1967         XUnmapEvent *ev = &e->xunmap;
1968
1969         if ((c = wintoclient(ev->window))) {
1970                 if (ev->send_event)
1971                         setclientstate(c, WithdrawnState);
1972                 else
1973                         unmanage(c, 0);
1974         }
1975 }
1976
1977 void
1978 updatebars(void)
1979 {
1980         Monitor *m;
1981         XSetWindowAttributes wa = {
1982                 .override_redirect = True,
1983                 .background_pixmap = ParentRelative,
1984                 .event_mask = ButtonPressMask|ExposureMask
1985         };
1986         XClassHint ch = {"dwm", "dwm"};
1987         for (m = mons; m; m = m->next) {
1988                 if (m->barwin)
1989                         continue;
1990                 m->barwin = XCreateWindow(dpy, root, m->wx, m->by, m->ww, bh, 0, DefaultDepth(dpy, screen),
1991                                 CopyFromParent, DefaultVisual(dpy, screen),
1992                                 CWOverrideRedirect|CWBackPixmap|CWEventMask, &wa);
1993                 XDefineCursor(dpy, m->barwin, cursor[CurNormal]->cursor);
1994                 XMapRaised(dpy, m->barwin);
1995                 XSetClassHint(dpy, m->barwin, &ch);
1996         }
1997 }
1998
1999 void
2000 updatebarpos(Monitor *m)
2001 {
2002         m->wy = m->my;
2003         m->wh = m->mh;
2004         if (m->showbar) {
2005                 m->wh -= bh;
2006                 m->by = m->topbar ? m->wy : m->wy + m->wh;
2007                 m->wy = m->topbar ? m->wy + bh : m->wy;
2008         } else
2009                 m->by = -bh;
2010 }
2011
2012 void
2013 updateclientlist()
2014 {
2015         Client *c;
2016         Monitor *m;
2017
2018         XDeleteProperty(dpy, root, netatom[NetClientList]);
2019         for (m = mons; m; m = m->next)
2020                 for (c = m->clients; c; c = c->next)
2021                         XChangeProperty(dpy, root, netatom[NetClientList],
2022                                 XA_WINDOW, 32, PropModeAppend,
2023                                 (unsigned char *) &(c->win), 1);
2024 }
2025
2026 int
2027 updategeom(void)
2028 {
2029         int dirty = 0;
2030
2031 #ifdef XINERAMA
2032         if (XineramaIsActive(dpy)) {
2033                 int i, j, n, nn;
2034                 Client *c;
2035                 Monitor *m;
2036                 XineramaScreenInfo *info = XineramaQueryScreens(dpy, &nn);
2037                 XineramaScreenInfo *unique = NULL;
2038
2039                 for (n = 0, m = mons; m; m = m->next, n++);
2040                 /* only consider unique geometries as separate screens */
2041                 unique = ecalloc(nn, sizeof(XineramaScreenInfo));
2042                 for (i = 0, j = 0; i < nn; i++)
2043                         if (isuniquegeom(unique, j, &info[i]))
2044                                 memcpy(&unique[j++], &info[i], sizeof(XineramaScreenInfo));
2045                 XFree(info);
2046                 nn = j;
2047                 if (n <= nn) { /* new monitors available */
2048                         for (i = 0; i < (nn - n); i++) {
2049                                 for (m = mons; m && m->next; m = m->next);
2050                                 if (m)
2051                                         m->next = createmon();
2052                                 else
2053                                         mons = createmon();
2054                         }
2055                         for (i = 0, m = mons; i < nn && m; m = m->next, i++)
2056                                 if (i >= n
2057                                 || unique[i].x_org != m->mx || unique[i].y_org != m->my
2058                                 || unique[i].width != m->mw || unique[i].height != m->mh)
2059                                 {
2060                                         dirty = 1;
2061                                         m->num = i;
2062                                         m->mx = m->wx = unique[i].x_org;
2063                                         m->my = m->wy = unique[i].y_org;
2064                                         m->mw = m->ww = unique[i].width;
2065                                         m->mh = m->wh = unique[i].height;
2066                                         updatebarpos(m);
2067                                 }
2068                 } else { /* less monitors available nn < n */
2069                         for (i = nn; i < n; i++) {
2070                                 for (m = mons; m && m->next; m = m->next);
2071                                 while ((c = m->clients)) {
2072                                         dirty = 1;
2073                                         m->clients = c->next;
2074                                         detachstack(c);
2075                                         c->mon = mons;
2076                                         attachbottom(c);
2077                                         attachstack(c);
2078                                 }
2079                                 if (m == selmon)
2080                                         selmon = mons;
2081                                 cleanupmon(m);
2082                         }
2083                 }
2084                 free(unique);
2085         } else
2086 #endif /* XINERAMA */
2087         { /* default monitor setup */
2088                 if (!mons)
2089                         mons = createmon();
2090                 if (mons->mw != sw || mons->mh != sh) {
2091                         dirty = 1;
2092                         mons->mw = mons->ww = sw;
2093                         mons->mh = mons->wh = sh;
2094                         updatebarpos(mons);
2095                 }
2096         }
2097         if (dirty) {
2098                 selmon = mons;
2099                 selmon = wintomon(root);
2100         }
2101         return dirty;
2102 }
2103
2104 void
2105 updatenumlockmask(void)
2106 {
2107         unsigned int i, j;
2108         XModifierKeymap *modmap;
2109
2110         numlockmask = 0;
2111         modmap = XGetModifierMapping(dpy);
2112         for (i = 0; i < 8; i++)
2113                 for (j = 0; j < modmap->max_keypermod; j++)
2114                         if (modmap->modifiermap[i * modmap->max_keypermod + j]
2115                                 == XKeysymToKeycode(dpy, XK_Num_Lock))
2116                                 numlockmask = (1 << i);
2117         XFreeModifiermap(modmap);
2118 }
2119
2120 void
2121 updatesizehints(Client *c)
2122 {
2123         long msize;
2124         XSizeHints size;
2125
2126         if (!XGetWMNormalHints(dpy, c->win, &size, &msize))
2127                 /* size is uninitialized, ensure that size.flags aren't used */
2128                 size.flags = PSize;
2129         if (size.flags & PBaseSize) {
2130                 c->basew = size.base_width;
2131                 c->baseh = size.base_height;
2132         } else if (size.flags & PMinSize) {
2133                 c->basew = size.min_width;
2134                 c->baseh = size.min_height;
2135         } else
2136                 c->basew = c->baseh = 0;
2137         if (size.flags & PResizeInc) {
2138                 c->incw = size.width_inc;
2139                 c->inch = size.height_inc;
2140         } else
2141                 c->incw = c->inch = 0;
2142         if (size.flags & PMaxSize) {
2143                 c->maxw = size.max_width;
2144                 c->maxh = size.max_height;
2145         } else
2146                 c->maxw = c->maxh = 0;
2147         if (size.flags & PMinSize) {
2148                 c->minw = size.min_width;
2149                 c->minh = size.min_height;
2150         } else if (size.flags & PBaseSize) {
2151                 c->minw = size.base_width;
2152                 c->minh = size.base_height;
2153         } else
2154                 c->minw = c->minh = 0;
2155         if (size.flags & PAspect) {
2156                 c->mina = (float)size.min_aspect.y / size.min_aspect.x;
2157                 c->maxa = (float)size.max_aspect.x / size.max_aspect.y;
2158         } else
2159                 c->maxa = c->mina = 0.0;
2160         c->isfixed = (c->maxw && c->maxh && c->maxw == c->minw && c->maxh == c->minh);
2161 }
2162
2163 void
2164 updatestatus(void)
2165 {
2166         if (!gettextprop(root, XA_WM_NAME, stext, sizeof(stext)))
2167                 strcpy(stext, "dwm-"VERSION);
2168         drawbar(selmon);
2169 }
2170
2171 void
2172 updatetitle(Client *c)
2173 {
2174         if (!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
2175                 gettextprop(c->win, XA_WM_NAME, c->name, sizeof c->name);
2176         if (c->name[0] == '\0') /* hack to mark broken clients */
2177                 strcpy(c->name, broken);
2178 }
2179
2180 void
2181 updatewindowtype(Client *c)
2182 {
2183         Atom state = getatomprop(c, netatom[NetWMState]);
2184         Atom wtype = getatomprop(c, netatom[NetWMWindowType]);
2185
2186         if (state == netatom[NetWMFullscreen])
2187                 setfullscreen(c, 1);
2188         if (wtype == netatom[NetWMWindowTypeDialog])
2189                 c->isfloating = 1;
2190 }
2191
2192 void
2193 updatewmhints(Client *c)
2194 {
2195         XWMHints *wmh;
2196
2197         if ((wmh = XGetWMHints(dpy, c->win))) {
2198                 if (c == selmon->sel && wmh->flags & XUrgencyHint) {
2199                         wmh->flags &= ~XUrgencyHint;
2200                         XSetWMHints(dpy, c->win, wmh);
2201                 } else
2202                         c->isurgent = (wmh->flags & XUrgencyHint) ? 1 : 0;
2203                 if (wmh->flags & InputHint)
2204                         c->neverfocus = !wmh->input;
2205                 else
2206                         c->neverfocus = 0;
2207                 XFree(wmh);
2208         }
2209 }
2210
2211 void
2212 view(const Arg *arg)
2213 {
2214         int i;
2215         unsigned int tmptag;
2216
2217         if ((arg->ui & TAGMASK) == selmon->tagset[selmon->seltags])
2218                 return;
2219         selmon->seltags ^= 1; /* toggle sel tagset */
2220         if (arg->ui & TAGMASK) {
2221                 selmon->tagset[selmon->seltags] = arg->ui & TAGMASK;
2222                 selmon->pertag->prevtag = selmon->pertag->curtag;
2223
2224                 if (arg->ui == ~0)
2225                         selmon->pertag->curtag = 0;
2226                 else {
2227                         for (i = 0; !(arg->ui & 1 << i); i++) ;
2228                         selmon->pertag->curtag = i + 1;
2229                 }
2230         } else {
2231                 tmptag = selmon->pertag->prevtag;
2232                 selmon->pertag->prevtag = selmon->pertag->curtag;
2233                 selmon->pertag->curtag = tmptag;
2234         }
2235
2236         selmon->nmaster = selmon->pertag->nmasters[selmon->pertag->curtag];
2237         selmon->mfact = selmon->pertag->mfacts[selmon->pertag->curtag];
2238         selmon->sellt = selmon->pertag->sellts[selmon->pertag->curtag];
2239         selmon->lt[selmon->sellt] = selmon->pertag->ltidxs[selmon->pertag->curtag][selmon->sellt];
2240         selmon->lt[selmon->sellt^1] = selmon->pertag->ltidxs[selmon->pertag->curtag][selmon->sellt^1];
2241
2242         if (selmon->showbar != selmon->pertag->showbars[selmon->pertag->curtag])
2243                 togglebar(NULL);
2244
2245         focus(NULL);
2246         arrange(selmon);
2247 }
2248
2249 Client *
2250 wintoclient(Window w)
2251 {
2252         Client *c;
2253         Monitor *m;
2254
2255         for (m = mons; m; m = m->next)
2256                 for (c = m->clients; c; c = c->next)
2257                         if (c->win == w)
2258                                 return c;
2259         return NULL;
2260 }
2261
2262 Monitor *
2263 wintomon(Window w)
2264 {
2265         int x, y;
2266         Client *c;
2267         Monitor *m;
2268
2269         if (w == root && getrootptr(&x, &y))
2270                 return recttomon(x, y, 1, 1);
2271         for (m = mons; m; m = m->next)
2272                 if (w == m->barwin)
2273                         return m;
2274         if ((c = wintoclient(w)))
2275                 return c->mon;
2276         return selmon;
2277 }
2278
2279 /* There's no way to check accesses to destroyed windows, thus those cases are
2280  * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
2281  * default error handler, which may call exit. */
2282 int
2283 xerror(Display *dpy, XErrorEvent *ee)
2284 {
2285         if (ee->error_code == BadWindow
2286         || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
2287         || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
2288         || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
2289         || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
2290         || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
2291         || (ee->request_code == X_GrabButton && ee->error_code == BadAccess)
2292         || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
2293         || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
2294                 return 0;
2295         fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
2296                 ee->request_code, ee->error_code);
2297         return xerrorxlib(dpy, ee); /* may call exit */
2298 }
2299
2300 int
2301 xerrordummy(Display *dpy, XErrorEvent *ee)
2302 {
2303         return 0;
2304 }
2305
2306 /* Startup Error handler to check if another window manager
2307  * is already running. */
2308 int
2309 xerrorstart(Display *dpy, XErrorEvent *ee)
2310 {
2311         die("dwm: another window manager is already running");
2312         return -1;
2313 }
2314
2315 void
2316 zoom(const Arg *arg)
2317 {
2318         Client *c = selmon->sel;
2319         Client *at = NULL, *cold, *cprevious = NULL;
2320
2321         if (!selmon->lt[selmon->sellt]->arrange
2322         || (selmon->sel && selmon->sel->isfloating))
2323                 return;
2324         if (c == nexttiled(selmon->clients)) {
2325                 at = findbefore(prevzoom);
2326                 if (at)
2327                         cprevious = nexttiled(at->next);
2328                 if (!cprevious || cprevious != prevzoom) {
2329                         prevzoom = NULL;
2330                         if (!c || !(c = nexttiled(c->next)))
2331                                 return;
2332                 } else
2333                         c = cprevious;
2334         }
2335         cold = nexttiled(selmon->clients);
2336         if (c != cold && !at)
2337                 at = findbefore(c);
2338         detach(c);
2339         attach(c);
2340         /* swap windows instead of pushing the previous one down */
2341         if (c != cold && at) {
2342                 prevzoom = cold;
2343                 if (cold && at != cold) {
2344                         detach(cold);
2345                         cold->next = at->next;
2346                         at->next = cold;
2347                 }
2348         }
2349         focus(c);
2350         arrange(c->mon);
2351 }
2352
2353 int
2354 main(int argc, char *argv[])
2355 {
2356         if (argc == 2 && !strcmp("-v", argv[1]))
2357                 die("dwm-"VERSION);
2358         else if (argc != 1)
2359                 die("usage: dwm [-v]");
2360         if (!setlocale(LC_CTYPE, "") || !XSupportsLocale())
2361                 fputs("warning: no locale support\n", stderr);
2362         if (!(dpy = XOpenDisplay(NULL)))
2363                 die("dwm: cannot open display");
2364         checkotherwm();
2365         autostart_exec();
2366         setup();
2367 #ifdef __OpenBSD__
2368         if (pledge("stdio rpath proc exec", NULL) == -1)
2369                 die("pledge");
2370 #endif /* __OpenBSD__ */
2371         scan();
2372         run();
2373         cleanup();
2374         XCloseDisplay(dpy);
2375         return EXIT_SUCCESS;
2376 }