Xinqi Bao's Git

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