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