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