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