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