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