Xinqi Bao's Git

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