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