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