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