Xinqi Bao's Git

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