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