Xinqi Bao's Git

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