Xinqi Bao's Git

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