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