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