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