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