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