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