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