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