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