Xinqi Bao's Git

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