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