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