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