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