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