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