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