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