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