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