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