Xinqi Bao's Git

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