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