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