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