aewl

view dwm.c @ 755:cdd895c163bd

tag and seltag is now only bool removed unnecessary functions cleanups
author meillo@marmaro.de
date Fri, 30 May 2008 00:07:26 +0200
parents 4c12dccc288d
children bff1012527b3
line source
1 /* (C)opyright MMVI-MMVII Anselm R. Garbe <garbeam at gmail dot com>
2 * See LICENSE file for license details.
3 *
4 * dynamic window manager is designed like any other X client as well. It is
5 * driven through handling X events. In contrast to other X clients, a window
6 * manager selects for SubstructureRedirectMask on the root window, to receive
7 * events about window (dis-)appearance. Only one X connection at a time is
8 * allowed to select for this event mask.
9 *
10 * Calls to fetch an X event from the event queue are blocking. Due reading
11 * status text from standard input, a select()-driven main loop has been
12 * implemented which selects for reads on the X connection and STDIN_FILENO to
13 * handle all data smoothly. The event handlers of dwm are organized in an
14 * array which is accessed whenever a new event has been fetched. This allows
15 * event dispatching in O(1) time.
16 *
17 * Each child of the root window is called a client, except windows which have
18 * set the override_redirect flag. Clients are organized in a global
19 * doubly-linked client list, the focus history is remembered through a global
20 * stack list. Each client contains an array of Bools of the same size as the
21 * global tags array to indicate the tags of a client. For each client dwm
22 * creates a small title window, which is resized whenever the (_NET_)WM_NAME
23 * properties are updated or the client is moved/resized.
24 *
25 * Keys and tagging rules are organized as arrays and defined in the config.h
26 * file. These arrays are kept static in event.o and tag.o respectively,
27 * because no other part of dwm needs access to them. The current mode is
28 * represented by the arrange() function pointer, which wether points to
29 * dofloat() or dotile().
30 *
31 * To understand everything else, start reading main.c:main().
32 */
34 #include "config.h"
35 #include <errno.h>
36 #include <locale.h>
37 #include <regex.h>
38 #include <stdio.h>
39 #include <stdarg.h>
40 #include <stdlib.h>
41 #include <string.h>
42 #include <unistd.h>
43 #include <sys/select.h>
44 #include <sys/types.h>
45 #include <sys/wait.h>
46 #include <X11/cursorfont.h>
47 #include <X11/keysym.h>
48 #include <X11/Xatom.h>
49 #include <X11/Xlib.h>
50 #include <X11/Xproto.h>
51 #include <X11/Xutil.h>
53 /* mask shorthands, used in event.c and client.c */
54 #define BUTTONMASK (ButtonPressMask | ButtonReleaseMask)
56 enum { NetSupported, NetWMName, NetLast }; /* EWMH atoms */
57 enum { WMProtocols, WMDelete, WMState, WMLast }; /* default atoms */
58 enum { CurNormal, CurResize, CurMove, CurLast }; /* cursor */
59 enum { ColBorder, ColFG, ColBG, ColLast }; /* color */
61 typedef union {
62 const char *cmd;
63 int i;
64 } Arg; /* argument type */
66 typedef struct {
67 int ascent;
68 int descent;
69 int height;
70 XFontSet set;
71 XFontStruct *xfont;
72 } Fnt;
74 typedef struct {
75 int x, y, w, h;
76 unsigned long norm[ColLast];
77 unsigned long sel[ColLast];
78 Drawable drawable;
79 Fnt font;
80 GC gc;
81 } DC; /* draw context */
83 typedef struct Client Client;
84 struct Client {
85 char name[256];
86 int x, y, w, h;
87 int rx, ry, rw, rh; /* revert geometry */
88 int basew, baseh, incw, inch, maxw, maxh, minw, minh;
89 int minax, minay, maxax, maxay;
90 long flags;
91 unsigned int border;
92 Bool isfixed, isfloat, ismax;
93 Bool tag;
94 Client *next;
95 Client *prev;
96 Client *snext;
97 Window win;
98 };
100 typedef struct {
101 const char *clpattern;
102 int tag;
103 Bool isfloat;
104 } Rule;
106 typedef struct {
107 regex_t *clregex;
108 } RReg;
111 typedef struct {
112 unsigned long mod;
113 KeySym keysym;
114 void (*func)(Arg *arg);
115 Arg arg;
116 } Key;
119 #define CLEANMASK(mask) (mask & ~(numlockmask | LockMask))
120 #define MOUSEMASK (BUTTONMASK | PointerMotionMask)
124 const char *tags[]; /* all tags */
125 char stext[256]; /* status text */
126 int bh, bmw; /* bar height, bar mode label width */
127 int screen, sx, sy, sw, sh; /* screen geometry */
128 int wax, way, wah, waw; /* windowarea geometry */
129 unsigned int nmaster; /* number of master clients */
130 unsigned int ntags, numlockmask; /* number of tags, dynamic lock mask */
131 void (*handler[LASTEvent])(XEvent *); /* event handler */
132 void (*arrange)(void); /* arrange function, indicates mode */
133 Atom wmatom[WMLast], netatom[NetLast];
134 Bool running, selscreen, seltag; /* seltag is array of Bool */
135 Client *clients, *sel, *stack; /* global client list and stack */
136 Cursor cursor[CurLast];
137 DC dc; /* global draw context */
138 Display *dpy;
139 Window root, barwin;
141 Bool running = True;
142 Bool selscreen = True;
143 Client *clients = NULL;
144 Client *sel = NULL;
145 Client *stack = NULL;
146 DC dc = {0};
148 static int (*xerrorxlib)(Display *, XErrorEvent *);
149 static Bool otherwm, readin;
150 static RReg *rreg = NULL;
151 static unsigned int len = 0;
154 TAGS
155 RULES
158 /* client.c */
159 void configure(Client *c); /* send synthetic configure event */
160 void focus(Client *c); /* focus c, c may be NULL */
161 Client *getclient(Window w); /* return client of w */
162 Bool isprotodel(Client *c); /* returns True if c->win supports wmatom[WMDelete] */
163 void killclient(Arg *arg); /* kill c nicely */
164 void manage(Window w, XWindowAttributes *wa); /* manage new client */
165 void resize(Client *c, Bool sizehints); /* resize c*/
166 void updatesizehints(Client *c); /* update the size hint variables of c */
167 void updatetitle(Client *c); /* update the name of c */
168 void unmanage(Client *c); /* destroy c */
170 /* draw.c */
171 void drawstatus(void); /* draw the bar */
172 unsigned long getcolor(const char *colstr); /* return color of colstr */
173 void setfont(const char *fontstr); /* set the font for DC */
174 unsigned int textw(const char *text); /* return the width of text in px*/
176 /* event.c */
177 void grabkeys(void); /* grab all keys defined in config.h */
178 void procevent(void); /* process pending X events */
180 /* main.c */
181 void quit(Arg *arg); /* quit dwm nicely */
182 void sendevent(Window w, Atom a, long value); /* send synthetic event to w */
183 int xerror(Display *dsply, XErrorEvent *ee); /* dwm's X error handler */
185 /* tag.c */
186 void initrregs(void); /* initialize regexps of rules defined in config.h */
187 Client *getnext(Client *c); /* returns next visible client */
188 void settags(Client *c, Client *trans); /* sets tags of c */
189 void toggletag(Arg *arg); /* toggles c tags with arg's index */
191 /* util.c */
192 void *emallocz(unsigned int size); /* allocates zero-initialized memory, exits on error */
193 void eprint(const char *errstr, ...); /* prints errstr and exits with 1 */
194 void spawn(Arg *arg); /* forks a new subprocess with to arg's cmd */
196 /* view.c */
197 void detach(Client *c); /* detaches c from global client list */
198 void dofloat(void); /* arranges all windows floating */
199 void dotile(void); /* arranges all windows tiled */
200 void domax(void); /* arranges all windows fullscreen */
201 void focusnext(Arg *arg); /* focuses next visible client, arg is ignored */
202 void incnmaster(Arg *arg); /* increments nmaster with arg's index value */
203 Bool isvisible(Client *c); /* returns True if client is visible */
204 void restack(void); /* restores z layers of all clients */
205 void togglefloat(Arg *arg); /* toggles focusesd client between floating/non-floating state */
206 void togglemode(Arg *arg); /* toggles global arrange function (dotile/dofloat) */
207 void toggleview(); /* views the tag with arg's index */
208 void zoom(Arg *arg); /* zooms the focused client to master area, arg is ignored */
219 /* from view.c */
220 /* static */
222 static Client *
223 nexttiled(Client *c) {
224 for(c = getnext(c); c && c->isfloat; c = getnext(c->next));
225 return c;
226 }
228 static void
229 togglemax(Client *c) {
230 XEvent ev;
232 if(c->isfixed)
233 return;
235 if((c->ismax = !c->ismax)) {
236 c->rx = c->x; c->x = wax;
237 c->ry = c->y; c->y = way;
238 c->rw = c->w; c->w = waw - 2 * BORDERPX;
239 c->rh = c->h; c->h = wah - 2 * BORDERPX;
240 }
241 else {
242 c->x = c->rx;
243 c->y = c->ry;
244 c->w = c->rw;
245 c->h = c->rh;
246 }
247 resize(c, True);
248 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
249 }
253 void (*arrange)(void) = DEFMODE;
255 void
256 detach(Client *c) {
257 if(c->prev)
258 c->prev->next = c->next;
259 if(c->next)
260 c->next->prev = c->prev;
261 if(c == clients)
262 clients = c->next;
263 c->next = c->prev = NULL;
264 }
266 void
267 dofloat(void) {
268 Client *c;
270 for(c = clients; c; c = c->next) {
271 if(isvisible(c)) {
272 resize(c, True);
273 }
274 else
275 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
276 }
277 if(!sel || !isvisible(sel)) {
278 for(c = stack; c && !isvisible(c); c = c->snext);
279 focus(c);
280 }
281 restack();
282 }
284 void
285 dotile(void) {
286 unsigned int i, n, mw, mh, tw, th;
287 Client *c;
289 for(n = 0, c = nexttiled(clients); c; c = nexttiled(c->next))
290 n++;
291 /* window geoms */
292 mh = (n > nmaster) ? wah / nmaster : wah / (n > 0 ? n : 1);
293 mw = (n > nmaster) ? waw / 2 : waw;
294 th = (n > nmaster) ? wah / (n - nmaster) : 0;
295 tw = waw - mw;
297 for(i = 0, c = clients; c; c = c->next)
298 if(isvisible(c)) {
299 if(c->isfloat) {
300 resize(c, True);
301 continue;
302 }
303 c->ismax = False;
304 c->x = wax;
305 c->y = way;
306 if(i < nmaster) {
307 c->y += i * mh;
308 c->w = mw - 2 * BORDERPX;
309 c->h = mh - 2 * BORDERPX;
310 }
311 else { /* tile window */
312 c->x += mw;
313 c->w = tw - 2 * BORDERPX;
314 if(th > 2 * BORDERPX) {
315 c->y += (i - nmaster) * th;
316 c->h = th - 2 * BORDERPX;
317 }
318 else /* fallback if th <= 2 * BORDERPX */
319 c->h = wah - 2 * BORDERPX;
320 }
321 resize(c, False);
322 i++;
323 }
324 else
325 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
326 if(!sel || !isvisible(sel)) {
327 for(c = stack; c && !isvisible(c); c = c->snext);
328 focus(c);
329 }
330 restack();
331 }
333 /* begin code by mitch */
334 void
335 arrangemax(Client *c) {
336 if(c == sel) {
337 c->ismax = True;
338 c->x = sx;
339 c->y = bh;
340 c->w = sw - 2 * BORDERPX;
341 c->h = sh - bh - 2 * BORDERPX;
342 XRaiseWindow(dpy, c->win);
343 } else {
344 c->ismax = False;
345 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
346 XLowerWindow(dpy, c->win);
347 }
348 }
350 void
351 domax(void) {
352 Client *c;
354 for(c = clients; c; c = c->next) {
355 if(isvisible(c)) {
356 if(c->isfloat) {
357 resize(c, True);
358 continue;
359 }
360 arrangemax(c);
361 resize(c, False);
362 } else {
363 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
364 }
366 }
367 if(!sel || !isvisible(sel)) {
368 for(c = stack; c && !isvisible(c); c = c->snext);
369 focus(c);
370 }
371 restack();
372 }
373 /* end code by mitch */
375 void
376 focusnext(Arg *arg) {
377 Client *c;
379 if(!sel)
380 return;
381 if(!(c = getnext(sel->next)))
382 c = getnext(clients);
383 if(c) {
384 focus(c);
385 restack();
386 }
387 }
389 void
390 incnmaster(Arg *arg) {
391 if((arrange == dofloat) || (nmaster + arg->i < 1)
392 || (wah / (nmaster + arg->i) <= 2 * BORDERPX))
393 return;
394 nmaster += arg->i;
395 if(sel)
396 arrange();
397 else
398 drawstatus();
399 }
401 Bool
402 isvisible(Client *c) {
403 if((c->tag && seltag) || (!c->tag && !seltag)) {
404 return True;
405 }
406 return False;
407 }
409 void
410 restack(void) {
411 Client *c;
412 XEvent ev;
414 drawstatus();
415 if(!sel)
416 return;
417 if(sel->isfloat || arrange == dofloat)
418 XRaiseWindow(dpy, sel->win);
420 /* begin code by mitch */
421 if(arrange == domax) {
422 for(c = nexttiled(clients); c; c = nexttiled(c->next)) {
423 arrangemax(c);
424 resize(c, False);
425 }
427 } else if (arrange == dotile) {
428 /* end code by mitch */
430 if(!sel->isfloat)
431 XLowerWindow(dpy, sel->win);
432 for(c = nexttiled(clients); c; c = nexttiled(c->next)) {
433 if(c == sel)
434 continue;
435 XLowerWindow(dpy, c->win);
436 }
437 }
438 XSync(dpy, False);
439 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
440 }
442 void
443 togglefloat(Arg *arg) {
444 if (!sel || arrange == dofloat)
445 return;
446 sel->isfloat = !sel->isfloat;
447 arrange();
448 }
450 void
451 togglemode(Arg *arg) {
452 /* only toggle between tile and max - float is just available through togglefloat */
453 arrange = (arrange == dotile) ? domax : dotile;
454 if(sel)
455 arrange();
456 else
457 drawstatus();
458 }
460 void
461 toggleview() {
462 seltag = !seltag;
463 arrange();
464 }
466 void
467 zoom(Arg *arg) {
468 unsigned int n;
469 Client *c;
471 if(!sel)
472 return;
473 if(sel->isfloat || (arrange == dofloat)) {
474 togglemax(sel);
475 return;
476 }
477 for(n = 0, c = nexttiled(clients); c; c = nexttiled(c->next))
478 n++;
480 if((c = sel) == nexttiled(clients))
481 if(!(c = nexttiled(c->next)))
482 return;
483 detach(c);
484 if(clients)
485 clients->prev = c;
486 c->next = clients;
487 clients = c;
488 focus(c);
489 arrange();
490 }
507 /* from util.c */
510 void *
511 emallocz(unsigned int size) {
512 void *res = calloc(1, size);
514 if(!res)
515 eprint("fatal: could not malloc() %u bytes\n", size);
516 return res;
517 }
519 void
520 eprint(const char *errstr, ...) {
521 va_list ap;
523 va_start(ap, errstr);
524 vfprintf(stderr, errstr, ap);
525 va_end(ap);
526 exit(EXIT_FAILURE);
527 }
529 void
530 spawn(Arg *arg) {
531 static char *shell = NULL;
533 if(!shell && !(shell = getenv("SHELL")))
534 shell = "/bin/sh";
535 if(!arg->cmd)
536 return;
537 /* The double-fork construct avoids zombie processes and keeps the code
538 * clean from stupid signal handlers. */
539 if(fork() == 0) {
540 if(fork() == 0) {
541 if(dpy)
542 close(ConnectionNumber(dpy));
543 setsid();
544 execl(shell, shell, "-c", arg->cmd, (char *)NULL);
545 fprintf(stderr, "dwm: execl '%s -c %s'", shell, arg->cmd);
546 perror(" failed");
547 }
548 exit(0);
549 }
550 wait(0);
551 }
565 /* from tag.c */
567 /* static */
569 Client *
570 getnext(Client *c) {
571 for(; c && !isvisible(c); c = c->next);
572 return c;
573 }
575 void
576 initrregs(void) {
577 unsigned int i;
578 regex_t *reg;
580 if(rreg)
581 return;
582 len = sizeof rule / sizeof rule[0];
583 rreg = emallocz(len * sizeof(RReg));
584 for(i = 0; i < len; i++) {
585 if(rule[i].clpattern) {
586 reg = emallocz(sizeof(regex_t));
587 if(regcomp(reg, rule[i].clpattern, REG_EXTENDED))
588 free(reg);
589 else
590 rreg[i].clregex = reg;
591 }
592 }
593 }
595 void
596 settags(Client *c, Client *trans) {
597 char prop[512];
598 unsigned int i, j;
599 regmatch_t tmp;
600 Bool matched = trans != NULL;
601 XClassHint ch = { 0 };
603 if(matched) {
604 c->tag = trans->tag;
605 } else {
606 XGetClassHint(dpy, c->win, &ch);
607 snprintf(prop, sizeof prop, "%s:%s:%s",
608 ch.res_class ? ch.res_class : "",
609 ch.res_name ? ch.res_name : "", c->name);
610 for(i = 0; i < len; i++)
611 if(rreg[i].clregex && !regexec(rreg[i].clregex, prop, 1, &tmp, 0)) {
612 c->isfloat = rule[i].isfloat;
613 if (rule[i].tag < 0) {
614 c->tag = seltag;
615 } else if (rule[i].tag == 0) {
616 c->tag = True;
617 } else {
618 c->tag = False;
619 }
620 matched = True;
621 break; /* perform only the first rule matching */
622 }
623 if(ch.res_class)
624 XFree(ch.res_class);
625 if(ch.res_name)
626 XFree(ch.res_name);
627 }
628 if(!matched) {
629 c->tag = seltag;
630 }
631 }
633 void
634 toggletag(Arg *arg) {
635 if(!sel)
636 return;
637 sel->tag = !sel->tag;
638 toggleview();
639 }
657 /* from event.c */
658 /* static */
660 KEYS
664 static void
665 movemouse(Client *c) {
666 int x1, y1, ocx, ocy, di;
667 unsigned int dui;
668 Window dummy;
669 XEvent ev;
671 ocx = c->x;
672 ocy = c->y;
673 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
674 None, cursor[CurMove], CurrentTime) != GrabSuccess)
675 return;
676 c->ismax = False;
677 XQueryPointer(dpy, root, &dummy, &dummy, &x1, &y1, &di, &di, &dui);
678 for(;;) {
679 XMaskEvent(dpy, MOUSEMASK | ExposureMask | SubstructureRedirectMask, &ev);
680 switch (ev.type) {
681 case ButtonRelease:
682 resize(c, True);
683 XUngrabPointer(dpy, CurrentTime);
684 return;
685 case ConfigureRequest:
686 case Expose:
687 case MapRequest:
688 handler[ev.type](&ev);
689 break;
690 case MotionNotify:
691 XSync(dpy, False);
692 c->x = ocx + (ev.xmotion.x - x1);
693 c->y = ocy + (ev.xmotion.y - y1);
694 if(abs(wax + c->x) < SNAP)
695 c->x = wax;
696 else if(abs((wax + waw) - (c->x + c->w + 2 * c->border)) < SNAP)
697 c->x = wax + waw - c->w - 2 * c->border;
698 if(abs(way - c->y) < SNAP)
699 c->y = way;
700 else if(abs((way + wah) - (c->y + c->h + 2 * c->border)) < SNAP)
701 c->y = way + wah - c->h - 2 * c->border;
702 resize(c, False);
703 break;
704 }
705 }
706 }
708 static void
709 resizemouse(Client *c) {
710 int ocx, ocy;
711 int nw, nh;
712 XEvent ev;
714 ocx = c->x;
715 ocy = c->y;
716 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
717 None, cursor[CurResize], CurrentTime) != GrabSuccess)
718 return;
719 c->ismax = False;
720 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->border - 1, c->h + c->border - 1);
721 for(;;) {
722 XMaskEvent(dpy, MOUSEMASK | ExposureMask | SubstructureRedirectMask , &ev);
723 switch(ev.type) {
724 case ButtonRelease:
725 resize(c, True);
726 XUngrabPointer(dpy, CurrentTime);
727 return;
728 case ConfigureRequest:
729 case Expose:
730 case MapRequest:
731 handler[ev.type](&ev);
732 break;
733 case MotionNotify:
734 XSync(dpy, False);
735 nw = ev.xmotion.x - ocx - 2 * c->border + 1;
736 c->w = nw > 0 ? nw : 1;
737 nh = ev.xmotion.y - ocy - 2 * c->border + 1;
738 c->h = nh > 0 ? nh : 1;
739 resize(c, True);
740 break;
741 }
742 }
743 }
745 static void
746 buttonpress(XEvent *e) {
747 int x;
748 Arg a;
749 Client *c;
750 XButtonPressedEvent *ev = &e->xbutton;
752 if(barwin == ev->window) {
753 x = 0;
754 for(a.i = 0; a.i < ntags; a.i++) {
755 x += textw(tags[a.i]);
756 if(ev->x < x) {
757 if(ev->button == Button1) {
758 toggleview();
759 }
760 return;
761 }
762 }
763 if(ev->x < x + bmw)
764 if (ev->button == Button1) {
765 togglemode(NULL);
766 }
767 }
768 else if((c = getclient(ev->window))) {
769 focus(c);
770 if(CLEANMASK(ev->state) != MODKEY)
771 return;
772 if(ev->button == Button1 && (arrange == dofloat || c->isfloat)) {
773 restack();
774 movemouse(c);
775 }
776 else if(ev->button == Button2)
777 zoom(NULL);
778 else if(ev->button == Button3 && (arrange == dofloat || c->isfloat) &&
779 !c->isfixed) {
780 restack();
781 resizemouse(c);
782 }
783 }
784 }
786 static void
787 configurerequest(XEvent *e) {
788 unsigned long newmask;
789 Client *c;
790 XConfigureRequestEvent *ev = &e->xconfigurerequest;
791 XWindowChanges wc;
793 if((c = getclient(ev->window))) {
794 c->ismax = False;
795 if(ev->value_mask & CWX)
796 c->x = ev->x;
797 if(ev->value_mask & CWY)
798 c->y = ev->y;
799 if(ev->value_mask & CWWidth)
800 c->w = ev->width;
801 if(ev->value_mask & CWHeight)
802 c->h = ev->height;
803 if(ev->value_mask & CWBorderWidth)
804 c->border = ev->border_width;
805 wc.x = c->x;
806 wc.y = c->y;
807 wc.width = c->w;
808 wc.height = c->h;
809 newmask = ev->value_mask & (~(CWSibling | CWStackMode | CWBorderWidth));
810 if(newmask)
811 XConfigureWindow(dpy, c->win, newmask, &wc);
812 else
813 configure(c);
814 XSync(dpy, False);
815 if(c->isfloat) {
816 resize(c, False);
817 if(!isvisible(c))
818 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
819 }
820 else
821 arrange();
822 }
823 else {
824 wc.x = ev->x;
825 wc.y = ev->y;
826 wc.width = ev->width;
827 wc.height = ev->height;
828 wc.border_width = ev->border_width;
829 wc.sibling = ev->above;
830 wc.stack_mode = ev->detail;
831 XConfigureWindow(dpy, ev->window, ev->value_mask, &wc);
832 XSync(dpy, False);
833 }
834 }
836 static void
837 destroynotify(XEvent *e) {
838 Client *c;
839 XDestroyWindowEvent *ev = &e->xdestroywindow;
841 if((c = getclient(ev->window)))
842 unmanage(c);
843 }
845 static void
846 enternotify(XEvent *e) {
847 Client *c;
848 XCrossingEvent *ev = &e->xcrossing;
850 if(ev->mode != NotifyNormal || ev->detail == NotifyInferior)
851 return;
852 if((c = getclient(ev->window)) && isvisible(c))
853 focus(c);
854 else if(ev->window == root) {
855 selscreen = True;
856 for(c = stack; c && !isvisible(c); c = c->snext);
857 focus(c);
858 }
859 }
861 static void
862 expose(XEvent *e) {
863 XExposeEvent *ev = &e->xexpose;
865 if(ev->count == 0) {
866 if(barwin == ev->window)
867 drawstatus();
868 }
869 }
871 static void
872 keypress(XEvent *e) {
873 static unsigned int len = sizeof key / sizeof key[0];
874 unsigned int i;
875 KeySym keysym;
876 XKeyEvent *ev = &e->xkey;
878 keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
879 for(i = 0; i < len; i++) {
880 if(keysym == key[i].keysym
881 && CLEANMASK(key[i].mod) == CLEANMASK(ev->state))
882 {
883 if(key[i].func)
884 key[i].func(&key[i].arg);
885 }
886 }
887 }
889 static void
890 leavenotify(XEvent *e) {
891 XCrossingEvent *ev = &e->xcrossing;
893 if((ev->window == root) && !ev->same_screen) {
894 selscreen = False;
895 focus(NULL);
896 }
897 }
899 static void
900 mappingnotify(XEvent *e) {
901 XMappingEvent *ev = &e->xmapping;
903 XRefreshKeyboardMapping(ev);
904 if(ev->request == MappingKeyboard)
905 grabkeys();
906 }
908 static void
909 maprequest(XEvent *e) {
910 static XWindowAttributes wa;
911 XMapRequestEvent *ev = &e->xmaprequest;
913 if(!XGetWindowAttributes(dpy, ev->window, &wa))
914 return;
915 if(wa.override_redirect) {
916 XSelectInput(dpy, ev->window,
917 (StructureNotifyMask | PropertyChangeMask));
918 return;
919 }
920 if(!getclient(ev->window))
921 manage(ev->window, &wa);
922 }
924 static void
925 propertynotify(XEvent *e) {
926 Client *c;
927 Window trans;
928 XPropertyEvent *ev = &e->xproperty;
930 if(ev->state == PropertyDelete)
931 return; /* ignore */
932 if((c = getclient(ev->window))) {
933 switch (ev->atom) {
934 default: break;
935 case XA_WM_TRANSIENT_FOR:
936 XGetTransientForHint(dpy, c->win, &trans);
937 if(!c->isfloat && (c->isfloat = (trans != 0)))
938 arrange();
939 break;
940 case XA_WM_NORMAL_HINTS:
941 updatesizehints(c);
942 break;
943 }
944 if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
945 updatetitle(c);
946 if(c == sel)
947 drawstatus();
948 }
949 }
950 }
952 static void
953 unmapnotify(XEvent *e) {
954 Client *c;
955 XUnmapEvent *ev = &e->xunmap;
957 if((c = getclient(ev->window)))
958 unmanage(c);
959 }
963 void (*handler[LASTEvent]) (XEvent *) = {
964 [ButtonPress] = buttonpress,
965 [ConfigureRequest] = configurerequest,
966 [DestroyNotify] = destroynotify,
967 [EnterNotify] = enternotify,
968 [LeaveNotify] = leavenotify,
969 [Expose] = expose,
970 [KeyPress] = keypress,
971 [MappingNotify] = mappingnotify,
972 [MapRequest] = maprequest,
973 [PropertyNotify] = propertynotify,
974 [UnmapNotify] = unmapnotify
975 };
977 void
978 grabkeys(void) {
979 static unsigned int len = sizeof key / sizeof key[0];
980 unsigned int i;
981 KeyCode code;
983 XUngrabKey(dpy, AnyKey, AnyModifier, root);
984 for(i = 0; i < len; i++) {
985 code = XKeysymToKeycode(dpy, key[i].keysym);
986 XGrabKey(dpy, code, key[i].mod, root, True,
987 GrabModeAsync, GrabModeAsync);
988 XGrabKey(dpy, code, key[i].mod | LockMask, root, True,
989 GrabModeAsync, GrabModeAsync);
990 XGrabKey(dpy, code, key[i].mod | numlockmask, root, True,
991 GrabModeAsync, GrabModeAsync);
992 XGrabKey(dpy, code, key[i].mod | numlockmask | LockMask, root, True,
993 GrabModeAsync, GrabModeAsync);
994 }
995 }
997 void
998 procevent(void) {
999 XEvent ev;
1001 while(XPending(dpy)) {
1002 XNextEvent(dpy, &ev);
1003 if(handler[ev.type])
1004 (handler[ev.type])(&ev); /* call handler */
1022 /* from draw.c */
1023 /* static */
1025 static unsigned int
1026 textnw(const char *text, unsigned int len) {
1027 XRectangle r;
1029 if(dc.font.set) {
1030 XmbTextExtents(dc.font.set, text, len, NULL, &r);
1031 return r.width;
1033 return XTextWidth(dc.font.xfont, text, len);
1036 static void
1037 drawtext(const char *text, unsigned long col[ColLast]) {
1038 int x, y, w, h;
1039 static char buf[256];
1040 unsigned int len, olen;
1041 XGCValues gcv;
1042 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
1044 XSetForeground(dpy, dc.gc, col[ColBG]);
1045 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
1046 if(!text)
1047 return;
1048 w = 0;
1049 olen = len = strlen(text);
1050 if(len >= sizeof buf)
1051 len = sizeof buf - 1;
1052 memcpy(buf, text, len);
1053 buf[len] = 0;
1054 h = dc.font.ascent + dc.font.descent;
1055 y = dc.y + (dc.h / 2) - (h / 2) + dc.font.ascent;
1056 x = dc.x + (h / 2);
1057 /* shorten text if necessary */
1058 while(len && (w = textnw(buf, len)) > dc.w - h)
1059 buf[--len] = 0;
1060 if(len < olen) {
1061 if(len > 1)
1062 buf[len - 1] = '.';
1063 if(len > 2)
1064 buf[len - 2] = '.';
1065 if(len > 3)
1066 buf[len - 3] = '.';
1068 if(w > dc.w)
1069 return; /* too long */
1070 gcv.foreground = col[ColFG];
1071 if(dc.font.set) {
1072 XChangeGC(dpy, dc.gc, GCForeground, &gcv);
1073 XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
1074 } else {
1075 gcv.font = dc.font.xfont->fid;
1076 XChangeGC(dpy, dc.gc, GCForeground | GCFont, &gcv);
1077 XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
1083 void
1084 drawstatus(void) {
1085 int i, x;
1087 dc.x = dc.y = 0;
1088 for(i = 0; i < ntags; i++) {
1089 dc.w = textw(tags[i]);
1090 drawtext(tags[i], ( (i == 0 && seltag || i == 1 && !seltag) ? dc.sel : dc.norm));
1091 dc.x += dc.w + 1;
1093 dc.w = bmw;
1094 drawtext("", dc.norm);
1095 x = dc.x + dc.w;
1096 dc.w = textw(stext);
1097 dc.x = sw - dc.w;
1098 if(dc.x < x) {
1099 dc.x = x;
1100 dc.w = sw - x;
1102 drawtext(stext, dc.norm);
1103 if((dc.w = dc.x - x) > bh) {
1104 dc.x = x;
1105 drawtext(sel ? sel->name : NULL, dc.norm);
1107 XCopyArea(dpy, dc.drawable, barwin, dc.gc, 0, 0, sw, bh, 0, 0);
1108 XSync(dpy, False);
1111 unsigned long
1112 getcolor(const char *colstr) {
1113 Colormap cmap = DefaultColormap(dpy, screen);
1114 XColor color;
1116 if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
1117 eprint("error, cannot allocate color '%s'\n", colstr);
1118 return color.pixel;
1121 void
1122 setfont(const char *fontstr) {
1123 char *def, **missing;
1124 int i, n;
1126 missing = NULL;
1127 if(dc.font.set)
1128 XFreeFontSet(dpy, dc.font.set);
1129 dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
1130 if(missing) {
1131 while(n--)
1132 fprintf(stderr, "missing fontset: %s\n", missing[n]);
1133 XFreeStringList(missing);
1135 if(dc.font.set) {
1136 XFontSetExtents *font_extents;
1137 XFontStruct **xfonts;
1138 char **font_names;
1139 dc.font.ascent = dc.font.descent = 0;
1140 font_extents = XExtentsOfFontSet(dc.font.set);
1141 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
1142 for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
1143 if(dc.font.ascent < (*xfonts)->ascent)
1144 dc.font.ascent = (*xfonts)->ascent;
1145 if(dc.font.descent < (*xfonts)->descent)
1146 dc.font.descent = (*xfonts)->descent;
1147 xfonts++;
1149 } else {
1150 if(dc.font.xfont)
1151 XFreeFont(dpy, dc.font.xfont);
1152 dc.font.xfont = NULL;
1153 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr)))
1154 eprint("error, cannot load font: '%s'\n", fontstr);
1155 dc.font.ascent = dc.font.xfont->ascent;
1156 dc.font.descent = dc.font.xfont->descent;
1158 dc.font.height = dc.font.ascent + dc.font.descent;
1161 unsigned int
1162 textw(const char *text) {
1163 return textnw(text, strlen(text)) + dc.font.height;
1176 /* from client.c */
1177 /* static */
1179 static void
1180 detachstack(Client *c) {
1181 Client **tc;
1182 for(tc=&stack; *tc && *tc != c; tc=&(*tc)->snext);
1183 *tc = c->snext;
1186 static void
1187 grabbuttons(Client *c, Bool focused) {
1188 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1190 if(focused) {
1191 XGrabButton(dpy, Button1, MODKEY, c->win, False, BUTTONMASK,
1192 GrabModeAsync, GrabModeSync, None, None);
1193 XGrabButton(dpy, Button1, MODKEY | LockMask, c->win, False, BUTTONMASK,
1194 GrabModeAsync, GrabModeSync, None, None);
1195 XGrabButton(dpy, Button1, MODKEY | numlockmask, c->win, False, BUTTONMASK,
1196 GrabModeAsync, GrabModeSync, None, None);
1197 XGrabButton(dpy, Button1, MODKEY | numlockmask | LockMask, c->win, False, BUTTONMASK,
1198 GrabModeAsync, GrabModeSync, None, None);
1200 XGrabButton(dpy, Button2, MODKEY, c->win, False, BUTTONMASK,
1201 GrabModeAsync, GrabModeSync, None, None);
1202 XGrabButton(dpy, Button2, MODKEY | LockMask, c->win, False, BUTTONMASK,
1203 GrabModeAsync, GrabModeSync, None, None);
1204 XGrabButton(dpy, Button2, MODKEY | numlockmask, c->win, False, BUTTONMASK,
1205 GrabModeAsync, GrabModeSync, None, None);
1206 XGrabButton(dpy, Button2, MODKEY | numlockmask | LockMask, c->win, False, BUTTONMASK,
1207 GrabModeAsync, GrabModeSync, None, None);
1209 XGrabButton(dpy, Button3, MODKEY, c->win, False, BUTTONMASK,
1210 GrabModeAsync, GrabModeSync, None, None);
1211 XGrabButton(dpy, Button3, MODKEY | LockMask, c->win, False, BUTTONMASK,
1212 GrabModeAsync, GrabModeSync, None, None);
1213 XGrabButton(dpy, Button3, MODKEY | numlockmask, c->win, False, BUTTONMASK,
1214 GrabModeAsync, GrabModeSync, None, None);
1215 XGrabButton(dpy, Button3, MODKEY | numlockmask | LockMask, c->win, False, BUTTONMASK,
1216 GrabModeAsync, GrabModeSync, None, None);
1217 } else {
1218 XGrabButton(dpy, AnyButton, AnyModifier, c->win, False, BUTTONMASK,
1219 GrabModeAsync, GrabModeSync, None, None);
1223 static void
1224 setclientstate(Client *c, long state) {
1225 long data[] = {state, None};
1226 XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1227 PropModeReplace, (unsigned char *)data, 2);
1230 static int
1231 xerrordummy(Display *dsply, XErrorEvent *ee) {
1232 return 0;
1237 void
1238 configure(Client *c) {
1239 XEvent synev;
1241 synev.type = ConfigureNotify;
1242 synev.xconfigure.display = dpy;
1243 synev.xconfigure.event = c->win;
1244 synev.xconfigure.window = c->win;
1245 synev.xconfigure.x = c->x;
1246 synev.xconfigure.y = c->y;
1247 synev.xconfigure.width = c->w;
1248 synev.xconfigure.height = c->h;
1249 synev.xconfigure.border_width = c->border;
1250 synev.xconfigure.above = None;
1251 XSendEvent(dpy, c->win, True, NoEventMask, &synev);
1254 void
1255 focus(Client *c) {
1256 if(c && !isvisible(c))
1257 return;
1258 if(sel && sel != c) {
1259 grabbuttons(sel, False);
1260 XSetWindowBorder(dpy, sel->win, dc.norm[ColBorder]);
1262 if(c) {
1263 detachstack(c);
1264 c->snext = stack;
1265 stack = c;
1266 grabbuttons(c, True);
1268 sel = c;
1269 drawstatus();
1270 if(!selscreen)
1271 return;
1272 if(c) {
1273 XSetWindowBorder(dpy, c->win, dc.sel[ColBorder]);
1274 XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
1275 } else {
1276 XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
1280 Client *
1281 getclient(Window w) {
1282 Client *c;
1284 for(c = clients; c; c = c->next) {
1285 if(c->win == w) {
1286 return c;
1289 return NULL;
1292 Bool
1293 isprotodel(Client *c) {
1294 int i, n;
1295 Atom *protocols;
1296 Bool ret = False;
1298 if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
1299 for(i = 0; !ret && i < n; i++)
1300 if(protocols[i] == wmatom[WMDelete])
1301 ret = True;
1302 XFree(protocols);
1304 return ret;
1307 void
1308 killclient(Arg *arg) {
1309 if(!sel)
1310 return;
1311 if(isprotodel(sel))
1312 sendevent(sel->win, wmatom[WMProtocols], wmatom[WMDelete]);
1313 else
1314 XKillClient(dpy, sel->win);
1317 void
1318 manage(Window w, XWindowAttributes *wa) {
1319 Client *c;
1320 Window trans;
1322 c = emallocz(sizeof(Client));
1323 c->tag = True;
1324 c->win = w;
1325 c->x = wa->x;
1326 c->y = wa->y;
1327 c->w = wa->width;
1328 c->h = wa->height;
1329 if(c->w == sw && c->h == sh) {
1330 c->border = 0;
1331 c->x = sx;
1332 c->y = sy;
1333 } else {
1334 c->border = BORDERPX;
1335 if(c->x + c->w + 2 * c->border > wax + waw)
1336 c->x = wax + waw - c->w - 2 * c->border;
1337 if(c->y + c->h + 2 * c->border > way + wah)
1338 c->y = way + wah - c->h - 2 * c->border;
1339 if(c->x < wax)
1340 c->x = wax;
1341 if(c->y < way)
1342 c->y = way;
1344 updatesizehints(c);
1345 XSelectInput(dpy, c->win,
1346 StructureNotifyMask | PropertyChangeMask | EnterWindowMask);
1347 XGetTransientForHint(dpy, c->win, &trans);
1348 grabbuttons(c, False);
1349 XSetWindowBorder(dpy, c->win, dc.norm[ColBorder]);
1350 updatetitle(c);
1351 settags(c, getclient(trans));
1352 if(!c->isfloat)
1353 c->isfloat = trans || c->isfixed;
1354 if(clients)
1355 clients->prev = c;
1356 c->next = clients;
1357 c->snext = stack;
1358 stack = clients = c;
1359 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
1360 XMapWindow(dpy, c->win);
1361 setclientstate(c, NormalState);
1362 if(isvisible(c))
1363 focus(c);
1364 arrange();
1367 void
1368 resize(Client *c, Bool sizehints) {
1369 float actual, dx, dy, max, min;
1370 XWindowChanges wc;
1372 if(c->w <= 0 || c->h <= 0)
1373 return;
1374 if(sizehints) {
1375 if(c->minw && c->w < c->minw)
1376 c->w = c->minw;
1377 if(c->minh && c->h < c->minh)
1378 c->h = c->minh;
1379 if(c->maxw && c->w > c->maxw)
1380 c->w = c->maxw;
1381 if(c->maxh && c->h > c->maxh)
1382 c->h = c->maxh;
1383 /* inspired by algorithm from fluxbox */
1384 if(c->minay > 0 && c->maxay && (c->h - c->baseh) > 0) {
1385 dx = (float)(c->w - c->basew);
1386 dy = (float)(c->h - c->baseh);
1387 min = (float)(c->minax) / (float)(c->minay);
1388 max = (float)(c->maxax) / (float)(c->maxay);
1389 actual = dx / dy;
1390 if(max > 0 && min > 0 && actual > 0) {
1391 if(actual < min) {
1392 dy = (dx * min + dy) / (min * min + 1);
1393 dx = dy * min;
1394 c->w = (int)dx + c->basew;
1395 c->h = (int)dy + c->baseh;
1397 else if(actual > max) {
1398 dy = (dx * min + dy) / (max * max + 1);
1399 dx = dy * min;
1400 c->w = (int)dx + c->basew;
1401 c->h = (int)dy + c->baseh;
1405 if(c->incw)
1406 c->w -= (c->w - c->basew) % c->incw;
1407 if(c->inch)
1408 c->h -= (c->h - c->baseh) % c->inch;
1410 if(c->w == sw && c->h == sh)
1411 c->border = 0;
1412 else
1413 c->border = BORDERPX;
1414 /* offscreen appearance fixes */
1415 if(c->x > sw)
1416 c->x = sw - c->w - 2 * c->border;
1417 if(c->y > sh)
1418 c->y = sh - c->h - 2 * c->border;
1419 if(c->x + c->w + 2 * c->border < sx)
1420 c->x = sx;
1421 if(c->y + c->h + 2 * c->border < sy)
1422 c->y = sy;
1423 wc.x = c->x;
1424 wc.y = c->y;
1425 wc.width = c->w;
1426 wc.height = c->h;
1427 wc.border_width = c->border;
1428 XConfigureWindow(dpy, c->win, CWX | CWY | CWWidth | CWHeight | CWBorderWidth, &wc);
1429 configure(c);
1430 XSync(dpy, False);
1433 void
1434 updatesizehints(Client *c) {
1435 long msize;
1436 XSizeHints size;
1438 if(!XGetWMNormalHints(dpy, c->win, &size, &msize) || !size.flags)
1439 size.flags = PSize;
1440 c->flags = size.flags;
1441 if(c->flags & PBaseSize) {
1442 c->basew = size.base_width;
1443 c->baseh = size.base_height;
1444 } else {
1445 c->basew = c->baseh = 0;
1447 if(c->flags & PResizeInc) {
1448 c->incw = size.width_inc;
1449 c->inch = size.height_inc;
1450 } else {
1451 c->incw = c->inch = 0;
1453 if(c->flags & PMaxSize) {
1454 c->maxw = size.max_width;
1455 c->maxh = size.max_height;
1456 } else {
1457 c->maxw = c->maxh = 0;
1459 if(c->flags & PMinSize) {
1460 c->minw = size.min_width;
1461 c->minh = size.min_height;
1462 } else {
1463 c->minw = c->minh = 0;
1465 if(c->flags & PAspect) {
1466 c->minax = size.min_aspect.x;
1467 c->minay = size.min_aspect.y;
1468 c->maxax = size.max_aspect.x;
1469 c->maxay = size.max_aspect.y;
1470 } else {
1471 c->minax = c->minay = c->maxax = c->maxay = 0;
1473 c->isfixed = (c->maxw && c->minw && c->maxh && c->minh &&
1474 c->maxw == c->minw && c->maxh == c->minh);
1477 void
1478 updatetitle(Client *c) {
1479 char **list = NULL;
1480 int n;
1481 XTextProperty name;
1483 name.nitems = 0;
1484 c->name[0] = 0;
1485 XGetTextProperty(dpy, c->win, &name, netatom[NetWMName]);
1486 if(!name.nitems)
1487 XGetWMName(dpy, c->win, &name);
1488 if(!name.nitems)
1489 return;
1490 if(name.encoding == XA_STRING)
1491 strncpy(c->name, (char *)name.value, sizeof c->name);
1492 else {
1493 if(XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success && n > 0 && *list) {
1494 strncpy(c->name, *list, sizeof c->name);
1495 XFreeStringList(list);
1498 XFree(name.value);
1501 void
1502 unmanage(Client *c) {
1503 Client *nc;
1505 /* The server grab construct avoids race conditions. */
1506 XGrabServer(dpy);
1507 XSetErrorHandler(xerrordummy);
1508 detach(c);
1509 detachstack(c);
1510 if(sel == c) {
1511 for(nc = stack; nc && !isvisible(nc); nc = nc->snext);
1512 focus(nc);
1514 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1515 setclientstate(c, WithdrawnState);
1516 free(c);
1517 XSync(dpy, False);
1518 XSetErrorHandler(xerror);
1519 XUngrabServer(dpy);
1520 arrange();
1541 /* static */
1544 static void
1545 cleanup(void) {
1546 close(STDIN_FILENO);
1547 while(stack) {
1548 resize(stack, True);
1549 unmanage(stack);
1551 if(dc.font.set)
1552 XFreeFontSet(dpy, dc.font.set);
1553 else
1554 XFreeFont(dpy, dc.font.xfont);
1555 XUngrabKey(dpy, AnyKey, AnyModifier, root);
1556 XFreePixmap(dpy, dc.drawable);
1557 XFreeGC(dpy, dc.gc);
1558 XDestroyWindow(dpy, barwin);
1559 XFreeCursor(dpy, cursor[CurNormal]);
1560 XFreeCursor(dpy, cursor[CurResize]);
1561 XFreeCursor(dpy, cursor[CurMove]);
1562 XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime);
1563 XSync(dpy, False);
1566 static void
1567 scan(void) {
1568 unsigned int i, num;
1569 Window *wins, d1, d2;
1570 XWindowAttributes wa;
1572 wins = NULL;
1573 if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1574 for(i = 0; i < num; i++) {
1575 if(!XGetWindowAttributes(dpy, wins[i], &wa))
1576 continue;
1577 if(wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1578 continue;
1579 if(wa.map_state == IsViewable)
1580 manage(wins[i], &wa);
1583 if(wins)
1584 XFree(wins);
1587 static void
1588 setup(void) {
1589 int i, j;
1590 unsigned int mask;
1591 Window w;
1592 XModifierKeymap *modmap;
1593 XSetWindowAttributes wa;
1595 /* init atoms */
1596 wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1597 wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1598 wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1599 netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1600 netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1601 XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1602 PropModeReplace, (unsigned char *) netatom, NetLast);
1603 /* init cursors */
1604 cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1605 cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1606 cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1607 /* init modifier map */
1608 numlockmask = 0;
1609 modmap = XGetModifierMapping(dpy);
1610 for (i = 0; i < 8; i++) {
1611 for (j = 0; j < modmap->max_keypermod; j++) {
1612 if(modmap->modifiermap[i * modmap->max_keypermod + j] == XKeysymToKeycode(dpy, XK_Num_Lock))
1613 numlockmask = (1 << i);
1616 XFreeModifiermap(modmap);
1617 /* select for events */
1618 wa.event_mask = SubstructureRedirectMask | SubstructureNotifyMask
1619 | EnterWindowMask | LeaveWindowMask;
1620 wa.cursor = cursor[CurNormal];
1621 XChangeWindowAttributes(dpy, root, CWEventMask | CWCursor, &wa);
1622 grabkeys();
1623 initrregs();
1624 ntags = 2;
1625 seltag = True;
1626 /* style */
1627 dc.norm[ColBorder] = getcolor(NORMBORDERCOLOR);
1628 dc.norm[ColBG] = getcolor(NORMBGCOLOR);
1629 dc.norm[ColFG] = getcolor(NORMFGCOLOR);
1630 dc.sel[ColBorder] = getcolor(SELBORDERCOLOR);
1631 dc.sel[ColBG] = getcolor(SELBGCOLOR);
1632 dc.sel[ColFG] = getcolor(SELFGCOLOR);
1633 setfont(FONT);
1634 /* geometry */
1635 sx = sy = 0;
1636 sw = DisplayWidth(dpy, screen);
1637 sh = DisplayHeight(dpy, screen);
1638 nmaster = NMASTER;
1639 bmw = 1;
1640 /* bar */
1641 dc.h = bh = dc.font.height + 2;
1642 wa.override_redirect = 1;
1643 wa.background_pixmap = ParentRelative;
1644 wa.event_mask = ButtonPressMask | ExposureMask;
1645 barwin = XCreateWindow(dpy, root, sx, sy, sw, bh, 0,
1646 DefaultDepth(dpy, screen), CopyFromParent, DefaultVisual(dpy, screen),
1647 CWOverrideRedirect | CWBackPixmap | CWEventMask, &wa);
1648 XDefineCursor(dpy, barwin, cursor[CurNormal]);
1649 XMapRaised(dpy, barwin);
1650 strcpy(stext, "dwm-"VERSION);
1651 /* windowarea */
1652 wax = sx;
1653 way = sy + bh;
1654 wah = sh - bh;
1655 waw = sw;
1656 /* pixmap for everything */
1657 dc.drawable = XCreatePixmap(dpy, root, sw, bh, DefaultDepth(dpy, screen));
1658 dc.gc = XCreateGC(dpy, root, 0, 0);
1659 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
1660 /* multihead support */
1661 selscreen = XQueryPointer(dpy, root, &w, &w, &i, &i, &i, &i, &mask);
1664 /*
1665 * Startup Error handler to check if another window manager
1666 * is already running.
1667 */
1668 static int
1669 xerrorstart(Display *dsply, XErrorEvent *ee) {
1670 otherwm = True;
1671 return -1;
1676 void
1677 sendevent(Window w, Atom a, long value) {
1678 XEvent e;
1680 e.type = ClientMessage;
1681 e.xclient.window = w;
1682 e.xclient.message_type = a;
1683 e.xclient.format = 32;
1684 e.xclient.data.l[0] = value;
1685 e.xclient.data.l[1] = CurrentTime;
1686 XSendEvent(dpy, w, False, NoEventMask, &e);
1687 XSync(dpy, False);
1690 void
1691 quit(Arg *arg) {
1692 readin = running = False;
1695 /* There's no way to check accesses to destroyed windows, thus those cases are
1696 * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
1697 * default error handler, which may call exit.
1698 */
1699 int
1700 xerror(Display *dpy, XErrorEvent *ee) {
1701 if(ee->error_code == BadWindow
1702 || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1703 || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1704 || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1705 || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1706 || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1707 || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1708 || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1709 return 0;
1710 fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1711 ee->request_code, ee->error_code);
1712 return xerrorxlib(dpy, ee); /* may call exit */
1715 int
1716 main(int argc, char *argv[]) {
1717 char *p;
1718 int r, xfd;
1719 fd_set rd;
1721 if(argc == 2 && !strncmp("-v", argv[1], 3)) {
1722 fputs("dwm-"VERSION", (C)opyright MMVI-MMVII Anselm R. Garbe\n", stdout);
1723 exit(EXIT_SUCCESS);
1724 } else if(argc != 1) {
1725 eprint("usage: dwm [-v]\n");
1727 setlocale(LC_CTYPE, "");
1728 dpy = XOpenDisplay(0);
1729 if(!dpy) {
1730 eprint("dwm: cannot open display\n");
1732 xfd = ConnectionNumber(dpy);
1733 screen = DefaultScreen(dpy);
1734 root = RootWindow(dpy, screen);
1735 otherwm = False;
1736 XSetErrorHandler(xerrorstart);
1737 /* this causes an error if some other window manager is running */
1738 XSelectInput(dpy, root, SubstructureRedirectMask);
1739 XSync(dpy, False);
1740 if(otherwm) {
1741 eprint("dwm: another window manager is already running\n");
1744 XSync(dpy, False);
1745 XSetErrorHandler(NULL);
1746 xerrorxlib = XSetErrorHandler(xerror);
1747 XSync(dpy, False);
1748 setup();
1749 drawstatus();
1750 scan();
1752 /* main event loop, also reads status text from stdin */
1753 XSync(dpy, False);
1754 procevent();
1755 readin = True;
1756 while(running) {
1757 FD_ZERO(&rd);
1758 if(readin)
1759 FD_SET(STDIN_FILENO, &rd);
1760 FD_SET(xfd, &rd);
1761 if(select(xfd + 1, &rd, NULL, NULL, NULL) == -1) {
1762 if(errno == EINTR)
1763 continue;
1764 eprint("select failed\n");
1766 if(FD_ISSET(STDIN_FILENO, &rd)) {
1767 switch(r = read(STDIN_FILENO, stext, sizeof stext - 1)) {
1768 case -1:
1769 strncpy(stext, strerror(errno), sizeof stext - 1);
1770 stext[sizeof stext - 1] = '\0';
1771 readin = False;
1772 break;
1773 case 0:
1774 strncpy(stext, "EOF", 4);
1775 readin = False;
1776 break;
1777 default:
1778 for(stext[r] = '\0', p = stext + strlen(stext) - 1; p >= stext && *p == '\n'; *p-- = '\0');
1779 for(; p >= stext && *p != '\n'; --p);
1780 if(p > stext)
1781 strncpy(stext, p + 1, sizeof stext);
1783 drawstatus();
1785 if(FD_ISSET(xfd, &rd))
1786 procevent();
1788 cleanup();
1789 XCloseDisplay(dpy);
1790 return 0;