Xinqi Bao's Git

fixed getclient brokeness
[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) {
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 if((dc.w = dc.x - x) > bh) {
656 dc.x = x;
657 if(selmon->sel) {
658 drawtext(selmon->sel->name, dc.sel, False);
659 drawsquare(selmon->sel->isfixed, selmon->sel->isfloating, False, dc.sel);
660 }
661 else
662 drawtext(NULL, dc.norm, False);
663 }
664 }
665 else {
666 dc.x = x;
667 dc.w = m->ww - x;
668 drawtext(NULL, dc.norm, False);
669 }
670 XCopyArea(dpy, dc.drawable, m->barwin, dc.gc, 0, 0, m->ww, bh, 0, 0);
671 XSync(dpy, False);
672 }
673
674 void
675 drawbars() {
676 Monitor *m;
677
678 for(m = mons; m; m = m->next)
679 drawbar(m);
680 }
681
682 void
683 drawsquare(Bool filled, Bool empty, Bool invert, unsigned long col[ColLast]) {
684 int x;
685 XGCValues gcv;
686 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
687
688 gcv.foreground = col[invert ? ColBG : ColFG];
689 XChangeGC(dpy, dc.gc, GCForeground, &gcv);
690 x = (dc.font.ascent + dc.font.descent + 2) / 4;
691 r.x = dc.x + 1;
692 r.y = dc.y + 1;
693 if(filled) {
694 r.width = r.height = x + 1;
695 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
696 }
697 else if(empty) {
698 r.width = r.height = x;
699 XDrawRectangles(dpy, dc.drawable, dc.gc, &r, 1);
700 }
701 }
702
703 void
704 drawtext(const char *text, unsigned long col[ColLast], Bool invert) {
705 char buf[256];
706 int i, x, y, h, len, olen;
707 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
708
709 XSetForeground(dpy, dc.gc, col[invert ? ColFG : ColBG]);
710 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
711 if(!text)
712 return;
713 olen = strlen(text);
714 h = dc.font.ascent + dc.font.descent;
715 y = dc.y + (dc.h / 2) - (h / 2) + dc.font.ascent;
716 x = dc.x + (h / 2);
717 /* shorten text if necessary */
718 for(len = MIN(olen, sizeof buf); len && textnw(text, len) > dc.w - h; len--);
719 if(!len)
720 return;
721 memcpy(buf, text, len);
722 if(len < olen)
723 for(i = len; i && i > len - 3; buf[--i] = '.');
724 XSetForeground(dpy, dc.gc, col[invert ? ColBG : ColFG]);
725 if(dc.font.set)
726 XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
727 else
728 XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
729 }
730
731 void
732 enternotify(XEvent *e) {
733 Client *c;
734 XCrossingEvent *ev = &e->xcrossing;
735
736 if((ev->mode != NotifyNormal || ev->detail == NotifyInferior) && ev->window != root)
737 return;
738 if((c = getclient(ev->window)))
739 focus(c);
740 else
741 focus(NULL);
742 }
743
744 void
745 expose(XEvent *e) {
746 Monitor *m;
747 XExposeEvent *ev = &e->xexpose;
748
749 if(ev->count == 0)
750 for(m = mons; m; m = m->next)
751 if(ev->window == m->barwin) {
752 drawbar(m);
753 break;
754 }
755 }
756
757 void
758 focus(Client *c) {
759 if(!c || !ISVISIBLE(c))
760 for(c = selmon->stack; c && !ISVISIBLE(c); c = c->snext);
761 if(selmon->sel && selmon->sel != c) {
762 grabbuttons(selmon->sel, False);
763 XSetWindowBorder(dpy, selmon->sel->win, dc.norm[ColBorder]);
764 }
765 if(c) {
766 if(c->isurgent)
767 clearurgent(c);
768 detachstack(c);
769 attachstack(c);
770 grabbuttons(c, True);
771 XSetWindowBorder(dpy, c->win, dc.sel[ColBorder]);
772 XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
773 }
774 else
775 XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
776 selmon->sel = c;
777 drawbars();
778 }
779
780 void
781 focusin(XEvent *e) { /* there are some broken focus acquiring clients */
782 XFocusChangeEvent *ev = &e->xfocus;
783
784 if(selmon->sel && ev->window != selmon->sel->win)
785 XSetInputFocus(dpy, selmon->sel->win, RevertToPointerRoot, CurrentTime);
786 }
787
788 #ifdef XINERAMA
789 void
790 focusmon(const Arg *arg) {
791 unsigned int i;
792 Monitor *m;
793
794 for(i = 0, m = mons; m; m = m->next, i++)
795 if(i == arg->ui) {
796 selmon = m;
797 focus(NULL);
798 drawbars();
799 break;
800 }
801 }
802 #endif /* XINERAMA */
803
804 void
805 focusstack(const Arg *arg) {
806 Client *c = NULL, *i;
807
808 if(!selmon->sel)
809 return;
810 if(arg->i > 0) {
811 for(c = selmon->sel->next; c && !ISVISIBLE(c); c = c->next);
812 if(!c)
813 for(c = selmon->clients; c && !ISVISIBLE(c); c = c->next);
814 }
815 else {
816 for(i = selmon->clients; i != selmon->sel; i = i->next)
817 if(ISVISIBLE(i))
818 c = i;
819 if(!c)
820 for(; i; i = i->next)
821 if(ISVISIBLE(i))
822 c = i;
823 }
824 if(c) {
825 focus(c);
826 restack(selmon);
827 }
828 }
829
830 Client *
831 getclient(Window w) {
832 Client *c;
833 Monitor *m;
834
835 for(m = mons; m; m = m->next)
836 for(c = m->clients; c; c = c->next)
837 if(c->win == w)
838 return c;
839 return NULL;
840 }
841
842 unsigned long
843 getcolor(const char *colstr) {
844 Colormap cmap = DefaultColormap(dpy, screen);
845 XColor color;
846
847 if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
848 die("error, cannot allocate color '%s'\n", colstr);
849 return color.pixel;
850 }
851
852 long
853 getstate(Window w) {
854 int format, status;
855 long result = -1;
856 unsigned char *p = NULL;
857 unsigned long n, extra;
858 Atom real;
859
860 status = XGetWindowProperty(dpy, w, wmatom[WMState], 0L, 2L, False, wmatom[WMState],
861 &real, &format, &n, &extra, (unsigned char **)&p);
862 if(status != Success)
863 return -1;
864 if(n != 0)
865 result = *p;
866 XFree(p);
867 return result;
868 }
869
870 Bool
871 gettextprop(Window w, Atom atom, char *text, unsigned int size) {
872 char **list = NULL;
873 int n;
874 XTextProperty name;
875
876 if(!text || size == 0)
877 return False;
878 text[0] = '\0';
879 XGetTextProperty(dpy, w, &name, atom);
880 if(!name.nitems)
881 return False;
882 if(name.encoding == XA_STRING)
883 strncpy(text, (char *)name.value, size - 1);
884 else {
885 if(XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success
886 && n > 0 && *list) {
887 strncpy(text, *list, size - 1);
888 XFreeStringList(list);
889 }
890 }
891 text[size - 1] = '\0';
892 XFree(name.value);
893 return True;
894 }
895
896 void
897 grabbuttons(Client *c, Bool focused) {
898 updatenumlockmask();
899 {
900 unsigned int i, j;
901 unsigned int modifiers[] = { 0, LockMask, numlockmask, numlockmask|LockMask };
902 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
903 if(focused) {
904 for(i = 0; i < LENGTH(buttons); i++)
905 if(buttons[i].click == ClkClientWin)
906 for(j = 0; j < LENGTH(modifiers); j++)
907 XGrabButton(dpy, buttons[i].button,
908 buttons[i].mask | modifiers[j],
909 c->win, False, BUTTONMASK,
910 GrabModeAsync, GrabModeSync, None, None);
911 } else
912 XGrabButton(dpy, AnyButton, AnyModifier, c->win, False,
913 BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
914 }
915 }
916
917 void
918 grabkeys(void) {
919 updatenumlockmask();
920 { /* grab keys */
921 unsigned int i, j;
922 unsigned int modifiers[] = { 0, LockMask, numlockmask, numlockmask|LockMask };
923 KeyCode code;
924
925 XUngrabKey(dpy, AnyKey, AnyModifier, root);
926 for(i = 0; i < LENGTH(keys); i++) {
927 if((code = XKeysymToKeycode(dpy, keys[i].keysym)))
928 for(j = 0; j < LENGTH(modifiers); j++)
929 XGrabKey(dpy, code, keys[i].mod | modifiers[j], root,
930 True, GrabModeAsync, GrabModeAsync);
931 }
932 }
933 }
934
935 void
936 initfont(const char *fontstr) {
937 char *def, **missing;
938 int i, n;
939
940 missing = NULL;
941 dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
942 if(missing) {
943 while(n--)
944 fprintf(stderr, "dwm: missing fontset: %s\n", missing[n]);
945 XFreeStringList(missing);
946 }
947 if(dc.font.set) {
948 XFontSetExtents *font_extents;
949 XFontStruct **xfonts;
950 char **font_names;
951 dc.font.ascent = dc.font.descent = 0;
952 font_extents = XExtentsOfFontSet(dc.font.set);
953 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
954 for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
955 dc.font.ascent = MAX(dc.font.ascent, (*xfonts)->ascent);
956 dc.font.descent = MAX(dc.font.descent,(*xfonts)->descent);
957 xfonts++;
958 }
959 }
960 else {
961 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr))
962 && !(dc.font.xfont = XLoadQueryFont(dpy, "fixed")))
963 die("error, cannot load font: '%s'\n", fontstr);
964 dc.font.ascent = dc.font.xfont->ascent;
965 dc.font.descent = dc.font.xfont->descent;
966 }
967 dc.font.height = dc.font.ascent + dc.font.descent;
968 }
969
970 Bool
971 isprotodel(Client *c) {
972 int i, n;
973 Atom *protocols;
974 Bool ret = False;
975
976 if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
977 for(i = 0; !ret && i < n; i++)
978 if(protocols[i] == wmatom[WMDelete])
979 ret = True;
980 XFree(protocols);
981 }
982 return ret;
983 }
984
985 void
986 keypress(XEvent *e) {
987 unsigned int i;
988 KeySym keysym;
989 XKeyEvent *ev;
990
991 ev = &e->xkey;
992 keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
993 for(i = 0; i < LENGTH(keys); i++)
994 if(keysym == keys[i].keysym
995 && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state)
996 && keys[i].func)
997 keys[i].func(&(keys[i].arg));
998 }
999
1000 void
1001 killclient(const Arg *arg) {
1002 XEvent ev;
1003
1004 if(!selmon->sel)
1005 return;
1006 if(isprotodel(selmon->sel)) {
1007 ev.type = ClientMessage;
1008 ev.xclient.window = selmon->sel->win;
1009 ev.xclient.message_type = wmatom[WMProtocols];
1010 ev.xclient.format = 32;
1011 ev.xclient.data.l[0] = wmatom[WMDelete];
1012 ev.xclient.data.l[1] = CurrentTime;
1013 XSendEvent(dpy, selmon->sel->win, False, NoEventMask, &ev);
1014 }
1015 else
1016 XKillClient(dpy, selmon->sel->win);
1017 }
1018
1019 void
1020 manage(Window w, XWindowAttributes *wa) {
1021 static Client cz;
1022 Client *c, *t = NULL;
1023 Window trans = None;
1024 XWindowChanges wc;
1025
1026 if(!(c = malloc(sizeof(Client))))
1027 die("fatal: could not malloc() %u bytes\n", sizeof(Client));
1028 *c = cz;
1029 c->win = w;
1030 c->mon = selmon;
1031
1032 /* geometry */
1033 c->x = wa->x;
1034 c->y = wa->y;
1035 c->w = wa->width;
1036 c->h = wa->height;
1037 c->oldbw = wa->border_width;
1038 if(c->w == sw && c->h == sh) {
1039 c->x = sx;
1040 c->y = sy;
1041 c->bw = 0;
1042 }
1043 else {
1044 if(c->x + WIDTH(c) > sx + sw)
1045 c->x = sx + sw - WIDTH(c);
1046 if(c->y + HEIGHT(c) > sy + sh)
1047 c->y = sy + sh - HEIGHT(c);
1048 c->x = MAX(c->x, sx);
1049 /* only fix client y-offset, if the client center might cover the bar */
1050 c->y = MAX(c->y, ((c->mon->by == 0) && (c->x + (c->w / 2) >= c->mon->wx)
1051 && (c->x + (c->w / 2) < c->mon->wx + c->mon->ww)) ? bh : sy);
1052 c->bw = borderpx;
1053 }
1054
1055 wc.border_width = c->bw;
1056 XConfigureWindow(dpy, w, CWBorderWidth, &wc);
1057 XSetWindowBorder(dpy, w, dc.norm[ColBorder]);
1058 configure(c); /* propagates border_width, if size doesn't change */
1059 updatesizehints(c);
1060 XSelectInput(dpy, w, EnterWindowMask|FocusChangeMask|PropertyChangeMask|StructureNotifyMask);
1061 grabbuttons(c, False);
1062 updatetitle(c);
1063 if(XGetTransientForHint(dpy, w, &trans))
1064 t = getclient(trans);
1065 if(t)
1066 c->tags = t->tags;
1067 else
1068 applyrules(c);
1069 if(!c->isfloating)
1070 c->isfloating = trans != None || c->isfixed;
1071 if(c->isfloating)
1072 XRaiseWindow(dpy, c->win);
1073 attach(c);
1074 attachstack(c);
1075 XMoveResizeWindow(dpy, c->win, c->x + 2 * sw, c->y, c->w, c->h); /* some windows require this */
1076 XMapWindow(dpy, c->win);
1077 setclientstate(c, NormalState);
1078 arrange();
1079 }
1080
1081 void
1082 mappingnotify(XEvent *e) {
1083 XMappingEvent *ev = &e->xmapping;
1084
1085 XRefreshKeyboardMapping(ev);
1086 if(ev->request == MappingKeyboard)
1087 grabkeys();
1088 }
1089
1090 void
1091 maprequest(XEvent *e) {
1092 static XWindowAttributes wa;
1093 XMapRequestEvent *ev = &e->xmaprequest;
1094
1095 if(!XGetWindowAttributes(dpy, ev->window, &wa))
1096 return;
1097 if(wa.override_redirect)
1098 return;
1099 if(!getclient(ev->window))
1100 manage(ev->window, &wa);
1101 }
1102
1103 void
1104 monocle(Monitor *m) {
1105 Client *c;
1106
1107 for(c = nexttiled(m->clients); c; c = nexttiled(c->next))
1108 resize(c, m->wx, m->wy, m->ww - 2 * c->bw, m->wh - 2 * c->bw);
1109 }
1110
1111 void
1112 movemouse(const Arg *arg) {
1113 int x, y, ocx, ocy, di, nx, ny;
1114 unsigned int dui;
1115 Client *c;
1116 Window dummy;
1117 XEvent ev;
1118
1119 if(!(c = selmon->sel))
1120 return;
1121 restack(selmon);
1122 ocx = c->x;
1123 ocy = c->y;
1124 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1125 None, cursor[CurMove], CurrentTime) != GrabSuccess)
1126 return;
1127 XQueryPointer(dpy, root, &dummy, &dummy, &x, &y, &di, &di, &dui);
1128 do {
1129 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
1130 switch (ev.type) {
1131 case ConfigureRequest:
1132 case Expose:
1133 case MapRequest:
1134 handler[ev.type](&ev);
1135 break;
1136 case MotionNotify:
1137 nx = ocx + (ev.xmotion.x - x);
1138 ny = ocy + (ev.xmotion.y - y);
1139 if(snap && nx >= selmon->wx && nx <= selmon->wx + selmon->ww
1140 && ny >= selmon->wy && ny <= selmon->wy + selmon->wh) {
1141 if(abs(selmon->wx - nx) < snap)
1142 nx = selmon->wx;
1143 else if(abs((selmon->wx + selmon->ww) - (nx + WIDTH(c))) < snap)
1144 nx = selmon->wx + selmon->ww - WIDTH(c);
1145 if(abs(selmon->wy - ny) < snap)
1146 ny = selmon->wy;
1147 else if(abs((selmon->wy + selmon->wh) - (ny + HEIGHT(c))) < snap)
1148 ny = selmon->wy + selmon->wh - HEIGHT(c);
1149 if(!c->isfloating && lt[selmon->sellt]->arrange
1150 && (abs(nx - c->x) > snap || abs(ny - c->y) > snap))
1151 togglefloating(NULL);
1152 }
1153 if(!lt[selmon->sellt]->arrange || c->isfloating)
1154 resize(c, nx, ny, c->w, c->h);
1155 break;
1156 }
1157 }
1158 while(ev.type != ButtonRelease);
1159 XUngrabPointer(dpy, CurrentTime);
1160 }
1161
1162 Client *
1163 nexttiled(Client *c) {
1164 for(; c && (c->isfloating || !ISVISIBLE(c)); c = c->next);
1165 return c;
1166 }
1167
1168 void
1169 propertynotify(XEvent *e) {
1170 Client *c;
1171 Window trans;
1172 XPropertyEvent *ev = &e->xproperty;
1173
1174 if((ev->window == root) && (ev->atom == XA_WM_NAME))
1175 updatestatus();
1176 else if(ev->state == PropertyDelete)
1177 return; /* ignore */
1178 else if((c = getclient(ev->window))) {
1179 switch (ev->atom) {
1180 default: break;
1181 case XA_WM_TRANSIENT_FOR:
1182 XGetTransientForHint(dpy, c->win, &trans);
1183 if(!c->isfloating && (c->isfloating = (getclient(trans) != NULL)))
1184 arrange();
1185 break;
1186 case XA_WM_NORMAL_HINTS:
1187 updatesizehints(c);
1188 break;
1189 case XA_WM_HINTS:
1190 updatewmhints(c);
1191 drawbars();
1192 break;
1193 }
1194 if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
1195 updatetitle(c);
1196 if(c == selmon->sel)
1197 drawbars();
1198 }
1199 }
1200 }
1201
1202 void
1203 quit(const Arg *arg) {
1204 running = False;
1205 }
1206
1207 void
1208 resize(Client *c, int x, int y, int w, int h) {
1209 XWindowChanges wc;
1210
1211 if(applysizehints(c, &x, &y, &w, &h)) {
1212 c->x = wc.x = x;
1213 c->y = wc.y = y;
1214 c->w = wc.width = w;
1215 c->h = wc.height = h;
1216 wc.border_width = c->bw;
1217 XConfigureWindow(dpy, c->win,
1218 CWX|CWY|CWWidth|CWHeight|CWBorderWidth, &wc);
1219 configure(c);
1220 XSync(dpy, False);
1221 }
1222 }
1223
1224 void
1225 resizemouse(const Arg *arg) {
1226 int ocx, ocy;
1227 int nw, nh;
1228 Client *c;
1229 XEvent ev;
1230
1231 if(!(c = selmon->sel))
1232 return;
1233 restack(selmon);
1234 ocx = c->x;
1235 ocy = c->y;
1236 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1237 None, cursor[CurResize], CurrentTime) != GrabSuccess)
1238 return;
1239 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->bw - 1, c->h + c->bw - 1);
1240 do {
1241 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
1242 switch(ev.type) {
1243 case ConfigureRequest:
1244 case Expose:
1245 case MapRequest:
1246 handler[ev.type](&ev);
1247 break;
1248 case MotionNotify:
1249 nw = MAX(ev.xmotion.x - ocx - 2 * c->bw + 1, 1);
1250 nh = MAX(ev.xmotion.y - ocy - 2 * c->bw + 1, 1);
1251
1252 if(snap && nw >= selmon->wx && nw <= selmon->wx + selmon->ww
1253 && nh >= selmon->wy && nh <= selmon->wy + selmon->wh) {
1254 if(!c->isfloating && lt[selmon->sellt]->arrange
1255 && (abs(nw - c->w) > snap || abs(nh - c->h) > snap))
1256 togglefloating(NULL);
1257 }
1258 if(!lt[selmon->sellt]->arrange || c->isfloating)
1259 resize(c, c->x, c->y, nw, nh);
1260 break;
1261 }
1262 }
1263 while(ev.type != ButtonRelease);
1264 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->bw - 1, c->h + c->bw - 1);
1265 XUngrabPointer(dpy, CurrentTime);
1266 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1267 }
1268
1269 void
1270 restack(Monitor *m) {
1271 Client *c;
1272 XEvent ev;
1273 XWindowChanges wc;
1274
1275 drawbars();
1276 if(!m->sel)
1277 return;
1278 if(m->sel->isfloating || !lt[m->sellt]->arrange)
1279 XRaiseWindow(dpy, m->sel->win);
1280 if(lt[m->sellt]->arrange) {
1281 wc.stack_mode = Below;
1282 wc.sibling = m->barwin;
1283 for(c = m->stack; c; c = c->snext)
1284 if(!c->isfloating && ISVISIBLE(c)) {
1285 XConfigureWindow(dpy, c->win, CWSibling|CWStackMode, &wc);
1286 wc.sibling = c->win;
1287 }
1288 }
1289 XSync(dpy, False);
1290 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1291 }
1292
1293 void
1294 run(void) {
1295 XEvent ev;
1296
1297 /* main event loop */
1298 XSync(dpy, False);
1299 while(running && !XNextEvent(dpy, &ev)) {
1300 if(handler[ev.type])
1301 (handler[ev.type])(&ev); /* call handler */
1302 }
1303 }
1304
1305 void
1306 scan(void) {
1307 unsigned int i, num;
1308 Window d1, d2, *wins = NULL;
1309 XWindowAttributes wa;
1310
1311 if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1312 for(i = 0; i < num; i++) {
1313 if(!XGetWindowAttributes(dpy, wins[i], &wa)
1314 || wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1315 continue;
1316 if(wa.map_state == IsViewable || getstate(wins[i]) == IconicState)
1317 manage(wins[i], &wa);
1318 }
1319 for(i = 0; i < num; i++) { /* now the transients */
1320 if(!XGetWindowAttributes(dpy, wins[i], &wa))
1321 continue;
1322 if(XGetTransientForHint(dpy, wins[i], &d1)
1323 && (wa.map_state == IsViewable || getstate(wins[i]) == IconicState))
1324 manage(wins[i], &wa);
1325 }
1326 if(wins)
1327 XFree(wins);
1328 }
1329 }
1330
1331 void
1332 setclientstate(Client *c, long state) {
1333 long data[] = {state, None};
1334
1335 XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1336 PropModeReplace, (unsigned char *)data, 2);
1337 }
1338
1339 void
1340 setlayout(const Arg *arg) {
1341 if(!arg || !arg->v || arg->v != lt[selmon->sellt])
1342 selmon->sellt ^= 1;
1343 if(arg && arg->v)
1344 lt[selmon->sellt] = (Layout *)arg->v;
1345 if(selmon->sel)
1346 arrange();
1347 else
1348 drawbars();
1349 }
1350
1351 /* arg > 1.0 will set mfact absolutly */
1352 void
1353 setmfact(const Arg *arg) {
1354 float f;
1355
1356 if(!arg || !lt[selmon->sellt]->arrange)
1357 return;
1358 f = arg->f < 1.0 ? arg->f + selmon->mfact : arg->f - 1.0;
1359 if(f < 0.1 || f > 0.9)
1360 return;
1361 selmon->mfact = f;
1362 arrange();
1363 }
1364
1365 void
1366 setup(void) {
1367 unsigned int i;
1368 int w;
1369 XSetWindowAttributes wa;
1370
1371 /* init screen */
1372 screen = DefaultScreen(dpy);
1373 root = RootWindow(dpy, screen);
1374 initfont(font);
1375 sx = 0;
1376 sy = 0;
1377 sw = DisplayWidth(dpy, screen);
1378 sh = DisplayHeight(dpy, screen);
1379 bh = dc.h = dc.font.height + 2;
1380 lt[0] = &layouts[0];
1381 lt[1] = &layouts[1 % LENGTH(layouts)];
1382 updategeom();
1383
1384 /* init atoms */
1385 wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1386 wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1387 wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1388 netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1389 netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1390
1391 /* init cursors */
1392 cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1393 cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1394 cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1395
1396 /* init appearance */
1397 dc.norm[ColBorder] = getcolor(normbordercolor);
1398 dc.norm[ColBG] = getcolor(normbgcolor);
1399 dc.norm[ColFG] = getcolor(normfgcolor);
1400 dc.sel[ColBorder] = getcolor(selbordercolor);
1401 dc.sel[ColBG] = getcolor(selbgcolor);
1402 dc.sel[ColFG] = getcolor(selfgcolor);
1403 dc.drawable = XCreatePixmap(dpy, root, DisplayWidth(dpy, screen), bh, DefaultDepth(dpy, screen));
1404 dc.gc = XCreateGC(dpy, root, 0, NULL);
1405 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
1406 if(!dc.font.set)
1407 XSetFont(dpy, dc.gc, dc.font.xfont->fid);
1408
1409 /* init bars */
1410 for(blw = i = 0; LENGTH(layouts) > 1 && i < LENGTH(layouts); i++) {
1411 w = TEXTW(layouts[i].symbol);
1412 blw = MAX(blw, w);
1413 }
1414 updatebars();
1415 updatestatus();
1416
1417 /* EWMH support per view */
1418 XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1419 PropModeReplace, (unsigned char *) netatom, NetLast);
1420
1421 /* select for events */
1422 wa.cursor = cursor[CurNormal];
1423 wa.event_mask = SubstructureRedirectMask|SubstructureNotifyMask|ButtonPressMask
1424 |EnterWindowMask|LeaveWindowMask|StructureNotifyMask
1425 |PropertyChangeMask;
1426 XChangeWindowAttributes(dpy, root, CWEventMask|CWCursor, &wa);
1427 XSelectInput(dpy, root, wa.event_mask);
1428
1429 grabkeys();
1430 }
1431
1432 void
1433 showhide(Client *c) {
1434 if(!c)
1435 return;
1436 if(ISVISIBLE(c)) { /* show clients top down */
1437 XMoveWindow(dpy, c->win, c->x, c->y);
1438 if(!lt[c->mon->sellt]->arrange || c->isfloating)
1439 resize(c, c->x, c->y, c->w, c->h);
1440 showhide(c->snext);
1441 }
1442 else { /* hide clients bottom up */
1443 showhide(c->snext);
1444 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
1445 }
1446 }
1447
1448
1449 void
1450 sigchld(int signal) {
1451 while(0 < waitpid(-1, NULL, WNOHANG));
1452 }
1453
1454 void
1455 spawn(const Arg *arg) {
1456 signal(SIGCHLD, sigchld);
1457 if(fork() == 0) {
1458 if(dpy)
1459 close(ConnectionNumber(dpy));
1460 setsid();
1461 execvp(((char **)arg->v)[0], (char **)arg->v);
1462 fprintf(stderr, "dwm: execvp %s", ((char **)arg->v)[0]);
1463 perror(" failed");
1464 exit(0);
1465 }
1466 }
1467
1468 void
1469 tag(const Arg *arg) {
1470 if(selmon->sel && arg->ui & TAGMASK) {
1471 selmon->sel->tags = arg->ui & TAGMASK;
1472 arrange();
1473 }
1474 }
1475
1476 #ifdef XINERAMA
1477 void
1478 tagmon(const Arg *arg) {
1479 unsigned int i;
1480 Client *c;
1481 Monitor *m;
1482
1483 if(!(c = selmon->sel))
1484 return;
1485 for(i = 0, m = mons; m; m = m->next, i++)
1486 if(i == arg->ui) {
1487 detach(c);
1488 detachstack(c);
1489 c->mon = m;
1490 attach(c);
1491 attachstack(c);
1492 selmon->sel = selmon->stack;
1493 m->sel = c;
1494 arrange();
1495 break;
1496 }
1497 }
1498 #endif /* XINERAMA */
1499
1500 int
1501 textnw(const char *text, unsigned int len) {
1502 XRectangle r;
1503
1504 if(dc.font.set) {
1505 XmbTextExtents(dc.font.set, text, len, NULL, &r);
1506 return r.width;
1507 }
1508 return XTextWidth(dc.font.xfont, text, len);
1509 }
1510
1511 void
1512 tile(Monitor *m) {
1513 int x, y, h, w, mw;
1514 unsigned int i, n;
1515 Client *c;
1516
1517 for(n = 0, c = nexttiled(m->clients); c; c = nexttiled(c->next), n++);
1518 if(n == 0)
1519 return;
1520
1521 /* master */
1522 c = nexttiled(m->clients);
1523 mw = m->mfact * m->ww;
1524 resize(c, m->wx, m->wy, (n == 1 ? m->ww : mw) - 2 * c->bw, m->wh - 2 * c->bw);
1525
1526 if(--n == 0)
1527 return;
1528
1529 /* tile stack */
1530 x = (m->wx + mw > c->x + c->w) ? c->x + c->w + 2 * c->bw : m->wx + mw;
1531 y = m->wy;
1532 w = (m->wx + mw > c->x + c->w) ? m->wx + m->ww - x : m->ww - mw;
1533 h = m->wh / n;
1534 if(h < bh)
1535 h = m->wh;
1536
1537 for(i = 0, c = nexttiled(c->next); c; c = nexttiled(c->next), i++) {
1538 resize(c, x, y, w - 2 * c->bw, /* remainder */ ((i + 1 == n)
1539 ? m->wy + m->wh - y - 2 * c->bw : h - 2 * c->bw));
1540 if(h != m->wh)
1541 y = c->y + HEIGHT(c);
1542 }
1543 }
1544
1545 void
1546 togglebar(const Arg *arg) {
1547 selmon->showbar = !selmon->showbar;
1548 updatebarpos(selmon);
1549 XMoveResizeWindow(dpy, selmon->barwin, selmon->wx, selmon->by, selmon->ww, bh);
1550 arrange();
1551 }
1552
1553 void
1554 togglefloating(const Arg *arg) {
1555 if(!selmon->sel)
1556 return;
1557 selmon->sel->isfloating = !selmon->sel->isfloating || selmon->sel->isfixed;
1558 if(selmon->sel->isfloating)
1559 resize(selmon->sel, selmon->sel->x, selmon->sel->y, selmon->sel->w, selmon->sel->h);
1560 arrange();
1561 }
1562
1563 void
1564 toggletag(const Arg *arg) {
1565 unsigned int mask;
1566
1567 if(!selmon->sel)
1568 return;
1569
1570 mask = selmon->sel->tags ^ (arg->ui & TAGMASK);
1571 if(mask) {
1572 selmon->sel->tags = mask;
1573 arrange();
1574 }
1575 }
1576
1577 void
1578 toggleview(const Arg *arg) {
1579 unsigned int mask = selmon->tagset[selmon->seltags] ^ (arg->ui & TAGMASK);
1580
1581 if(mask) {
1582 selmon->tagset[selmon->seltags] = mask;
1583 arrange();
1584 }
1585 }
1586
1587 void
1588 unmanage(Client *c) {
1589 XWindowChanges wc;
1590
1591 wc.border_width = c->oldbw;
1592 /* The server grab construct avoids race conditions. */
1593 XGrabServer(dpy);
1594 XSetErrorHandler(xerrordummy);
1595 XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
1596 detach(c);
1597 detachstack(c);
1598 if(c->mon->sel == c) {
1599 c->mon->sel = c->mon->stack;
1600 focus(NULL);
1601 }
1602 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1603 setclientstate(c, WithdrawnState);
1604 free(c);
1605 XSync(dpy, False);
1606 XSetErrorHandler(xerror);
1607 XUngrabServer(dpy);
1608 arrange();
1609 }
1610
1611 void
1612 unmapnotify(XEvent *e) {
1613 Client *c;
1614 XUnmapEvent *ev = &e->xunmap;
1615
1616 if((c = getclient(ev->window)))
1617 unmanage(c);
1618 }
1619
1620 void
1621 updatebars(void) {
1622 Monitor *m;
1623 XSetWindowAttributes wa;
1624
1625 wa.override_redirect = True;
1626 wa.background_pixmap = ParentRelative;
1627 wa.event_mask = ButtonPressMask|ExposureMask;
1628
1629 for(m = mons; m; m = m->next) {
1630 m->barwin = XCreateWindow(dpy, root, m->wx, m->by, m->ww, bh, 0, DefaultDepth(dpy, screen),
1631
1632 CopyFromParent, DefaultVisual(dpy, screen),
1633 CWOverrideRedirect|CWBackPixmap|CWEventMask, &wa);
1634 XDefineCursor(dpy, m->barwin, cursor[CurNormal]);
1635 XMapRaised(dpy, m->barwin);
1636 }
1637 }
1638
1639 void
1640 updatebarpos(Monitor *m) {
1641 m->wy = m->my;
1642 m->wh = m->mh;
1643 if(m->showbar) {
1644 m->wh -= bh;
1645 m->by = m->topbar ? m->wy : m->wy + m->wh;
1646 m->wy = m->topbar ? m->wy + bh : m->wy;
1647 }
1648 else
1649 m->by = -bh;
1650 }
1651
1652 void
1653 updategeom(void) {
1654 int i, di, n = 1, x, y;
1655 unsigned int dui;
1656 Client *c;
1657 Monitor *newmons = NULL, *m, *tm;
1658 Window dummy;
1659
1660 #ifdef XINULATOR
1661 n = 2;
1662 #elif defined(XINERAMA)
1663 XineramaScreenInfo *info = NULL;
1664
1665 if(XineramaIsActive(dpy))
1666 info = XineramaQueryScreens(dpy, &n);
1667 #endif
1668 /* allocate monitor(s) for the new geometry setup */
1669 for(i = 0; i < n; i++) {
1670 m = (Monitor *)malloc(sizeof(Monitor));
1671 m->next = newmons;
1672 newmons = m;
1673 }
1674
1675 /* initialise monitor(s) */
1676 #ifdef XINULATOR
1677 if(1) {
1678 m = newmons;
1679 m->screen_number = 0;
1680 m->wx = sx;
1681 m->my = m->wy = sy;
1682 m->ww = sw;
1683 m->mh = m->wh = sh / 2;
1684 m = newmons->next;
1685 m->screen_number = 1;
1686 m->wx = sx;
1687 m->my = m->wy = sy + sh / 2;
1688 m->ww = sw;
1689 m->mh = m->wh = sh / 2;
1690 }
1691 else
1692 #elif defined(XINERAMA)
1693 if(XineramaIsActive(dpy)) {
1694 for(i = 0, m = newmons; m; m = m->next, i++) {
1695 m->screen_number = info[i].screen_number;
1696 m->wx = info[i].x_org;
1697 m->my = m->wy = info[i].y_org;
1698 m->ww = info[i].width;
1699 m->mh = m->wh = info[i].height;
1700 }
1701 XFree(info);
1702 }
1703 else
1704 #endif
1705 /* default monitor setup */
1706 {
1707 m->screen_number = 0;
1708 m->wx = sx;
1709 m->my = m->wy = sy;
1710 m->ww = sw;
1711 m->mh = m->wh = sh;
1712 }
1713
1714 /* bar geometry setup */
1715 for(m = newmons; m; m = m->next) {
1716 /* TODO: consider removing the following values from config.h */
1717 m->clients = NULL;
1718 m->sel = NULL;
1719 m->stack = NULL;
1720 m->seltags = 0;
1721 m->sellt = 0;
1722 m->tagset[0] = m->tagset[1] = 1;
1723 m->mfact = mfact;
1724 m->showbar = showbar;
1725 m->topbar = topbar;
1726 updatebarpos(m);
1727 }
1728
1729 /* reassign left over clients of disappeared monitors */
1730 for(tm = mons; tm; tm = tm->next) {
1731 while(tm->clients) {
1732 c = tm->clients;
1733 tm->clients = c->next;
1734 detachstack(c);
1735 c->mon = newmons;
1736 attach(c);
1737 attachstack(c);
1738 }
1739 }
1740
1741 /* select focused monitor */
1742 selmon = newmons;
1743 if(XQueryPointer(dpy, root, &dummy, &dummy, &x, &y, &di, &di, &dui))
1744 for(m = newmons; m; m = m->next)
1745 if(INRECT(x, y, m->wx, m->wy, m->ww, m->wh)) {
1746 selmon = m;
1747 break;
1748 }
1749
1750 /* final assignment of new monitors */
1751 cleanupmons();
1752 mons = newmons;
1753 }
1754
1755 void
1756 updatenumlockmask(void) {
1757 unsigned int i, j;
1758 XModifierKeymap *modmap;
1759
1760 numlockmask = 0;
1761 modmap = XGetModifierMapping(dpy);
1762 for(i = 0; i < 8; i++)
1763 for(j = 0; j < modmap->max_keypermod; j++)
1764 if(modmap->modifiermap[i * modmap->max_keypermod + j]
1765 == XKeysymToKeycode(dpy, XK_Num_Lock))
1766 numlockmask = (1 << i);
1767 XFreeModifiermap(modmap);
1768 }
1769
1770 void
1771 updatesizehints(Client *c) {
1772 long msize;
1773 XSizeHints size;
1774
1775 if(!XGetWMNormalHints(dpy, c->win, &size, &msize))
1776 /* size is uninitialized, ensure that size.flags aren't used */
1777 size.flags = PSize;
1778 if(size.flags & PBaseSize) {
1779 c->basew = size.base_width;
1780 c->baseh = size.base_height;
1781 }
1782 else if(size.flags & PMinSize) {
1783 c->basew = size.min_width;
1784 c->baseh = size.min_height;
1785 }
1786 else
1787 c->basew = c->baseh = 0;
1788 if(size.flags & PResizeInc) {
1789 c->incw = size.width_inc;
1790 c->inch = size.height_inc;
1791 }
1792 else
1793 c->incw = c->inch = 0;
1794 if(size.flags & PMaxSize) {
1795 c->maxw = size.max_width;
1796 c->maxh = size.max_height;
1797 }
1798 else
1799 c->maxw = c->maxh = 0;
1800 if(size.flags & PMinSize) {
1801 c->minw = size.min_width;
1802 c->minh = size.min_height;
1803 }
1804 else if(size.flags & PBaseSize) {
1805 c->minw = size.base_width;
1806 c->minh = size.base_height;
1807 }
1808 else
1809 c->minw = c->minh = 0;
1810 if(size.flags & PAspect) {
1811 c->mina = (float)size.min_aspect.y / (float)size.min_aspect.x;
1812 c->maxa = (float)size.max_aspect.x / (float)size.max_aspect.y;
1813 }
1814 else
1815 c->maxa = c->mina = 0.0;
1816 c->isfixed = (c->maxw && c->minw && c->maxh && c->minh
1817 && c->maxw == c->minw && c->maxh == c->minh);
1818 }
1819
1820 void
1821 updatetitle(Client *c) {
1822 if(!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
1823 gettextprop(c->win, XA_WM_NAME, c->name, sizeof c->name);
1824 }
1825
1826 void
1827 updatestatus() {
1828 if(!gettextprop(root, XA_WM_NAME, stext, sizeof(stext)))
1829 strcpy(stext, "dwm-"VERSION);
1830 drawbar(selmon);
1831 }
1832
1833 void
1834 updatewmhints(Client *c) {
1835 XWMHints *wmh;
1836
1837 if((wmh = XGetWMHints(dpy, c->win))) {
1838 if(c == selmon->sel && wmh->flags & XUrgencyHint) {
1839 wmh->flags &= ~XUrgencyHint;
1840 XSetWMHints(dpy, c->win, wmh);
1841 }
1842 else
1843 c->isurgent = (wmh->flags & XUrgencyHint) ? True : False;
1844
1845 XFree(wmh);
1846 }
1847 }
1848
1849 void
1850 view(const Arg *arg) {
1851 if((arg->ui & TAGMASK) == selmon->tagset[selmon->seltags])
1852 return;
1853 selmon->seltags ^= 1; /* toggle sel tagset */
1854 if(arg->ui & TAGMASK)
1855 selmon->tagset[selmon->seltags] = arg->ui & TAGMASK;
1856 arrange();
1857 }
1858
1859 /* There's no way to check accesses to destroyed windows, thus those cases are
1860 * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
1861 * default error handler, which may call exit. */
1862 int
1863 xerror(Display *dpy, XErrorEvent *ee) {
1864 if(ee->error_code == BadWindow
1865 || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1866 || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1867 || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1868 || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1869 || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1870 || (ee->request_code == X_GrabButton && ee->error_code == BadAccess)
1871 || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1872 || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1873 return 0;
1874 fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1875 ee->request_code, ee->error_code);
1876 return xerrorxlib(dpy, ee); /* may call exit */
1877 }
1878
1879 int
1880 xerrordummy(Display *dpy, XErrorEvent *ee) {
1881 return 0;
1882 }
1883
1884 /* Startup Error handler to check if another window manager
1885 * is already running. */
1886 int
1887 xerrorstart(Display *dpy, XErrorEvent *ee) {
1888 otherwm = True;
1889 return -1;
1890 }
1891
1892 void
1893 zoom(const Arg *arg) {
1894 Client *c = selmon->sel;
1895
1896 if(!lt[selmon->sellt]->arrange || lt[selmon->sellt]->arrange == monocle || (selmon->sel && selmon->sel->isfloating))
1897 return;
1898 if(c == nexttiled(selmon->clients))
1899 if(!c || !(c = nexttiled(c->next)))
1900 return;
1901 detach(c);
1902 attach(c);
1903 focus(c);
1904 arrange();
1905 }
1906
1907 int
1908 main(int argc, char *argv[]) {
1909 if(argc == 2 && !strcmp("-v", argv[1]))
1910 die("dwm-"VERSION", © 2006-2009 dwm engineers, see LICENSE for details\n");
1911 else if(argc != 1)
1912 die("usage: dwm [-v]\n");
1913
1914 if(!setlocale(LC_CTYPE, "") || !XSupportsLocale())
1915 fputs("warning: no locale support\n", stderr);
1916
1917 if(!(dpy = XOpenDisplay(NULL)))
1918 die("dwm: cannot open display\n");
1919
1920 checkotherwm();
1921 setup();
1922 scan();
1923 run();
1924 cleanup();
1925
1926 XCloseDisplay(dpy);
1927 return 0;
1928 }