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