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