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