Xinqi Bao's Git

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