Xinqi Bao's Git

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