Xinqi Bao's Git

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