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