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