]> git.armaanb.net Git - dwm.git/blob - dwm.c
Initial commit
[dwm.git] / dwm.c
1 /* See LICENSE file for copyright and license details.
2  *
3  * dynamic window manager is designed like any other X client as well. It is
4  * driven through handling X events. In contrast to other X clients, a window
5  * manager selects for SubstructureRedirectMask on the root window, to receive
6  * events about window (dis-)appearance. Only one X connection at a time is
7  * allowed to select for this event mask.
8  *
9  * The event handlers of dwm are organized in an array which is accessed
10  * whenever a new event has been fetched. This allows event dispatching
11  * in O(1) time.
12  *
13  * Each child of the root window is called a client, except windows which have
14  * set the override_redirect flag. Clients are organized in a linked client
15  * list on each monitor, the focus history is remembered through a stack list
16  * on each monitor. Each client contains a bit array to indicate the tags of a
17  * client.
18  *
19  * Keys and tagging rules are organized as arrays and defined in config.h.
20  *
21  * To understand everything else, start reading main().
22  */
23 #include <errno.h>
24 #include <locale.h>
25 #include <signal.h>
26 #include <stdarg.h>
27 #include <stdio.h>
28 #include <stdlib.h>
29 #include <string.h>
30 #include <unistd.h>
31 #include <sys/types.h>
32 #include <sys/wait.h>
33 #include <X11/cursorfont.h>
34 #include <X11/keysym.h>
35 #include <X11/Xatom.h>
36 #include <X11/Xlib.h>
37 #include <X11/Xproto.h>
38 #include <X11/Xutil.h>
39 #ifdef XINERAMA
40 #include <X11/extensions/Xinerama.h>
41 #endif /* XINERAMA */
42 #include <X11/Xft/Xft.h>
43 #include <X11/XF86keysym.h>
44
45 #include "drw.h"
46 #include "util.h"
47
48 /* macros */
49 #define BUTTONMASK              (ButtonPressMask|ButtonReleaseMask)
50 #define CLEANMASK(mask)         (mask & ~(numlockmask|LockMask) & (ShiftMask|ControlMask|Mod1Mask|Mod2Mask|Mod3Mask|Mod4Mask|Mod5Mask))
51 #define INTERSECT(x,y,w,h,m)    (MAX(0, MIN((x)+(w),(m)->wx+(m)->ww) - MAX((x),(m)->wx)) \
52                                * MAX(0, MIN((y)+(h),(m)->wy+(m)->wh) - MAX((y),(m)->wy)))
53 #define ISVISIBLE(C)            ((C->tags & C->mon->tagset[C->mon->seltags]))
54 #define LENGTH(X)               (sizeof X / sizeof X[0])
55 #define MOUSEMASK               (BUTTONMASK|PointerMotionMask)
56 #define WIDTH(X)                ((X)->w + 2 * (X)->bw)
57 #define HEIGHT(X)               ((X)->h + 2 * (X)->bw)
58 #define TAGMASK                 ((1 << LENGTH(tags)) - 1)
59 #define TEXTW(X)                (drw_fontset_getwidth(drw, (X)) + lrpad)
60
61 /* enums */
62 enum { CurNormal, CurResize, CurMove, CurLast }; /* cursor */
63 enum { SchemeNorm, SchemeSel }; /* color schemes */
64 enum { NetSupported, NetWMName, NetWMState, NetWMCheck,
65        NetWMFullscreen, NetActiveWindow, NetWMWindowType,
66        NetWMWindowTypeDialog, NetClientList, NetLast }; /* EWMH atoms */
67 enum { WMProtocols, WMDelete, WMState, WMTakeFocus, WMLast }; /* default atoms */
68 enum { ClkTagBar, ClkLtSymbol, ClkStatusText, ClkWinTitle,
69        ClkClientWin, ClkRootWin, ClkLast }; /* clicks */
70
71 typedef union {
72         int i;
73         unsigned int ui;
74         float f;
75         const void *v;
76 } Arg;
77
78 typedef struct {
79         unsigned int click;
80         unsigned int mask;
81         unsigned int button;
82         void (*func)(const Arg *arg);
83         const Arg arg;
84 } Button;
85
86 typedef struct Monitor Monitor;
87 typedef struct Client Client;
88 struct Client {
89         char name[256];
90         float mina, maxa;
91         int x, y, w, h;
92         int oldx, oldy, oldw, oldh;
93         int basew, baseh, incw, inch, maxw, maxh, minw, minh;
94         int bw, oldbw;
95         unsigned int tags;
96         int isfixed, isfloating, isurgent, neverfocus, oldstate, isfullscreen;
97         Client *next;
98         Client *snext;
99         Monitor *mon;
100         Window win;
101 };
102
103 typedef struct {
104         unsigned int mod;
105         KeySym keysym;
106         void (*func)(const Arg *);
107         const Arg arg;
108 } Key;
109
110 typedef struct {
111         const char *symbol;
112         void (*arrange)(Monitor *);
113 } Layout;
114
115 struct Monitor {
116         char ltsymbol[16];
117         float mfact;
118         int nmaster;
119         int num;
120         int by;               /* bar geometry */
121         int mx, my, mw, mh;   /* screen size */
122         int wx, wy, ww, wh;   /* window area  */
123         unsigned int seltags;
124         unsigned int sellt;
125         unsigned int tagset[2];
126         int showbar;
127         int topbar;
128         Client *clients;
129         Client *sel;
130         Client *stack;
131         Monitor *next;
132         Window barwin;
133         const Layout *lt[2];
134 };
135
136 typedef struct {
137         const char *class;
138         const char *instance;
139         const char *title;
140         unsigned int tags;
141         int isfloating;
142         int monitor;
143 } Rule;
144
145 /* function declarations */
146 static void applyrules(Client *c);
147 static int applysizehints(Client *c, int *x, int *y, int *w, int *h, int interact);
148 static void arrange(Monitor *m);
149 static void arrangemon(Monitor *m);
150 static void attach(Client *c);
151 static void attachbottom(Client *c);
152 static void attachstack(Client *c);
153 static void buttonpress(XEvent *e);
154 static void checkotherwm(void);
155 static void cleanup(void);
156 static void cleanupmon(Monitor *mon);
157 static void clientmessage(XEvent *e);
158 static void configure(Client *c);
159 static void configurenotify(XEvent *e);
160 static void configurerequest(XEvent *e);
161 static Monitor *createmon(void);
162 static void destroynotify(XEvent *e);
163 static void detach(Client *c);
164 static void detachstack(Client *c);
165 static Monitor *dirtomon(int dir);
166 static void drawbar(Monitor *m);
167 static void drawbars(void);
168 static void enternotify(XEvent *e);
169 static void expose(XEvent *e);
170 static void focus(Client *c);
171 static void focusin(XEvent *e);
172 static void focusmon(const Arg *arg);
173 static void focusstack(const Arg *arg);
174 static Atom getatomprop(Client *c, Atom prop);
175 static int getrootptr(int *x, int *y);
176 static long getstate(Window w);
177 static int gettextprop(Window w, Atom atom, char *text, unsigned int size);
178 static void grabbuttons(Client *c, int focused);
179 static void grabkeys(void);
180 static void incnmaster(const Arg *arg);
181 static void keypress(XEvent *e);
182 static void killclient(const Arg *arg);
183 static void manage(Window w, XWindowAttributes *wa);
184 static void mappingnotify(XEvent *e);
185 static void maprequest(XEvent *e);
186 static void monocle(Monitor *m);
187 static void motionnotify(XEvent *e);
188 static void movemouse(const Arg *arg);
189 static Client *nexttiled(Client *c);
190 static void pop(Client *);
191 static void propertynotify(XEvent *e);
192 static void quit(const Arg *arg);
193 static Monitor *recttomon(int x, int y, int w, int h);
194 static void resize(Client *c, int x, int y, int w, int h, int interact);
195 static void resizeclient(Client *c, int x, int y, int w, int h);
196 static void resizemouse(const Arg *arg);
197 static void restack(Monitor *m);
198 static void run(void);
199 static void scan(void);
200 static int sendevent(Client *c, Atom proto);
201 static void sendmon(Client *c, Monitor *m);
202 static void setclientstate(Client *c, long state);
203 static void setfocus(Client *c);
204 static void setfullscreen(Client *c, int fullscreen);
205 static void setlayout(const Arg *arg);
206 static void setmfact(const Arg *arg);
207 static void setup(void);
208 static void seturgent(Client *c, int urg);
209 static void showhide(Client *c);
210 static void sigchld(int unused);
211 static void spawn(const Arg *arg);
212 static void tag(const Arg *arg);
213 static void tagmon(const Arg *arg);
214 static void tile(Monitor *);
215 static void togglebar(const Arg *arg);
216 static void togglefloating(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, blw = 0;      /* bar geometry */
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         for (i = 0; i < LENGTH(rules); i++) {
298                 r = &rules[i];
299                 if ((!r->title || strstr(c->name, r->title))
300                 && (!r->class || strstr(class, r->class))
301                 && (!r->instance || strstr(instance, r->instance)))
302                 {
303                         c->isfloating = r->isfloating;
304                         c->tags |= r->tags;
305                         for (m = mons; m && m->num != r->monitor; m = m->next);
306                         if (m)
307                                 c->mon = m;
308                 }
309         }
310         if (ch.res_class)
311                 XFree(ch.res_class);
312         if (ch.res_name)
313                 XFree(ch.res_name);
314         c->tags = c->tags & TAGMASK ? c->tags & TAGMASK : c->mon->tagset[c->mon->seltags];
315 }
316
317 int
318 applysizehints(Client *c, int *x, int *y, int *w, int *h, int interact)
319 {
320         int baseismin;
321         Monitor *m = c->mon;
322
323         /* set minimum possible */
324         *w = MAX(1, *w);
325         *h = MAX(1, *h);
326         if (interact) {
327                 if (*x > sw)
328                         *x = sw - WIDTH(c);
329                 if (*y > sh)
330                         *y = sh - HEIGHT(c);
331                 if (*x + *w + 2 * c->bw < 0)
332                         *x = 0;
333                 if (*y + *h + 2 * c->bw < 0)
334                         *y = 0;
335         } else {
336                 if (*x >= m->wx + m->ww)
337                         *x = m->wx + m->ww - WIDTH(c);
338                 if (*y >= m->wy + m->wh)
339                         *y = m->wy + m->wh - HEIGHT(c);
340                 if (*x + *w + 2 * c->bw <= m->wx)
341                         *x = m->wx;
342                 if (*y + *h + 2 * c->bw <= m->wy)
343                         *y = m->wy;
344         }
345         if (*h < bh)
346                 *h = bh;
347         if (*w < bh)
348                 *w = bh;
349         if (resizehints || c->isfloating || !c->mon->lt[c->mon->sellt]->arrange) {
350                 /* see last two sentences in ICCCM 4.1.2.3 */
351                 baseismin = c->basew == c->minw && c->baseh == c->minh;
352                 if (!baseismin) { /* temporarily remove base dimensions */
353                         *w -= c->basew;
354                         *h -= c->baseh;
355                 }
356                 /* adjust for aspect limits */
357                 if (c->mina > 0 && c->maxa > 0) {
358                         if (c->maxa < (float)*w / *h)
359                                 *w = *h * c->maxa + 0.5;
360                         else if (c->mina < (float)*h / *w)
361                                 *h = *w * c->mina + 0.5;
362                 }
363                 if (baseismin) { /* increment calculation requires this */
364                         *w -= c->basew;
365                         *h -= c->baseh;
366                 }
367                 /* adjust for increment value */
368                 if (c->incw)
369                         *w -= *w % c->incw;
370                 if (c->inch)
371                         *h -= *h % c->inch;
372                 /* restore base dimensions */
373                 *w = MAX(*w + c->basew, c->minw);
374                 *h = MAX(*h + c->baseh, c->minh);
375                 if (c->maxw)
376                         *w = MIN(*w, c->maxw);
377                 if (c->maxh)
378                         *h = MIN(*h, c->maxh);
379         }
380         return *x != c->x || *y != c->y || *w != c->w || *h != c->h;
381 }
382
383 void
384 arrange(Monitor *m)
385 {
386         if (m)
387                 showhide(m->stack);
388         else for (m = mons; m; m = m->next)
389                 showhide(m->stack);
390         if (m) {
391                 arrangemon(m);
392                 restack(m);
393         } else for (m = mons; m; m = m->next)
394                 arrangemon(m);
395 }
396
397 void
398 arrangemon(Monitor *m)
399 {
400         strncpy(m->ltsymbol, m->lt[m->sellt]->symbol, sizeof m->ltsymbol);
401         if (m->lt[m->sellt]->arrange)
402                 m->lt[m->sellt]->arrange(m);
403 }
404
405 void
406 attach(Client *c)
407 {
408         c->next = c->mon->clients;
409         c->mon->clients = c;
410 }
411
412 void
413 attachbottom(Client *c)
414 {
415         Client **tc;
416         c->next = NULL;
417         for (tc = &c->mon->clients; *tc; tc = &(*tc)->next);
418         *tc = c;
419 }
420
421 void
422 attachstack(Client *c)
423 {
424         c->snext = c->mon->stack;
425         c->mon->stack = c;
426 }
427
428 void
429 buttonpress(XEvent *e)
430 {
431         unsigned int i, x, click;
432         Arg arg = {0};
433         Client *c;
434         Monitor *m;
435         XButtonPressedEvent *ev = &e->xbutton;
436
437         click = ClkRootWin;
438         /* focus monitor if necessary */
439         if ((m = wintomon(ev->window)) && m != selmon) {
440                 unfocus(selmon->sel, 1);
441                 selmon = m;
442                 focus(NULL);
443         }
444         if (ev->window == selmon->barwin) {
445                 i = x = 0;
446                 do
447                         x += TEXTW(tags[i]);
448                 while (ev->x >= x && ++i < LENGTH(tags));
449                 if (i < LENGTH(tags)) {
450                         click = ClkTagBar;
451                         arg.ui = 1 << i;
452                 } else if (ev->x < x + blw)
453                         click = ClkLtSymbol;
454                 else if (ev->x > selmon->ww - (int)TEXTW(stext))
455                         click = ClkStatusText;
456                 else
457                         click = ClkWinTitle;
458         } else if ((c = wintoclient(ev->window))) {
459                 focus(c);
460                 restack(selmon);
461                 XAllowEvents(dpy, ReplayPointer, CurrentTime);
462                 click = ClkClientWin;
463         }
464         for (i = 0; i < LENGTH(buttons); i++)
465                 if (click == buttons[i].click && buttons[i].func && buttons[i].button == ev->button
466                 && CLEANMASK(buttons[i].mask) == CLEANMASK(ev->state))
467                         buttons[i].func(click == ClkTagBar && buttons[i].arg.i == 0 ? &arg : &buttons[i].arg);
468 }
469
470 void
471 checkotherwm(void)
472 {
473         xerrorxlib = XSetErrorHandler(xerrorstart);
474         /* this causes an error if some other window manager is running */
475         XSelectInput(dpy, DefaultRootWindow(dpy), SubstructureRedirectMask);
476         XSync(dpy, False);
477         XSetErrorHandler(xerror);
478         XSync(dpy, False);
479 }
480
481 void
482 cleanup(void)
483 {
484         Arg a = {.ui = ~0};
485         Layout foo = { "", NULL };
486         Monitor *m;
487         size_t i;
488
489         view(&a);
490         selmon->lt[selmon->sellt] = &foo;
491         for (m = mons; m; m = m->next)
492                 while (m->stack)
493                         unmanage(m->stack, 0);
494         XUngrabKey(dpy, AnyKey, AnyModifier, root);
495         while (mons)
496                 cleanupmon(mons);
497         for (i = 0; i < CurLast; i++)
498                 drw_cur_free(drw, cursor[i]);
499         for (i = 0; i < LENGTH(colors); i++)
500                 free(scheme[i]);
501         XDestroyWindow(dpy, wmcheckwin);
502         drw_free(drw);
503         XSync(dpy, False);
504         XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime);
505         XDeleteProperty(dpy, root, netatom[NetActiveWindow]);
506 }
507
508 void
509 cleanupmon(Monitor *mon)
510 {
511         Monitor *m;
512
513         if (mon == mons)
514                 mons = mons->next;
515         else {
516                 for (m = mons; m && m->next != mon; m = m->next);
517                 m->next = mon->next;
518         }
519         XUnmapWindow(dpy, mon->barwin);
520         XDestroyWindow(dpy, mon->barwin);
521         free(mon);
522 }
523
524 void
525 clientmessage(XEvent *e)
526 {
527         XClientMessageEvent *cme = &e->xclient;
528         Client *c = wintoclient(cme->window);
529
530         if (!c)
531                 return;
532         if (cme->message_type == netatom[NetWMState]) {
533                 if (cme->data.l[1] == netatom[NetWMFullscreen]
534                 || cme->data.l[2] == netatom[NetWMFullscreen])
535                         setfullscreen(c, (cme->data.l[0] == 1 /* _NET_WM_STATE_ADD    */
536                                 || cme->data.l[0] == 2 /* _NET_WM_STATE_TOGGLE */));
537         } else if (cme->message_type == netatom[NetActiveWindow]) {
538                 if (c != selmon->sel && !c->isurgent)
539                         seturgent(c, 1);
540         }
541 }
542
543 void
544 configure(Client *c)
545 {
546         XConfigureEvent ce;
547
548         ce.type = ConfigureNotify;
549         ce.display = dpy;
550         ce.event = c->win;
551         ce.window = c->win;
552         ce.x = c->x;
553         ce.y = c->y;
554         ce.width = c->w;
555         ce.height = c->h;
556         ce.border_width = c->bw;
557         ce.above = None;
558         ce.override_redirect = False;
559         XSendEvent(dpy, c->win, False, StructureNotifyMask, (XEvent *)&ce);
560 }
561
562 void
563 configurenotify(XEvent *e)
564 {
565         Monitor *m;
566         XConfigureEvent *ev = &e->xconfigure;
567         int dirty;
568
569         /* TODO: updategeom handling sucks, needs to be simplified */
570         if (ev->window == root) {
571                 dirty = (sw != ev->width || sh != ev->height);
572                 sw = ev->width;
573                 sh = ev->height;
574                 if (updategeom() || dirty) {
575                         drw_resize(drw, sw, bh);
576                         updatebars();
577                         for (m = mons; m; m = m->next) {
578                                 XMoveResizeWindow(dpy, m->barwin, m->wx, m->by, m->ww, bh);
579                         }
580                         focus(NULL);
581                         arrange(NULL);
582                 }
583         }
584 }
585
586 void
587 configurerequest(XEvent *e)
588 {
589         Client *c;
590         Monitor *m;
591         XConfigureRequestEvent *ev = &e->xconfigurerequest;
592         XWindowChanges wc;
593
594         if ((c = wintoclient(ev->window))) {
595                 if (ev->value_mask & CWBorderWidth)
596                         c->bw = ev->border_width;
597                 else if (c->isfloating || !selmon->lt[selmon->sellt]->arrange) {
598                         m = c->mon;
599                         if (ev->value_mask & CWX) {
600                                 c->oldx = c->x;
601                                 c->x = m->mx + ev->x;
602                         }
603                         if (ev->value_mask & CWY) {
604                                 c->oldy = c->y;
605                                 c->y = m->my + ev->y;
606                         }
607                         if (ev->value_mask & CWWidth) {
608                                 c->oldw = c->w;
609                                 c->w = ev->width;
610                         }
611                         if (ev->value_mask & CWHeight) {
612                                 c->oldh = c->h;
613                                 c->h = ev->height;
614                         }
615                         if ((c->x + c->w) > m->mx + m->mw && c->isfloating)
616                                 c->x = m->mx + (m->mw / 2 - WIDTH(c) / 2); /* center in x direction */
617                         if ((c->y + c->h) > m->my + m->mh && c->isfloating)
618                                 c->y = m->my + (m->mh / 2 - HEIGHT(c) / 2); /* center in y direction */
619                         if ((ev->value_mask & (CWX|CWY)) && !(ev->value_mask & (CWWidth|CWHeight)))
620                                 configure(c);
621                         if (ISVISIBLE(c))
622                                 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h);
623                 } else
624                         configure(c);
625         } else {
626                 wc.x = ev->x;
627                 wc.y = ev->y;
628                 wc.width = ev->width;
629                 wc.height = ev->height;
630                 wc.border_width = ev->border_width;
631                 wc.sibling = ev->above;
632                 wc.stack_mode = ev->detail;
633                 XConfigureWindow(dpy, ev->window, ev->value_mask, &wc);
634         }
635         XSync(dpy, False);
636 }
637
638 Monitor *
639 createmon(void)
640 {
641         Monitor *m;
642
643         m = ecalloc(1, sizeof(Monitor));
644         m->tagset[0] = m->tagset[1] = 1;
645         m->mfact = mfact;
646         m->nmaster = nmaster;
647         m->showbar = showbar;
648         m->topbar = topbar;
649         m->lt[0] = &layouts[0];
650         m->lt[1] = &layouts[1 % LENGTH(layouts)];
651         strncpy(m->ltsymbol, layouts[0].symbol, sizeof m->ltsymbol);
652         return m;
653 }
654
655 void
656 destroynotify(XEvent *e)
657 {
658         Client *c;
659         XDestroyWindowEvent *ev = &e->xdestroywindow;
660
661         if ((c = wintoclient(ev->window)))
662                 unmanage(c, 1);
663 }
664
665 void
666 detach(Client *c)
667 {
668         Client **tc;
669
670         for (tc = &c->mon->clients; *tc && *tc != c; tc = &(*tc)->next);
671         *tc = c->next;
672 }
673
674 void
675 detachstack(Client *c)
676 {
677         Client **tc, *t;
678
679         for (tc = &c->mon->stack; *tc && *tc != c; tc = &(*tc)->snext);
680         *tc = c->snext;
681
682         if (c == c->mon->sel) {
683                 for (t = c->mon->stack; t && !ISVISIBLE(t); t = t->snext);
684                 c->mon->sel = t;
685         }
686 }
687
688 Monitor *
689 dirtomon(int dir)
690 {
691         Monitor *m = NULL;
692
693         if (dir > 0) {
694                 if (!(m = selmon->next))
695                         m = mons;
696         } else if (selmon == mons)
697                 for (m = mons; m->next; m = m->next);
698         else
699                 for (m = mons; m->next != selmon; m = m->next);
700         return m;
701 }
702
703 void
704 drawbar(Monitor *m)
705 {
706         int x, w, tw = 0;
707         int boxs = drw->fonts->h / 9;
708         int boxw = drw->fonts->h / 6 + 2;
709         unsigned int i, occ = 0, urg = 0;
710         Client *c;
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 = blw = 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)
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 {
925                 if (XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success && n > 0 && *list) {
926                         strncpy(text, *list, size - 1);
927                         XFreeStringList(list);
928                 }
929         }
930         text[size - 1] = '\0';
931         XFree(name.value);
932         return 1;
933 }
934
935 void
936 grabbuttons(Client *c, int focused)
937 {
938         updatenumlockmask();
939         {
940                 unsigned int i, j;
941                 unsigned int modifiers[] = { 0, LockMask, numlockmask, numlockmask|LockMask };
942                 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
943                 if (!focused)
944                         XGrabButton(dpy, AnyButton, AnyModifier, c->win, False,
945                                 BUTTONMASK, GrabModeSync, GrabModeSync, None, None);
946                 for (i = 0; i < LENGTH(buttons); i++)
947                         if (buttons[i].click == ClkClientWin)
948                                 for (j = 0; j < LENGTH(modifiers); j++)
949                                         XGrabButton(dpy, buttons[i].button,
950                                                 buttons[i].mask | modifiers[j],
951                                                 c->win, False, BUTTONMASK,
952                                                 GrabModeAsync, GrabModeSync, None, None);
953         }
954 }
955
956 void
957 grabkeys(void)
958 {
959         updatenumlockmask();
960         {
961                 unsigned int i, j;
962                 unsigned int modifiers[] = { 0, LockMask, numlockmask, numlockmask|LockMask };
963                 KeyCode code;
964
965                 XUngrabKey(dpy, AnyKey, AnyModifier, root);
966                 for (i = 0; i < LENGTH(keys); i++)
967                         if ((code = XKeysymToKeycode(dpy, keys[i].keysym)))
968                                 for (j = 0; j < LENGTH(modifiers); j++)
969                                         XGrabKey(dpy, code, keys[i].mod | modifiers[j], root,
970                                                 True, GrabModeAsync, GrabModeAsync);
971         }
972 }
973
974 void
975 incnmaster(const Arg *arg)
976 {
977         selmon->nmaster = MAX(selmon->nmaster + arg->i, 0);
978         arrange(selmon);
979 }
980
981 #ifdef XINERAMA
982 static int
983 isuniquegeom(XineramaScreenInfo *unique, size_t n, XineramaScreenInfo *info)
984 {
985         while (n--)
986                 if (unique[n].x_org == info->x_org && unique[n].y_org == info->y_org
987                 && unique[n].width == info->width && unique[n].height == info->height)
988                         return 0;
989         return 1;
990 }
991 #endif /* XINERAMA */
992
993 void
994 keypress(XEvent *e)
995 {
996         unsigned int i;
997         KeySym keysym;
998         XKeyEvent *ev;
999
1000         ev = &e->xkey;
1001         keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
1002         for (i = 0; i < LENGTH(keys); i++)
1003                 if (keysym == keys[i].keysym
1004                 && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state)
1005                 && keys[i].func)
1006                         keys[i].func(&(keys[i].arg));
1007 }
1008
1009 void
1010 killclient(const Arg *arg)
1011 {
1012         if (!selmon->sel)
1013                 return;
1014         if (!sendevent(selmon->sel, wmatom[WMDelete])) {
1015                 XGrabServer(dpy);
1016                 XSetErrorHandler(xerrordummy);
1017                 XSetCloseDownMode(dpy, DestroyAll);
1018                 XKillClient(dpy, selmon->sel->win);
1019                 XSync(dpy, False);
1020                 XSetErrorHandler(xerror);
1021                 XUngrabServer(dpy);
1022         }
1023 }
1024
1025 void
1026 manage(Window w, XWindowAttributes *wa)
1027 {
1028         Client *c, *t = NULL;
1029         Window trans = None;
1030         XWindowChanges wc;
1031
1032         c = ecalloc(1, sizeof(Client));
1033         c->win = w;
1034         /* geometry */
1035         c->x = c->oldx = wa->x;
1036         c->y = c->oldy = wa->y;
1037         c->w = c->oldw = wa->width;
1038         c->h = c->oldh = wa->height;
1039         c->oldbw = wa->border_width;
1040
1041         updatetitle(c);
1042         if (XGetTransientForHint(dpy, w, &trans) && (t = wintoclient(trans))) {
1043                 c->mon = t->mon;
1044                 c->tags = t->tags;
1045         } else {
1046                 c->mon = selmon;
1047                 applyrules(c);
1048         }
1049
1050         if (c->x + WIDTH(c) > c->mon->mx + c->mon->mw)
1051                 c->x = c->mon->mx + c->mon->mw - WIDTH(c);
1052         if (c->y + HEIGHT(c) > c->mon->my + c->mon->mh)
1053                 c->y = c->mon->my + c->mon->mh - HEIGHT(c);
1054         c->x = MAX(c->x, c->mon->mx);
1055         /* only fix client y-offset, if the client center might cover the bar */
1056         c->y = MAX(c->y, ((c->mon->by == c->mon->my) && (c->x + (c->w / 2) >= c->mon->wx)
1057                 && (c->x + (c->w / 2) < c->mon->wx + c->mon->ww)) ? bh : c->mon->my);
1058         c->bw = borderpx;
1059
1060         wc.border_width = c->bw;
1061         XConfigureWindow(dpy, w, CWBorderWidth, &wc);
1062         XSetWindowBorder(dpy, w, scheme[SchemeNorm][ColBorder].pixel);
1063         configure(c); /* propagates border_width, if size doesn't change */
1064         updatewindowtype(c);
1065         updatesizehints(c);
1066         updatewmhints(c);
1067         XSelectInput(dpy, w, EnterWindowMask|FocusChangeMask|PropertyChangeMask|StructureNotifyMask);
1068         grabbuttons(c, 0);
1069         if (!c->isfloating)
1070                 c->isfloating = c->oldstate = trans != None || c->isfixed;
1071         if (c->isfloating)
1072                 XRaiseWindow(dpy, c->win);
1073         attachbottom(c);
1074         attachstack(c);
1075         XChangeProperty(dpy, root, netatom[NetClientList], XA_WINDOW, 32, PropModeAppend,
1076                 (unsigned char *) &(c->win), 1);
1077         XMoveResizeWindow(dpy, c->win, c->x + 2 * sw, c->y, c->w, c->h); /* some windows require this */
1078         setclientstate(c, NormalState);
1079         if (c->mon == selmon)
1080                 unfocus(selmon->sel, 0);
1081         c->mon->sel = c;
1082         arrange(c->mon);
1083         XMapWindow(dpy, c->win);
1084         focus(NULL);
1085 }
1086
1087 void
1088 mappingnotify(XEvent *e)
1089 {
1090         XMappingEvent *ev = &e->xmapping;
1091
1092         XRefreshKeyboardMapping(ev);
1093         if (ev->request == MappingKeyboard)
1094                 grabkeys();
1095 }
1096
1097 void
1098 maprequest(XEvent *e)
1099 {
1100         static XWindowAttributes wa;
1101         XMapRequestEvent *ev = &e->xmaprequest;
1102
1103         if (!XGetWindowAttributes(dpy, ev->window, &wa))
1104                 return;
1105         if (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         restack(selmon);
1155         ocx = c->x;
1156         ocy = c->y;
1157         if (XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1158                 None, cursor[CurMove]->cursor, CurrentTime) != GrabSuccess)
1159                 return;
1160         if (!getrootptr(&x, &y))
1161                 return;
1162         do {
1163                 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
1164                 switch(ev.type) {
1165                 case ConfigureRequest:
1166                 case Expose:
1167                 case MapRequest:
1168                         handler[ev.type](&ev);
1169                         break;
1170                 case MotionNotify:
1171                         if ((ev.xmotion.time - lasttime) <= (1000 / 60))
1172                                 continue;
1173                         lasttime = ev.xmotion.time;
1174
1175                         nx = ocx + (ev.xmotion.x - x);
1176                         ny = ocy + (ev.xmotion.y - y);
1177                         if (abs(selmon->wx - nx) < snap)
1178                                 nx = selmon->wx;
1179                         else if (abs((selmon->wx + selmon->ww) - (nx + WIDTH(c))) < snap)
1180                                 nx = selmon->wx + selmon->ww - WIDTH(c);
1181                         if (abs(selmon->wy - ny) < snap)
1182                                 ny = selmon->wy;
1183                         else if (abs((selmon->wy + selmon->wh) - (ny + HEIGHT(c))) < snap)
1184                                 ny = selmon->wy + selmon->wh - HEIGHT(c);
1185                         if (!c->isfloating && selmon->lt[selmon->sellt]->arrange
1186                         && (abs(nx - c->x) > snap || abs(ny - c->y) > snap))
1187                                 togglefloating(NULL);
1188                         if (!selmon->lt[selmon->sellt]->arrange || c->isfloating)
1189                                 resize(c, nx, ny, c->w, c->h, 1);
1190                         break;
1191                 }
1192         } while (ev.type != ButtonRelease);
1193         XUngrabPointer(dpy, CurrentTime);
1194         if ((m = recttomon(c->x, c->y, c->w, c->h)) != selmon) {
1195                 sendmon(c, m);
1196                 selmon = m;
1197                 focus(NULL);
1198         }
1199 }
1200
1201 Client *
1202 nexttiled(Client *c)
1203 {
1204         for (; c && (c->isfloating || !ISVISIBLE(c)); c = c->next);
1205         return c;
1206 }
1207
1208 void
1209 pop(Client *c)
1210 {
1211         detach(c);
1212         attach(c);
1213         focus(c);
1214         arrange(c->mon);
1215 }
1216
1217 void
1218 propertynotify(XEvent *e)
1219 {
1220         Client *c;
1221         Window trans;
1222         XPropertyEvent *ev = &e->xproperty;
1223
1224         if ((ev->window == root) && (ev->atom == XA_WM_NAME))
1225                 updatestatus();
1226         else if (ev->state == PropertyDelete)
1227                 return; /* ignore */
1228         else if ((c = wintoclient(ev->window))) {
1229                 switch(ev->atom) {
1230                 default: break;
1231                 case XA_WM_TRANSIENT_FOR:
1232                         if (!c->isfloating && (XGetTransientForHint(dpy, c->win, &trans)) &&
1233                                 (c->isfloating = (wintoclient(trans)) != NULL))
1234                                 arrange(c->mon);
1235                         break;
1236                 case XA_WM_NORMAL_HINTS:
1237                         updatesizehints(c);
1238                         break;
1239                 case XA_WM_HINTS:
1240                         updatewmhints(c);
1241                         drawbars();
1242                         break;
1243                 }
1244                 if (ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
1245                         updatetitle(c);
1246                         if (c == c->mon->sel)
1247                                 drawbar(c->mon);
1248                 }
1249                 if (ev->atom == netatom[NetWMWindowType])
1250                         updatewindowtype(c);
1251         }
1252 }
1253
1254 void
1255 quit(const Arg *arg)
1256 {
1257         running = 0;
1258 }
1259
1260 Monitor *
1261 recttomon(int x, int y, int w, int h)
1262 {
1263         Monitor *m, *r = selmon;
1264         int a, area = 0;
1265
1266         for (m = mons; m; m = m->next)
1267                 if ((a = INTERSECT(x, y, w, h, m)) > area) {
1268                         area = a;
1269                         r = m;
1270                 }
1271         return r;
1272 }
1273
1274 void
1275 resize(Client *c, int x, int y, int w, int h, int interact)
1276 {
1277         if (applysizehints(c, &x, &y, &w, &h, interact))
1278                 resizeclient(c, x, y, w, h);
1279 }
1280
1281 void
1282 resizeclient(Client *c, int x, int y, int w, int h)
1283 {
1284         XWindowChanges wc;
1285
1286         c->oldx = c->x; c->x = wc.x = x;
1287         c->oldy = c->y; c->y = wc.y = y;
1288         c->oldw = c->w; c->w = wc.width = w;
1289         c->oldh = c->h; c->h = wc.height = h;
1290         wc.border_width = c->bw;
1291         XConfigureWindow(dpy, c->win, CWX|CWY|CWWidth|CWHeight|CWBorderWidth, &wc);
1292         configure(c);
1293         XSync(dpy, False);
1294 }
1295
1296 void
1297 resizemouse(const Arg *arg)
1298 {
1299         int ocx, ocy, nw, nh;
1300         Client *c;
1301         Monitor *m;
1302         XEvent ev;
1303         Time lasttime = 0;
1304
1305         if (!(c = selmon->sel))
1306                 return;
1307         restack(selmon);
1308         ocx = c->x;
1309         ocy = c->y;
1310         if (XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1311                 None, cursor[CurResize]->cursor, CurrentTime) != GrabSuccess)
1312                 return;
1313         XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->bw - 1, c->h + c->bw - 1);
1314         do {
1315                 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
1316                 switch(ev.type) {
1317                 case ConfigureRequest:
1318                 case Expose:
1319                 case MapRequest:
1320                         handler[ev.type](&ev);
1321                         break;
1322                 case MotionNotify:
1323                         if ((ev.xmotion.time - lasttime) <= (1000 / 60))
1324                                 continue;
1325                         lasttime = ev.xmotion.time;
1326
1327                         nw = MAX(ev.xmotion.x - ocx - 2 * c->bw + 1, 1);
1328                         nh = MAX(ev.xmotion.y - ocy - 2 * c->bw + 1, 1);
1329                         if (c->mon->wx + nw >= selmon->wx && c->mon->wx + nw <= selmon->wx + selmon->ww
1330                         && c->mon->wy + nh >= selmon->wy && c->mon->wy + nh <= selmon->wy + selmon->wh)
1331                         {
1332                                 if (!c->isfloating && selmon->lt[selmon->sellt]->arrange
1333                                 && (abs(nw - c->w) > snap || abs(nh - c->h) > snap))
1334                                         togglefloating(NULL);
1335                         }
1336                         if (!selmon->lt[selmon->sellt]->arrange || c->isfloating)
1337                                 resize(c, c->x, c->y, nw, nh, 1);
1338                         break;
1339                 }
1340         } while (ev.type != ButtonRelease);
1341         XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->bw - 1, c->h + c->bw - 1);
1342         XUngrabPointer(dpy, CurrentTime);
1343         while (XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1344         if ((m = recttomon(c->x, c->y, c->w, c->h)) != selmon) {
1345                 sendmon(c, m);
1346                 selmon = m;
1347                 focus(NULL);
1348         }
1349 }
1350
1351 void
1352 restack(Monitor *m)
1353 {
1354         Client *c;
1355         XEvent ev;
1356         XWindowChanges wc;
1357
1358         drawbar(m);
1359         if (!m->sel)
1360                 return;
1361         if (m->sel->isfloating || !m->lt[m->sellt]->arrange)
1362                 XRaiseWindow(dpy, m->sel->win);
1363         if (m->lt[m->sellt]->arrange) {
1364                 wc.stack_mode = Below;
1365                 wc.sibling = m->barwin;
1366                 for (c = m->stack; c; c = c->snext)
1367                         if (!c->isfloating && ISVISIBLE(c)) {
1368                                 XConfigureWindow(dpy, c->win, CWSibling|CWStackMode, &wc);
1369                                 wc.sibling = c->win;
1370                         }
1371         }
1372         XSync(dpy, False);
1373         while (XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1374 }
1375
1376 void
1377 run(void)
1378 {
1379         XEvent ev;
1380         /* main event loop */
1381         XSync(dpy, False);
1382         while (running && !XNextEvent(dpy, &ev))
1383                 if (handler[ev.type])
1384                         handler[ev.type](&ev); /* call handler */
1385 }
1386
1387 void
1388 scan(void)
1389 {
1390         unsigned int i, num;
1391         Window d1, d2, *wins = NULL;
1392         XWindowAttributes wa;
1393
1394         if (XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1395                 for (i = 0; i < num; i++) {
1396                         if (!XGetWindowAttributes(dpy, wins[i], &wa)
1397                         || wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1398                                 continue;
1399                         if (wa.map_state == IsViewable || getstate(wins[i]) == IconicState)
1400                                 manage(wins[i], &wa);
1401                 }
1402                 for (i = 0; i < num; i++) { /* now the transients */
1403                         if (!XGetWindowAttributes(dpy, wins[i], &wa))
1404                                 continue;
1405                         if (XGetTransientForHint(dpy, wins[i], &d1)
1406                         && (wa.map_state == IsViewable || getstate(wins[i]) == IconicState))
1407                                 manage(wins[i], &wa);
1408                 }
1409                 if (wins)
1410                         XFree(wins);
1411         }
1412 }
1413
1414 void
1415 sendmon(Client *c, Monitor *m)
1416 {
1417         if (c->mon == m)
1418                 return;
1419         unfocus(c, 1);
1420         detach(c);
1421         detachstack(c);
1422         c->mon = m;
1423         c->tags = m->tagset[m->seltags]; /* assign tags of target monitor */
1424         attachbottom(c);
1425         attachstack(c);
1426         focus(NULL);
1427         arrange(NULL);
1428 }
1429
1430 void
1431 setclientstate(Client *c, long state)
1432 {
1433         long data[] = { state, None };
1434
1435         XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1436                 PropModeReplace, (unsigned char *)data, 2);
1437 }
1438
1439 int
1440 sendevent(Client *c, Atom proto)
1441 {
1442         int n;
1443         Atom *protocols;
1444         int exists = 0;
1445         XEvent ev;
1446
1447         if (XGetWMProtocols(dpy, c->win, &protocols, &n)) {
1448                 while (!exists && n--)
1449                         exists = protocols[n] == proto;
1450                 XFree(protocols);
1451         }
1452         if (exists) {
1453                 ev.type = ClientMessage;
1454                 ev.xclient.window = c->win;
1455                 ev.xclient.message_type = wmatom[WMProtocols];
1456                 ev.xclient.format = 32;
1457                 ev.xclient.data.l[0] = proto;
1458                 ev.xclient.data.l[1] = CurrentTime;
1459                 XSendEvent(dpy, c->win, False, NoEventMask, &ev);
1460         }
1461         return exists;
1462 }
1463
1464 void
1465 setfocus(Client *c)
1466 {
1467         if (!c->neverfocus) {
1468                 XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
1469                 XChangeProperty(dpy, root, netatom[NetActiveWindow],
1470                         XA_WINDOW, 32, PropModeReplace,
1471                         (unsigned char *) &(c->win), 1);
1472         }
1473         sendevent(c, wmatom[WMTakeFocus]);
1474 }
1475
1476 void
1477 setfullscreen(Client *c, int fullscreen)
1478 {
1479         if (fullscreen && !c->isfullscreen) {
1480                 XChangeProperty(dpy, c->win, netatom[NetWMState], XA_ATOM, 32,
1481                         PropModeReplace, (unsigned char*)&netatom[NetWMFullscreen], 1);
1482                 c->isfullscreen = 1;
1483         } else if (!fullscreen && c->isfullscreen){
1484                 XChangeProperty(dpy, c->win, netatom[NetWMState], XA_ATOM, 32,
1485                         PropModeReplace, (unsigned char*)0, 0);
1486                 c->isfullscreen = 0;
1487         }
1488 }
1489
1490 void
1491 setlayout(const Arg *arg)
1492 {
1493         if (!arg || !arg->v || arg->v != selmon->lt[selmon->sellt])
1494                 selmon->sellt ^= 1;
1495         if (arg && arg->v)
1496                 selmon->lt[selmon->sellt] = (Layout *)arg->v;
1497         strncpy(selmon->ltsymbol, selmon->lt[selmon->sellt]->symbol, sizeof selmon->ltsymbol);
1498         if (selmon->sel)
1499                 arrange(selmon);
1500         else
1501                 drawbar(selmon);
1502 }
1503
1504 /* arg > 1.0 will set mfact absolutely */
1505 void
1506 setmfact(const Arg *arg)
1507 {
1508         float f;
1509
1510         if (!arg || !selmon->lt[selmon->sellt]->arrange)
1511                 return;
1512         f = arg->f < 1.0 ? arg->f + selmon->mfact : arg->f - 1.0;
1513         if (f < 0.05 || f > 0.95)
1514                 return;
1515         selmon->mfact = f;
1516         arrange(selmon);
1517 }
1518
1519 void
1520 setup(void)
1521 {
1522         int i;
1523         XSetWindowAttributes wa;
1524         Atom utf8string;
1525
1526         /* clean up any zombies immediately */
1527         sigchld(0);
1528
1529         /* init screen */
1530         screen = DefaultScreen(dpy);
1531         sw = DisplayWidth(dpy, screen);
1532         sh = DisplayHeight(dpy, screen);
1533         root = RootWindow(dpy, screen);
1534         drw = drw_create(dpy, screen, root, sw, sh);
1535         if (!drw_fontset_create(drw, fonts, LENGTH(fonts)))
1536                 die("no fonts could be loaded.");
1537         lrpad = drw->fonts->h;
1538         bh = drw->fonts->h + 2;
1539         updategeom();
1540         /* init atoms */
1541         utf8string = XInternAtom(dpy, "UTF8_STRING", False);
1542         wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1543         wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1544         wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1545         wmatom[WMTakeFocus] = XInternAtom(dpy, "WM_TAKE_FOCUS", False);
1546         netatom[NetActiveWindow] = XInternAtom(dpy, "_NET_ACTIVE_WINDOW", False);
1547         netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1548         netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1549         netatom[NetWMState] = XInternAtom(dpy, "_NET_WM_STATE", False);
1550         netatom[NetWMCheck] = XInternAtom(dpy, "_NET_SUPPORTING_WM_CHECK", False);
1551         netatom[NetWMFullscreen] = XInternAtom(dpy, "_NET_WM_STATE_FULLSCREEN", False);
1552         netatom[NetWMWindowType] = XInternAtom(dpy, "_NET_WM_WINDOW_TYPE", False);
1553         netatom[NetWMWindowTypeDialog] = XInternAtom(dpy, "_NET_WM_WINDOW_TYPE_DIALOG", False);
1554         netatom[NetClientList] = XInternAtom(dpy, "_NET_CLIENT_LIST", False);
1555         /* init cursors */
1556         cursor[CurNormal] = drw_cur_create(drw, XC_left_ptr);
1557         cursor[CurResize] = drw_cur_create(drw, XC_sizing);
1558         cursor[CurMove] = drw_cur_create(drw, XC_fleur);
1559         /* init appearance */
1560         scheme = ecalloc(LENGTH(colors), sizeof(Clr *));
1561         for (i = 0; i < LENGTH(colors); i++)
1562                 scheme[i] = drw_scm_create(drw, colors[i], 3);
1563         /* init bars */
1564         updatebars();
1565         updatestatus();
1566         /* supporting window for NetWMCheck */
1567         wmcheckwin = XCreateSimpleWindow(dpy, root, 0, 0, 1, 1, 0, 0, 0);
1568         XChangeProperty(dpy, wmcheckwin, netatom[NetWMCheck], XA_WINDOW, 32,
1569                 PropModeReplace, (unsigned char *) &wmcheckwin, 1);
1570         XChangeProperty(dpy, wmcheckwin, netatom[NetWMName], utf8string, 8,
1571                 PropModeReplace, (unsigned char *) "dwm", 3);
1572         XChangeProperty(dpy, root, netatom[NetWMCheck], XA_WINDOW, 32,
1573                 PropModeReplace, (unsigned char *) &wmcheckwin, 1);
1574         /* EWMH support per view */
1575         XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1576                 PropModeReplace, (unsigned char *) netatom, NetLast);
1577         XDeleteProperty(dpy, root, netatom[NetClientList]);
1578         /* select events */
1579         wa.cursor = cursor[CurNormal]->cursor;
1580         wa.event_mask = SubstructureRedirectMask|SubstructureNotifyMask
1581                 |ButtonPressMask|PointerMotionMask|EnterWindowMask
1582                 |LeaveWindowMask|StructureNotifyMask|PropertyChangeMask;
1583         XChangeWindowAttributes(dpy, root, CWEventMask|CWCursor, &wa);
1584         XSelectInput(dpy, root, wa.event_mask);
1585         grabkeys();
1586         focus(NULL);
1587 }
1588
1589
1590 void
1591 seturgent(Client *c, int urg)
1592 {
1593         XWMHints *wmh;
1594
1595         c->isurgent = urg;
1596         if (!(wmh = XGetWMHints(dpy, c->win)))
1597                 return;
1598         wmh->flags = urg ? (wmh->flags | XUrgencyHint) : (wmh->flags & ~XUrgencyHint);
1599         XSetWMHints(dpy, c->win, wmh);
1600         XFree(wmh);
1601 }
1602
1603 void
1604 showhide(Client *c)
1605 {
1606         if (!c)
1607                 return;
1608         if (ISVISIBLE(c)) {
1609                 /* show clients top down */
1610                 XMoveWindow(dpy, c->win, c->x, c->y);
1611                 if (!c->mon->lt[c->mon->sellt]->arrange || c->isfloating)
1612                         resize(c, c->x, c->y, c->w, c->h, 0);
1613                 showhide(c->snext);
1614         } else {
1615                 /* hide clients bottom up */
1616                 showhide(c->snext);
1617                 XMoveWindow(dpy, c->win, WIDTH(c) * -2, c->y);
1618         }
1619 }
1620
1621 void
1622 sigchld(int unused)
1623 {
1624         if (signal(SIGCHLD, sigchld) == SIG_ERR)
1625                 die("can't install SIGCHLD handler:");
1626         while (0 < waitpid(-1, NULL, WNOHANG));
1627 }
1628
1629 void
1630 spawn(const Arg *arg)
1631 {
1632         if (arg->v == dmenucmd)
1633                 dmenumon[0] = '0' + selmon->num;
1634         if (fork() == 0) {
1635                 if (dpy)
1636                         close(ConnectionNumber(dpy));
1637                 setsid();
1638                 execvp(((char **)arg->v)[0], (char **)arg->v);
1639                 fprintf(stderr, "dwm: execvp %s", ((char **)arg->v)[0]);
1640                 perror(" failed");
1641                 exit(EXIT_SUCCESS);
1642         }
1643 }
1644
1645 void
1646 tag(const Arg *arg)
1647 {
1648         if (selmon->sel && arg->ui & TAGMASK) {
1649                 selmon->sel->tags = arg->ui & TAGMASK;
1650                 focus(NULL);
1651                 arrange(selmon);
1652         }
1653 }
1654
1655 void
1656 tagmon(const Arg *arg)
1657 {
1658         if (!selmon->sel || !mons->next)
1659                 return;
1660         sendmon(selmon->sel, dirtomon(arg->i));
1661 }
1662
1663 void
1664 tile(Monitor *m)
1665 {
1666         unsigned int i, n, h, mw, my, ty;
1667         Client *c;
1668
1669         for (n = 0, c = nexttiled(m->clients); c; c = nexttiled(c->next), n++);
1670         if (n == 0)
1671                 return;
1672
1673         if (n > m->nmaster)
1674                 mw = m->nmaster ? m->ww * m->mfact : 0;
1675         else
1676                 mw = m->ww;
1677         for (i = my = ty = 0, c = nexttiled(m->clients); c; c = nexttiled(c->next), i++)
1678                 if (i < m->nmaster) {
1679                         h = (m->wh - my) / (MIN(n, m->nmaster) - i);
1680                         resize(c, m->wx, m->wy + my, mw - (2*c->bw), h - (2*c->bw), 0);
1681                         if (my + HEIGHT(c) < m->wh)
1682                                 my += HEIGHT(c);
1683                 } else {
1684                         h = (m->wh - ty) / (n - i);
1685                         resize(c, m->wx + mw, m->wy + ty, m->ww - mw - (2*c->bw), h - (2*c->bw), 0);
1686                         if (ty + HEIGHT(c) < m->wh)
1687                                 ty += HEIGHT(c);
1688                 }
1689 }
1690
1691 void
1692 togglebar(const Arg *arg)
1693 {
1694         selmon->showbar = !selmon->showbar;
1695         updatebarpos(selmon);
1696         XMoveResizeWindow(dpy, selmon->barwin, selmon->wx, selmon->by, selmon->ww, bh);
1697         arrange(selmon);
1698 }
1699
1700 void
1701 togglefloating(const Arg *arg)
1702 {
1703         if (!selmon->sel)
1704                 return;
1705         selmon->sel->isfloating = !selmon->sel->isfloating || selmon->sel->isfixed;
1706         if (selmon->sel->isfloating)
1707                 resize(selmon->sel, selmon->sel->x, selmon->sel->y,
1708                         selmon->sel->w, selmon->sel->h, 0);
1709         arrange(selmon);
1710 }
1711
1712 void
1713 toggletag(const Arg *arg)
1714 {
1715         unsigned int newtags;
1716
1717         if (!selmon->sel)
1718                 return;
1719         newtags = selmon->sel->tags ^ (arg->ui & TAGMASK);
1720         if (newtags) {
1721                 selmon->sel->tags = newtags;
1722                 focus(NULL);
1723                 arrange(selmon);
1724         }
1725 }
1726
1727 void
1728 toggleview(const Arg *arg)
1729 {
1730         unsigned int newtagset = selmon->tagset[selmon->seltags] ^ (arg->ui & TAGMASK);
1731
1732         if (newtagset) {
1733                 selmon->tagset[selmon->seltags] = newtagset;
1734                 focus(NULL);
1735                 arrange(selmon);
1736         }
1737 }
1738
1739 void
1740 unfocus(Client *c, int setfocus)
1741 {
1742         if (!c)
1743                 return;
1744         grabbuttons(c, 0);
1745         XSetWindowBorder(dpy, c->win, scheme[SchemeNorm][ColBorder].pixel);
1746         if (setfocus) {
1747                 XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
1748                 XDeleteProperty(dpy, root, netatom[NetActiveWindow]);
1749         }
1750 }
1751
1752 void
1753 unmanage(Client *c, int destroyed)
1754 {
1755         Monitor *m = c->mon;
1756         XWindowChanges wc;
1757
1758         detach(c);
1759         detachstack(c);
1760         if (!destroyed) {
1761                 wc.border_width = c->oldbw;
1762                 XGrabServer(dpy); /* avoid race conditions */
1763                 XSetErrorHandler(xerrordummy);
1764                 XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
1765                 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1766                 setclientstate(c, WithdrawnState);
1767                 XSync(dpy, False);
1768                 XSetErrorHandler(xerror);
1769                 XUngrabServer(dpy);
1770         }
1771         free(c);
1772
1773         focus(NULL);
1774         updateclientlist();
1775         arrange(m);
1776 }
1777
1778 void
1779 unmapnotify(XEvent *e)
1780 {
1781         Client *c;
1782         XUnmapEvent *ev = &e->xunmap;
1783
1784         if ((c = wintoclient(ev->window))) {
1785                 if (ev->send_event)
1786                         setclientstate(c, WithdrawnState);
1787                 else
1788                         unmanage(c, 0);
1789         }
1790 }
1791
1792 void
1793 updatebars(void)
1794 {
1795         Monitor *m;
1796         XSetWindowAttributes wa = {
1797                 .override_redirect = True,
1798                 .background_pixmap = ParentRelative,
1799                 .event_mask = ButtonPressMask|ExposureMask
1800         };
1801         XClassHint ch = {"dwm", "dwm"};
1802         for (m = mons; m; m = m->next) {
1803                 if (m->barwin)
1804                         continue;
1805                 m->barwin = XCreateWindow(dpy, root, m->wx, m->by, m->ww, bh, 0, DefaultDepth(dpy, screen),
1806                                 CopyFromParent, DefaultVisual(dpy, screen),
1807                                 CWOverrideRedirect|CWBackPixmap|CWEventMask, &wa);
1808                 XDefineCursor(dpy, m->barwin, cursor[CurNormal]->cursor);
1809                 XMapRaised(dpy, m->barwin);
1810                 XSetClassHint(dpy, m->barwin, &ch);
1811         }
1812 }
1813
1814 void
1815 updatebarpos(Monitor *m)
1816 {
1817         m->wy = m->my;
1818         m->wh = m->mh;
1819         if (m->showbar) {
1820                 m->wh -= bh;
1821                 m->by = m->topbar ? m->wy : m->wy + m->wh;
1822                 m->wy = m->topbar ? m->wy + bh : m->wy;
1823         } else
1824                 m->by = -bh;
1825 }
1826
1827 void
1828 updateclientlist()
1829 {
1830         Client *c;
1831         Monitor *m;
1832
1833         XDeleteProperty(dpy, root, netatom[NetClientList]);
1834         for (m = mons; m; m = m->next)
1835                 for (c = m->clients; c; c = c->next)
1836                         XChangeProperty(dpy, root, netatom[NetClientList],
1837                                 XA_WINDOW, 32, PropModeAppend,
1838                                 (unsigned char *) &(c->win), 1);
1839 }
1840
1841 int
1842 updategeom(void)
1843 {
1844         int dirty = 0;
1845
1846 #ifdef XINERAMA
1847         if (XineramaIsActive(dpy)) {
1848                 int i, j, n, nn;
1849                 Client *c;
1850                 Monitor *m;
1851                 XineramaScreenInfo *info = XineramaQueryScreens(dpy, &nn);
1852                 XineramaScreenInfo *unique = NULL;
1853
1854                 for (n = 0, m = mons; m; m = m->next, n++);
1855                 /* only consider unique geometries as separate screens */
1856                 unique = ecalloc(nn, sizeof(XineramaScreenInfo));
1857                 for (i = 0, j = 0; i < nn; i++)
1858                         if (isuniquegeom(unique, j, &info[i]))
1859                                 memcpy(&unique[j++], &info[i], sizeof(XineramaScreenInfo));
1860                 XFree(info);
1861                 nn = j;
1862                 if (n <= nn) { /* new monitors available */
1863                         for (i = 0; i < (nn - n); i++) {
1864                                 for (m = mons; m && m->next; m = m->next);
1865                                 if (m)
1866                                         m->next = createmon();
1867                                 else
1868                                         mons = createmon();
1869                         }
1870                         for (i = 0, m = mons; i < nn && m; m = m->next, i++)
1871                                 if (i >= n
1872                                 || unique[i].x_org != m->mx || unique[i].y_org != m->my
1873                                 || unique[i].width != m->mw || unique[i].height != m->mh)
1874                                 {
1875                                         dirty = 1;
1876                                         m->num = i;
1877                                         m->mx = m->wx = unique[i].x_org;
1878                                         m->my = m->wy = unique[i].y_org;
1879                                         m->mw = m->ww = unique[i].width;
1880                                         m->mh = m->wh = unique[i].height;
1881                                         updatebarpos(m);
1882                                 }
1883                 } else { /* less monitors available nn < n */
1884                         for (i = nn; i < n; i++) {
1885                                 for (m = mons; m && m->next; m = m->next);
1886                                 while ((c = m->clients)) {
1887                                         dirty = 1;
1888                                         m->clients = c->next;
1889                                         detachstack(c);
1890                                         c->mon = mons;
1891                                         attachbottom(c);
1892                                         attachstack(c);
1893                                 }
1894                                 if (m == selmon)
1895                                         selmon = mons;
1896                                 cleanupmon(m);
1897                         }
1898                 }
1899                 free(unique);
1900         } else
1901 #endif /* XINERAMA */
1902         { /* default monitor setup */
1903                 if (!mons)
1904                         mons = createmon();
1905                 if (mons->mw != sw || mons->mh != sh) {
1906                         dirty = 1;
1907                         mons->mw = mons->ww = sw;
1908                         mons->mh = mons->wh = sh;
1909                         updatebarpos(mons);
1910                 }
1911         }
1912         if (dirty) {
1913                 selmon = mons;
1914                 selmon = wintomon(root);
1915         }
1916         return dirty;
1917 }
1918
1919 void
1920 updatenumlockmask(void)
1921 {
1922         unsigned int i, j;
1923         XModifierKeymap *modmap;
1924
1925         numlockmask = 0;
1926         modmap = XGetModifierMapping(dpy);
1927         for (i = 0; i < 8; i++)
1928                 for (j = 0; j < modmap->max_keypermod; j++)
1929                         if (modmap->modifiermap[i * modmap->max_keypermod + j]
1930                                 == XKeysymToKeycode(dpy, XK_Num_Lock))
1931                                 numlockmask = (1 << i);
1932         XFreeModifiermap(modmap);
1933 }
1934
1935 void
1936 updatesizehints(Client *c)
1937 {
1938         long msize;
1939         XSizeHints size;
1940
1941         if (!XGetWMNormalHints(dpy, c->win, &size, &msize))
1942                 /* size is uninitialized, ensure that size.flags aren't used */
1943                 size.flags = PSize;
1944         if (size.flags & PBaseSize) {
1945                 c->basew = size.base_width;
1946                 c->baseh = size.base_height;
1947         } else if (size.flags & PMinSize) {
1948                 c->basew = size.min_width;
1949                 c->baseh = size.min_height;
1950         } else
1951                 c->basew = c->baseh = 0;
1952         if (size.flags & PResizeInc) {
1953                 c->incw = size.width_inc;
1954                 c->inch = size.height_inc;
1955         } else
1956                 c->incw = c->inch = 0;
1957         if (size.flags & PMaxSize) {
1958                 c->maxw = size.max_width;
1959                 c->maxh = size.max_height;
1960         } else
1961                 c->maxw = c->maxh = 0;
1962         if (size.flags & PMinSize) {
1963                 c->minw = size.min_width;
1964                 c->minh = size.min_height;
1965         } else if (size.flags & PBaseSize) {
1966                 c->minw = size.base_width;
1967                 c->minh = size.base_height;
1968         } else
1969                 c->minw = c->minh = 0;
1970         if (size.flags & PAspect) {
1971                 c->mina = (float)size.min_aspect.y / size.min_aspect.x;
1972                 c->maxa = (float)size.max_aspect.x / size.max_aspect.y;
1973         } else
1974                 c->maxa = c->mina = 0.0;
1975         c->isfixed = (c->maxw && c->maxh && c->maxw == c->minw && c->maxh == c->minh);
1976 }
1977
1978 void
1979 updatestatus(void)
1980 {
1981         if (!gettextprop(root, XA_WM_NAME, stext, sizeof(stext)))
1982                 strcpy(stext, "dwm-"VERSION);
1983         drawbar(selmon);
1984 }
1985
1986 void
1987 updatetitle(Client *c)
1988 {
1989         if (!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
1990                 gettextprop(c->win, XA_WM_NAME, c->name, sizeof c->name);
1991         if (c->name[0] == '\0') /* hack to mark broken clients */
1992                 strcpy(c->name, broken);
1993 }
1994
1995 void
1996 updatewindowtype(Client *c)
1997 {
1998         Atom state = getatomprop(c, netatom[NetWMState]);
1999         Atom wtype = getatomprop(c, netatom[NetWMWindowType]);
2000
2001         if (state == netatom[NetWMFullscreen])
2002                 setfullscreen(c, 1);
2003         if (wtype == netatom[NetWMWindowTypeDialog])
2004                 c->isfloating = 1;
2005 }
2006
2007 void
2008 updatewmhints(Client *c)
2009 {
2010         XWMHints *wmh;
2011
2012         if ((wmh = XGetWMHints(dpy, c->win))) {
2013                 if (c == selmon->sel && wmh->flags & XUrgencyHint) {
2014                         wmh->flags &= ~XUrgencyHint;
2015                         XSetWMHints(dpy, c->win, wmh);
2016                 } else
2017                         c->isurgent = (wmh->flags & XUrgencyHint) ? 1 : 0;
2018                 if (wmh->flags & InputHint)
2019                         c->neverfocus = !wmh->input;
2020                 else
2021                         c->neverfocus = 0;
2022                 XFree(wmh);
2023         }
2024 }
2025
2026 void
2027 view(const Arg *arg)
2028 {
2029         if ((arg->ui & TAGMASK) == selmon->tagset[selmon->seltags])
2030                 return;
2031         selmon->seltags ^= 1; /* toggle sel tagset */
2032         if (arg->ui & TAGMASK)
2033                 selmon->tagset[selmon->seltags] = arg->ui & TAGMASK;
2034         focus(NULL);
2035         arrange(selmon);
2036 }
2037
2038 Client *
2039 wintoclient(Window w)
2040 {
2041         Client *c;
2042         Monitor *m;
2043
2044         for (m = mons; m; m = m->next)
2045                 for (c = m->clients; c; c = c->next)
2046                         if (c->win == w)
2047                                 return c;
2048         return NULL;
2049 }
2050
2051 Monitor *
2052 wintomon(Window w)
2053 {
2054         int x, y;
2055         Client *c;
2056         Monitor *m;
2057
2058         if (w == root && getrootptr(&x, &y))
2059                 return recttomon(x, y, 1, 1);
2060         for (m = mons; m; m = m->next)
2061                 if (w == m->barwin)
2062                         return m;
2063         if ((c = wintoclient(w)))
2064                 return c->mon;
2065         return selmon;
2066 }
2067
2068 /* There's no way to check accesses to destroyed windows, thus those cases are
2069  * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
2070  * default error handler, which may call exit. */
2071 int
2072 xerror(Display *dpy, XErrorEvent *ee)
2073 {
2074         if (ee->error_code == BadWindow
2075         || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
2076         || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
2077         || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
2078         || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
2079         || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
2080         || (ee->request_code == X_GrabButton && ee->error_code == BadAccess)
2081         || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
2082         || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
2083                 return 0;
2084         fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
2085                 ee->request_code, ee->error_code);
2086         return xerrorxlib(dpy, ee); /* may call exit */
2087 }
2088
2089 int
2090 xerrordummy(Display *dpy, XErrorEvent *ee)
2091 {
2092         return 0;
2093 }
2094
2095 /* Startup Error handler to check if another window manager
2096  * is already running. */
2097 int
2098 xerrorstart(Display *dpy, XErrorEvent *ee)
2099 {
2100         die("dwm: another window manager is already running");
2101         return -1;
2102 }
2103
2104 void
2105 zoom(const Arg *arg)
2106 {
2107         Client *c = selmon->sel;
2108
2109         if (!selmon->lt[selmon->sellt]->arrange
2110         || (selmon->sel && selmon->sel->isfloating))
2111                 return;
2112         if (c == nexttiled(selmon->clients))
2113                 if (!c || !(c = nexttiled(c->next)))
2114                         return;
2115         pop(c);
2116 }
2117
2118 int
2119 main(int argc, char *argv[])
2120 {
2121         if (argc == 2 && !strcmp("-v", argv[1]))
2122                 die("dwm-"VERSION);
2123         else if (argc != 1)
2124                 die("usage: dwm [-v]");
2125         if (!setlocale(LC_CTYPE, "") || !XSupportsLocale())
2126                 fputs("warning: no locale support\n", stderr);
2127         if (!(dpy = XOpenDisplay(NULL)))
2128                 die("dwm: cannot open display");
2129         checkotherwm();
2130         setup();
2131 #ifdef __OpenBSD__
2132         if (pledge("stdio rpath proc exec", NULL) == -1)
2133                 die("pledge");
2134 #endif /* __OpenBSD__ */
2135         scan();
2136         run();
2137         cleanup();
2138         XCloseDisplay(dpy);
2139         return EXIT_SUCCESS;
2140 }