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