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