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