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