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