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