Xinqi Bao's Git

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