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