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