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