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