JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
Mod1-Button2 on a floating but not-fixed client will make it tiled again
[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 the config.h
25  * file. These arrays are kept static in event.o and tag.o respectively,
26  * because no other part of dwm needs access to them.  The current layout is
27  * represented by the lt pointer.
28  *
29  * To understand everything else, start reading main().
30  */
31 #include <errno.h>
32 #include <locale.h>
33 #include <regex.h>
34 #include <stdarg.h>
35 #include <stdio.h>
36 #include <stdlib.h>
37 #include <string.h>
38 #include <unistd.h>
39 #include <sys/select.h>
40 #include <sys/wait.h>
41 #include <X11/cursorfont.h>
42 #include <X11/keysym.h>
43 #include <X11/Xatom.h>
44 #include <X11/Xproto.h>
45 #include <X11/Xutil.h>
46
47 /* macros */
48 #define BUTTONMASK              (ButtonPressMask | ButtonReleaseMask)
49 #define CLEANMASK(mask)         (mask & ~(numlockmask | LockMask))
50 #define MOUSEMASK               (BUTTONMASK | PointerMotionMask)
51
52 /* enums */
53 enum { BarTop, BarBot, BarOff };                        /* bar position */
54 enum { CurNormal, CurResize, CurMove, CurLast };        /* cursor */
55 enum { ColBorder, ColFG, ColBG, ColLast };              /* color */
56 enum { NetSupported, NetWMName, NetLast };              /* EWMH atoms */
57 enum { WMProtocols, WMDelete, WMName, WMState, WMLast };/* default atoms */
58
59 /* typedefs */
60 typedef struct Client Client;
61 struct Client {
62         char name[256];
63         int x, y, w, h;
64         int rx, ry, rw, rh; /* revert geometry */
65         int basew, baseh, incw, inch, maxw, maxh, minw, minh;
66         int minax, maxax, minay, maxay;
67         long flags; 
68         unsigned int border, oldborder;
69         Bool isbanned, isfixed, ismax, isfloating;
70         Bool *tags;
71         Client *next;
72         Client *prev;
73         Client *snext;
74         Window win;
75 };
76
77 typedef struct {
78         int x, y, w, h;
79         unsigned long norm[ColLast];
80         unsigned long sel[ColLast];
81         Drawable drawable;
82         GC gc;
83         struct {
84                 int ascent;
85                 int descent;
86                 int height;
87                 XFontSet set;
88                 XFontStruct *xfont;
89         } font;
90 } DC; /* draw context */
91
92 typedef struct {
93         unsigned long mod;
94         KeySym keysym;
95         void (*func)(const char *arg);
96         const char *arg;
97 } Key;
98
99 typedef struct {
100         const char *symbol;
101         void (*arrange)(void);
102 } Layout;
103
104 typedef struct {
105         const char *prop;
106         const char *tags;
107         Bool isfloating;
108 } Rule;
109
110 typedef struct {
111         regex_t *propregex;
112         regex_t *tagregex;
113 } Regs;
114
115 /* forward declarations */
116 static void applyrules(Client *c);
117 static void arrange(void);
118 static void attach(Client *c);
119 static void attachstack(Client *c);
120 static void ban(Client *c);
121 static void buttonpress(XEvent *e);
122 static void checkotherwm(void);
123 static void cleanup(void);
124 static void compileregs(void);
125 static void configure(Client *c);
126 static void configurenotify(XEvent *e);
127 static void configurerequest(XEvent *e);
128 static void destroynotify(XEvent *e);
129 static void detach(Client *c);
130 static void detachstack(Client *c);
131 static void drawbar(void);
132 static void drawsquare(Bool filled, Bool empty, unsigned long col[ColLast]);
133 static void drawtext(const char *text, unsigned long col[ColLast]);
134 static void *emallocz(unsigned int size);
135 static void enternotify(XEvent *e);
136 static void eprint(const char *errstr, ...);
137 static void expose(XEvent *e);
138 static void floating(void); /* default floating layout */
139 static void focus(Client *c);
140 static void focusnext(const char *arg);
141 static void focusprev(const char *arg);
142 static Client *getclient(Window w);
143 static unsigned long getcolor(const char *colstr);
144 static long getstate(Window w);
145 static Bool gettextprop(Window w, Atom atom, char *text, unsigned int size);
146 static void grabbuttons(Client *c, Bool focused);
147 static unsigned int idxoftag(const char *tag);
148 static void initfont(const char *fontstr);
149 static Bool isarrange(void (*func)());
150 static Bool isoccupied(unsigned int t);
151 static Bool isprotodel(Client *c);
152 static Bool isvisible(Client *c);
153 static void keypress(XEvent *e);
154 static void killclient(const char *arg);
155 static void leavenotify(XEvent *e);
156 static void manage(Window w, XWindowAttributes *wa);
157 static void mappingnotify(XEvent *e);
158 static void maprequest(XEvent *e);
159 static void movemouse(Client *c);
160 static Client *nexttiled(Client *c);
161 static void propertynotify(XEvent *e);
162 static void quit(const char *arg);
163 static void resize(Client *c, int x, int y, int w, int h, Bool sizehints);
164 static void resizemouse(Client *c);
165 static void restack(void);
166 static void run(void);
167 static void scan(void);
168 static void setclientstate(Client *c, long state);
169 static void setlayout(const char *arg);
170 static void setmwfact(const char *arg);
171 static void setup(void);
172 static void spawn(const char *arg);
173 static void tag(const char *arg);
174 static unsigned int textnw(const char *text, unsigned int len);
175 static unsigned int textw(const char *text);
176 static void tile(void);
177 static void togglebar(const char *arg);
178 static void togglefloating(const char *arg);
179 static void togglemax(const char *arg);
180 static void toggletag(const char *arg);
181 static void toggleview(const char *arg);
182 static void unban(Client *c);
183 static void unmanage(Client *c);
184 static void unmapnotify(XEvent *e);
185 static void updatebarpos(void);
186 static void updatesizehints(Client *c);
187 static void updatetitle(Client *c);
188 static void view(const char *arg);
189 static int xerror(Display *dpy, XErrorEvent *ee);
190 static int xerrordummy(Display *dsply, XErrorEvent *ee);
191 static int xerrorstart(Display *dsply, XErrorEvent *ee);
192 static void zoom(const char *arg);
193
194 /* variables */
195 static char stext[256];
196 static double mwfact;
197 static int screen, sx, sy, sw, sh, wax, way, waw, wah;
198 static int (*xerrorxlib)(Display *, XErrorEvent *);
199 static unsigned int bh, bpos, ntags;
200 static unsigned int blw = 0;
201 static unsigned int ltidx = 0; /* default */
202 static unsigned int nlayouts = 0;
203 static unsigned int nrules = 0;
204 static unsigned int numlockmask = 0;
205 static 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 static Atom wmatom[WMLast], netatom[NetLast];
220 static Bool otherwm, readin;
221 static Bool running = True;
222 static Bool *seltags;
223 static Bool selscreen = True;
224 static Client *clients = NULL;
225 static Client *sel = NULL;
226 static Client *stack = NULL;
227 static Cursor cursor[CurLast];
228 static Display *dpy;
229 static DC dc = {0};
230 static Window barwin, root;
231 static Regs *regs = NULL;
232
233 /* configuration, allows nested code to access above variables */
234 #include "config.h"
235
236 /* functions*/
237 static void
238 applyrules(Client *c) {
239         static char buf[512];
240         unsigned int i, j;
241         regmatch_t tmp;
242         Bool matched = False;
243         XClassHint ch = { 0 };
244
245         /* rule matching */
246         XGetClassHint(dpy, c->win, &ch);
247         snprintf(buf, sizeof buf, "%s:%s:%s",
248                         ch.res_class ? ch.res_class : "",
249                         ch.res_name ? ch.res_name : "", c->name);
250         for(i = 0; i < nrules; i++)
251                 if(regs[i].propregex && !regexec(regs[i].propregex, buf, 1, &tmp, 0)) {
252                         c->isfloating = rules[i].isfloating;
253                         for(j = 0; regs[i].tagregex && j < ntags; j++) {
254                                 if(!regexec(regs[i].tagregex, tags[j], 1, &tmp, 0)) {
255                                         matched = True;
256                                         c->tags[j] = True;
257                                 }
258                         }
259                 }
260         if(ch.res_class)
261                 XFree(ch.res_class);
262         if(ch.res_name)
263                 XFree(ch.res_name);
264         if(!matched)
265                 for(i = 0; i < ntags; i++)
266                         c->tags[i] = seltags[i];
267 }
268
269 static void
270 arrange(void) {
271         Client *c;
272
273         for(c = clients; c; c = c->next)
274                 if(isvisible(c))
275                         unban(c);
276                 else
277                         ban(c);
278         layouts[ltidx].arrange();
279         focus(NULL);
280         restack();
281 }
282
283 static void
284 attach(Client *c) {
285         if(clients)
286                 clients->prev = c;
287         c->next = clients;
288         clients = c;
289 }
290
291 static void
292 attachstack(Client *c) {
293         c->snext = stack;
294         stack = c;
295 }
296
297 static void
298 ban(Client *c) {
299         if(c->isbanned)
300                 return;
301         XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
302         c->isbanned = True;
303 }
304
305 static void
306 buttonpress(XEvent *e) {
307         unsigned int i, x;
308         Client *c;
309         XButtonPressedEvent *ev = &e->xbutton;
310
311         if(barwin == ev->window) {
312                 x = 0;
313                 for(i = 0; i < ntags; i++) {
314                         x += textw(tags[i]);
315                         if(ev->x < x) {
316                                 if(ev->button == Button1) {
317                                         if(ev->state & MODKEY)
318                                                 tag(tags[i]);
319                                         else
320                                                 view(tags[i]);
321                                 }
322                                 else if(ev->button == Button3) {
323                                         if(ev->state & MODKEY)
324                                                 toggletag(tags[i]);
325                                         else
326                                                 toggleview(tags[i]);
327                                 }
328                                 return;
329                         }
330                 }
331                 if((ev->x < x + blw) && ev->button == Button1)
332                         setlayout(NULL);
333         }
334         else if((c = getclient(ev->window))) {
335                 focus(c);
336                 if(CLEANMASK(ev->state) != MODKEY)
337                         return;
338                 if(ev->button == Button1) {
339                         if(!isarrange(floating) && !c->isfloating)
340                                 togglefloating(NULL);
341                         else
342                                 restack();
343                         movemouse(c);
344                 }
345                 else if(ev->button == Button2) {
346                         if(isarrange(tile) && !c->isfixed && c->isfloating)
347                                 togglefloating(NULL);
348                         else
349                                 zoom(NULL);
350                 }
351                 else if(ev->button == Button3 && !c->isfixed) {
352                         if(!isarrange(floating) && !c->isfloating)
353                                 togglefloating(NULL);
354                         else
355                                 restack();
356                         resizemouse(c);
357                 }
358         }
359 }
360
361 static void
362 checkotherwm(void) {
363         otherwm = False;
364         XSetErrorHandler(xerrorstart);
365
366         /* this causes an error if some other window manager is running */
367         XSelectInput(dpy, root, SubstructureRedirectMask);
368         XSync(dpy, False);
369         if(otherwm)
370                 eprint("dwm: another window manager is already running\n");
371         XSync(dpy, False);
372         XSetErrorHandler(NULL);
373         xerrorxlib = XSetErrorHandler(xerror);
374         XSync(dpy, False);
375 }
376
377 static void
378 cleanup(void) {
379         close(STDIN_FILENO);
380         while(stack) {
381                 unban(stack);
382                 unmanage(stack);
383         }
384         if(dc.font.set)
385                 XFreeFontSet(dpy, dc.font.set);
386         else
387                 XFreeFont(dpy, dc.font.xfont);
388         XUngrabKey(dpy, AnyKey, AnyModifier, root);
389         XFreePixmap(dpy, dc.drawable);
390         XFreeGC(dpy, dc.gc);
391         XDestroyWindow(dpy, barwin);
392         XFreeCursor(dpy, cursor[CurNormal]);
393         XFreeCursor(dpy, cursor[CurResize]);
394         XFreeCursor(dpy, cursor[CurMove]);
395         XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime);
396         XSync(dpy, False);
397         free(seltags);
398 }
399
400 static 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 static 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 static 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 static 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 static 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 static 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 static 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 static 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 static 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 static 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 static 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 static 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 static 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 static 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 static 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 static 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 static 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 static 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 static 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 static 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 static 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 static 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 static 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 static 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 static 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 static Bool
897 isarrange(void (*func)())
898 {
899         return func == layouts[ltidx].arrange;
900 }
901
902 static 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 static 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 static 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 static 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 static 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 static 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 static void
1002 manage(Window w, XWindowAttributes *wa) {
1003         unsigned int i;
1004         Client *c, *t = NULL;
1005         Window trans;
1006         Status rettrans;
1007         XWindowChanges wc;
1008
1009         c = emallocz(sizeof(Client));
1010         c->tags = emallocz(ntags * sizeof(Bool));
1011         c->win = w;
1012         c->x = wa->x;
1013         c->y = wa->y;
1014         c->w = wa->width;
1015         c->h = wa->height;
1016         c->oldborder = wa->border_width;
1017         if(c->w == sw && c->h == sh) {
1018                 c->x = sx;
1019                 c->y = sy;
1020                 c->border = wa->border_width;
1021         }
1022         else {
1023                 if(c->x + c->w + 2 * c->border > wax + waw)
1024                         c->x = wax + waw - c->w - 2 * c->border;
1025                 if(c->y + c->h + 2 * c->border > way + wah)
1026                         c->y = way + wah - c->h - 2 * c->border;
1027                 if(c->x < wax)
1028                         c->x = wax;
1029                 if(c->y < way)
1030                         c->y = way;
1031                 c->border = BORDERPX;
1032         }
1033         wc.border_width = c->border;
1034         XConfigureWindow(dpy, w, CWBorderWidth, &wc);
1035         XSetWindowBorder(dpy, w, dc.norm[ColBorder]);
1036         configure(c); /* propagates border_width, if size doesn't change */
1037         updatesizehints(c);
1038         XSelectInput(dpy, w,
1039                 StructureNotifyMask | PropertyChangeMask | EnterWindowMask);
1040         grabbuttons(c, False);
1041         updatetitle(c);
1042         if((rettrans = XGetTransientForHint(dpy, w, &trans) == Success))
1043                 for(t = clients; t && t->win != trans; t = t->next);
1044         if(t)
1045                 for(i = 0; i < ntags; i++)
1046                         c->tags[i] = t->tags[i];
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 static 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 static 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 static 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 static Client *
1125 nexttiled(Client *c) {
1126         for(; c && (c->isfloating || !isvisible(c)); c = c->next);
1127         return c;
1128 }
1129
1130 static 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 static void
1159 quit(const char *arg) {
1160         readin = running = False;
1161 }
1162
1163 static void
1164 resize(Client *c, int x, int y, int w, int h, Bool sizehints) {
1165         double dx, dy, max, min, ratio;
1166         XWindowChanges wc; 
1167
1168         if(sizehints) {
1169                 if(c->minay > 0 && c->maxay > 0 && (h - c->baseh) > 0 && (w - c->basew) > 0) {
1170                         dx = (double)(w - c->basew);
1171                         dy = (double)(h - c->baseh);
1172                         min = (double)(c->minax) / (double)(c->minay);
1173                         max = (double)(c->maxax) / (double)(c->maxay);
1174                         ratio = dx / dy;
1175                         if(max > 0 && min > 0 && ratio > 0) {
1176                                 if(ratio < min) {
1177                                         dy = (dx * min + dy) / (min * min + 1);
1178                                         dx = dy * min;
1179                                         w = (int)dx + c->basew;
1180                                         h = (int)dy + c->baseh;
1181                                 }
1182                                 else if(ratio > max) {
1183                                         dy = (dx * min + dy) / (max * max + 1);
1184                                         dx = dy * min;
1185                                         w = (int)dx + c->basew;
1186                                         h = (int)dy + c->baseh;
1187                                 }
1188                         }
1189                 }
1190                 if(c->minw && w < c->minw)
1191                         w = c->minw;
1192                 if(c->minh && h < c->minh)
1193                         h = c->minh;
1194                 if(c->maxw && w > c->maxw)
1195                         w = c->maxw;
1196                 if(c->maxh && h > c->maxh)
1197                         h = c->maxh;
1198                 if(c->incw)
1199                         w -= (w - c->basew) % c->incw;
1200                 if(c->inch)
1201                         h -= (h - c->baseh) % c->inch;
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 static 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 static 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 static 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 static 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 static 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 static 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 static void
1400 setmwfact(const char *arg) {
1401         double delta;
1402
1403         if(!isarrange(tile))
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 static void
1422 setup(void) {
1423         unsigned int i, j, mask;
1424         Window w;
1425         XModifierKeymap *modmap;
1426         XSetWindowAttributes wa;
1427
1428         /* init atoms */
1429         wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1430         wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1431         wmatom[WMName] = XInternAtom(dpy, "WM_NAME", False);
1432         wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1433         netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1434         netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1435         XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1436                         PropModeReplace, (unsigned char *) netatom, NetLast);
1437
1438         /* init cursors */
1439         cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1440         cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1441         cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1442
1443         /* init geometry */
1444         sx = sy = 0;
1445         sw = DisplayWidth(dpy, screen);
1446         sh = DisplayHeight(dpy, screen);
1447
1448         /* init modifier map */
1449         modmap = XGetModifierMapping(dpy);
1450         for(i = 0; i < 8; i++)
1451                 for(j = 0; j < modmap->max_keypermod; j++) {
1452                         if(modmap->modifiermap[i * modmap->max_keypermod + j]
1453                         == XKeysymToKeycode(dpy, XK_Num_Lock))
1454                                 numlockmask = (1 << i);
1455                 }
1456         XFreeModifiermap(modmap);
1457
1458         /* select for events */
1459         wa.event_mask = SubstructureRedirectMask | SubstructureNotifyMask
1460                 | EnterWindowMask | LeaveWindowMask | StructureNotifyMask;
1461         wa.cursor = cursor[CurNormal];
1462         XChangeWindowAttributes(dpy, root, CWEventMask | CWCursor, &wa);
1463         XSelectInput(dpy, root, wa.event_mask);
1464
1465         /* grab keys */
1466         keypress(NULL);
1467
1468         /* init tags */
1469         compileregs();
1470         for(ntags = 0; tags[ntags]; ntags++);
1471         seltags = emallocz(sizeof(Bool) * ntags);
1472         seltags[0] = True;
1473
1474         /* init appearance */
1475         dc.norm[ColBorder] = getcolor(NORMBORDERCOLOR);
1476         dc.norm[ColBG] = getcolor(NORMBGCOLOR);
1477         dc.norm[ColFG] = getcolor(NORMFGCOLOR);
1478         dc.sel[ColBorder] = getcolor(SELBORDERCOLOR);
1479         dc.sel[ColBG] = getcolor(SELBGCOLOR);
1480         dc.sel[ColFG] = getcolor(SELFGCOLOR);
1481         initfont(FONT);
1482         dc.h = bh = dc.font.height + 2;
1483
1484         /* init layouts */
1485         mwfact = MWFACT;
1486         nlayouts = sizeof layouts / sizeof layouts[0];
1487         for(blw = i = 0; i < nlayouts; i++) {
1488                 j = textw(layouts[i].symbol);
1489                 if(j > blw)
1490                         blw = j;
1491         }
1492
1493         /* init bar */
1494         bpos = BARPOS;
1495         wa.override_redirect = 1;
1496         wa.background_pixmap = ParentRelative;
1497         wa.event_mask = ButtonPressMask | ExposureMask;
1498         barwin = XCreateWindow(dpy, root, sx, sy, sw, bh, 0,
1499                         DefaultDepth(dpy, screen), CopyFromParent, DefaultVisual(dpy, screen),
1500                         CWOverrideRedirect | CWBackPixmap | CWEventMask, &wa);
1501         XDefineCursor(dpy, barwin, cursor[CurNormal]);
1502         updatebarpos();
1503         XMapRaised(dpy, barwin);
1504         strcpy(stext, "dwm-"VERSION);
1505         dc.drawable = XCreatePixmap(dpy, root, sw, bh, DefaultDepth(dpy, screen));
1506         dc.gc = XCreateGC(dpy, root, 0, 0);
1507         XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
1508         if(!dc.font.set)
1509                 XSetFont(dpy, dc.gc, dc.font.xfont->fid);
1510
1511         /* multihead support */
1512         selscreen = XQueryPointer(dpy, root, &w, &w, &i, &i, &i, &i, &mask);
1513 }
1514
1515 static 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 static 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 static 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 static unsigned int
1565 textw(const char *text) {
1566         return textnw(text, strlen(text)) + dc.font.height;
1567 }
1568
1569 static void
1570 tile(void) {
1571         unsigned int i, n, nx, ny, nw, nh, mw, th;
1572         Client *c;
1573
1574         for(n = 0, c = nexttiled(clients); c; c = nexttiled(c->next))
1575                 n++;
1576
1577         /* window geoms */
1578         mw = (n == 1) ? waw : mwfact * waw;
1579         th = (n > 1) ? wah / (n - 1) : 0;
1580         if(n > 1 && th < bh)
1581                 th = wah;
1582
1583         nx = wax;
1584         ny = way;
1585         for(i = 0, c = nexttiled(clients); c; c = nexttiled(c->next), i++) {
1586                 c->ismax = False;
1587                 if(i == 0) { /* master */
1588                         nw = mw - 2 * c->border;
1589                         nh = wah - 2 * c->border;
1590                 }
1591                 else {  /* tile window */
1592                         if(i == 1) {
1593                                 ny = way;
1594                                 nx += mw;
1595                         }
1596                         nw = waw - mw - 2 * c->border;
1597                         if(i + 1 == n) /* remainder */
1598                                 nh = (way + wah) - ny - 2 * c->border;
1599                         else
1600                                 nh = th - 2 * c->border;
1601                 }
1602                 resize(c, nx, ny, nw, nh, RESIZEHINTS);
1603                 if(n > 1 && th != wah)
1604                         ny += nh + 2 * c->border;
1605         }
1606 }
1607
1608 static void
1609 togglebar(const char *arg) {
1610         if(bpos == BarOff)
1611                 bpos = (BARPOS == BarOff) ? BarTop : BARPOS;
1612         else
1613                 bpos = BarOff;
1614         updatebarpos();
1615         arrange();
1616 }
1617
1618 static void
1619 togglefloating(const char *arg) {
1620         if(!sel)
1621                 return;
1622         sel->isfloating = !sel->isfloating;
1623         if(sel->isfloating)
1624                 resize(sel, sel->x, sel->y, sel->w, sel->h, True);
1625         arrange();
1626 }
1627
1628 static void
1629 togglemax(const char *arg) {
1630         XEvent ev;
1631
1632         if(!sel || (!isarrange(floating) && !sel->isfloating) || sel->isfixed)
1633                 return;
1634         if((sel->ismax = !sel->ismax)) {
1635                 sel->rx = sel->x;
1636                 sel->ry = sel->y;
1637                 sel->rw = sel->w;
1638                 sel->rh = sel->h;
1639                 resize(sel, wax, way, waw - 2 * sel->border, wah - 2 * sel->border, True);
1640         }
1641         else
1642                 resize(sel, sel->rx, sel->ry, sel->rw, sel->rh, True);
1643         drawbar();
1644         while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1645 }
1646
1647 static void
1648 toggletag(const char *arg) {
1649         unsigned int i, j;
1650
1651         if(!sel)
1652                 return;
1653         i = idxoftag(arg);
1654         sel->tags[i] = !sel->tags[i];
1655         for(j = 0; j < ntags && !sel->tags[j]; j++);
1656         if(j == ntags)
1657                 sel->tags[i] = True;
1658         arrange();
1659 }
1660
1661 static void
1662 toggleview(const char *arg) {
1663         unsigned int i, j;
1664
1665         i = idxoftag(arg);
1666         seltags[i] = !seltags[i];
1667         for(j = 0; j < ntags && !seltags[j]; j++);
1668         if(j == ntags)
1669                 seltags[i] = True; /* cannot toggle last view */
1670         arrange();
1671 }
1672
1673 static void
1674 unban(Client *c) {
1675         if(!c->isbanned)
1676                 return;
1677         XMoveWindow(dpy, c->win, c->x, c->y);
1678         c->isbanned = False;
1679 }
1680
1681 static void
1682 unmanage(Client *c) {
1683         XWindowChanges wc;
1684
1685         wc.border_width = c->oldborder;
1686         /* The server grab construct avoids race conditions. */
1687         XGrabServer(dpy);
1688         XSetErrorHandler(xerrordummy);
1689         XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
1690         detach(c);
1691         detachstack(c);
1692         if(sel == c)
1693                 focus(NULL);
1694         XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1695         setclientstate(c, WithdrawnState);
1696         free(c->tags);
1697         free(c);
1698         XSync(dpy, False);
1699         XSetErrorHandler(xerror);
1700         XUngrabServer(dpy);
1701         arrange();
1702 }
1703
1704 static void
1705 unmapnotify(XEvent *e) {
1706         Client *c;
1707         XUnmapEvent *ev = &e->xunmap;
1708
1709         if((c = getclient(ev->window)))
1710                 unmanage(c);
1711 }
1712
1713 static void
1714 updatebarpos(void) {
1715         XEvent ev;
1716
1717         wax = sx;
1718         way = sy;
1719         wah = sh;
1720         waw = sw;
1721         switch(bpos) {
1722         default:
1723                 wah -= bh;
1724                 way += bh;
1725                 XMoveWindow(dpy, barwin, sx, sy);
1726                 break;
1727         case BarBot:
1728                 wah -= bh;
1729                 XMoveWindow(dpy, barwin, sx, sy + wah);
1730                 break;
1731         case BarOff:
1732                 XMoveWindow(dpy, barwin, sx, sy - bh);
1733                 break;
1734         }
1735         XSync(dpy, False);
1736         while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1737 }
1738
1739 static void
1740 updatesizehints(Client *c) {
1741         long msize;
1742         XSizeHints size;
1743
1744         if(!XGetWMNormalHints(dpy, c->win, &size, &msize) || !size.flags)
1745                 size.flags = PSize;
1746         c->flags = size.flags;
1747         if(c->flags & PBaseSize) {
1748                 c->basew = size.base_width;
1749                 c->baseh = size.base_height;
1750         }
1751         else if(c->flags & PMinSize) {
1752                 c->basew = size.min_width;
1753                 c->baseh = size.min_height;
1754         }
1755         else
1756                 c->basew = c->baseh = 0;
1757         if(c->flags & PResizeInc) {
1758                 c->incw = size.width_inc;
1759                 c->inch = size.height_inc;
1760         }
1761         else
1762                 c->incw = c->inch = 0;
1763         if(c->flags & PMaxSize) {
1764                 c->maxw = size.max_width;
1765                 c->maxh = size.max_height;
1766         }
1767         else
1768                 c->maxw = c->maxh = 0;
1769         if(c->flags & PMinSize) {
1770                 c->minw = size.min_width;
1771                 c->minh = size.min_height;
1772         }
1773         else if(c->flags & PBaseSize) {
1774                 c->minw = size.base_width;
1775                 c->minh = size.base_height;
1776         }
1777         else
1778                 c->minw = c->minh = 0;
1779         if(c->flags & PAspect) {
1780                 c->minax = size.min_aspect.x;
1781                 c->maxax = size.max_aspect.x;
1782                 c->minay = size.min_aspect.y;
1783                 c->maxay = size.max_aspect.y;
1784         }
1785         else
1786                 c->minax = c->maxax = c->minay = c->maxay = 0;
1787         c->isfixed = (c->maxw && c->minw && c->maxh && c->minh
1788                         && c->maxw == c->minw && c->maxh == c->minh);
1789 }
1790
1791 static void
1792 updatetitle(Client *c) {
1793         if(!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
1794                 gettextprop(c->win, wmatom[WMName], c->name, sizeof c->name);
1795 }
1796
1797 /* There's no way to check accesses to destroyed windows, thus those cases are
1798  * ignored (especially on UnmapNotify's).  Other types of errors call Xlibs
1799  * default error handler, which may call exit.  */
1800 static int
1801 xerror(Display *dpy, XErrorEvent *ee) {
1802         if(ee->error_code == BadWindow
1803         || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1804         || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1805         || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1806         || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1807         || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1808         || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1809         || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1810                 return 0;
1811         fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1812                 ee->request_code, ee->error_code);
1813         return xerrorxlib(dpy, ee); /* may call exit */
1814 }
1815
1816 static int
1817 xerrordummy(Display *dsply, XErrorEvent *ee) {
1818         return 0;
1819 }
1820
1821 /* Startup Error handler to check if another window manager
1822  * is already running. */
1823 static int
1824 xerrorstart(Display *dsply, XErrorEvent *ee) {
1825         otherwm = True;
1826         return -1;
1827 }
1828
1829 static void
1830 view(const char *arg) {
1831         unsigned int i;
1832
1833         for(i = 0; i < ntags; i++)
1834                 seltags[i] = arg == NULL;
1835         i = idxoftag(arg);
1836         if(i >= 0 && i < ntags)
1837                 seltags[i] = True;
1838         arrange();
1839 }
1840
1841 static void
1842 zoom(const char *arg) {
1843         Client *c;
1844
1845         if(!sel || !isarrange(tile) || sel->isfloating)
1846                 return;
1847         if((c = sel) == nexttiled(clients))
1848                 if(!(c = nexttiled(c->next)))
1849                         return;
1850         detach(c);
1851         attach(c);
1852         focus(c);
1853         arrange();
1854 }
1855
1856 int
1857 main(int argc, char *argv[]) {
1858         if(argc == 2 && !strcmp("-v", argv[1]))
1859                 eprint("dwm-"VERSION", © 2006-2007 A. R. Garbe, S. van Dijk, J. Salmi, P. Hruby, S. Nagy\n");
1860         else if(argc != 1)
1861                 eprint("usage: dwm [-v]\n");
1862
1863         setlocale(LC_CTYPE, "");
1864         if(!(dpy = XOpenDisplay(0)))
1865                 eprint("dwm: cannot open display\n");
1866         screen = DefaultScreen(dpy);
1867         root = RootWindow(dpy, screen);
1868
1869         checkotherwm();
1870         setup();
1871         drawbar();
1872         scan();
1873         run();
1874         cleanup();
1875
1876         XCloseDisplay(dpy);
1877         return 0;
1878 }