aewl

view aewl.c @ 766:3f7c68a720b5

undone naming change: "group" is "tag" again (but without plural)
author meillo@marmaro.de
date Fri, 05 Dec 2008 19:43:56 +0100
parents 15660880e23d
children 706991d15451
line source
1 /* (C)opyright MMVI-MMVII Anselm R. Garbe <garbeam at gmail dot com>
2 * (C)opyright MMVIII markus schnalke <meillo at marmaro dot de>
3 * See LICENSE file for license details.
4 *
5 * dynamic window manager is designed like any other X client as well. It is
6 * driven through handling X events. In contrast to other X clients, a window
7 * manager selects for SubstructureRedirectMask on the root window, to receive
8 * events about window (dis-)appearance. Only one X connection at a time is
9 * allowed to select for this event mask.
10 *
11 * Calls to fetch an X event from the event queue are blocking. Due reading
12 * status text from standard input, a select()-driven main loop has been
13 * implemented which selects for reads on the X connection and STDIN_FILENO to
14 * handle all data smoothly. The event handlers of dwm are organized in an
15 * array which is accessed whenever a new event has been fetched. This allows
16 * event dispatching in O(1) time.
17 *
18 * Each child of the root window is called a client, except windows which have
19 * set the override_redirect flag. Clients are organized in a global
20 * doubly-linked client list, the focus history is remembered through a global
21 * stack list. [...]
22 *
23 * Keys and tagging rules are organized as arrays and defined in the config.h
24 * file. These arrays are kept static in event.o and tag.o respectively,
25 * because no other part of dwm needs access to them. The current mode is
26 * represented by the arrange() function pointer, which wether points to
27 * domax() or dotile().
28 *
29 * To understand everything else, start reading main.c:main().
30 *
31 * -- and now about aewl --
32 *
33 * aewl is a stripped down dwm. It stated as a patchset, but finally forked off
34 * completely. The reason for this was the increasing gap between my wish to
35 * stay where dwm was, and dwm direction to go further. Further more did I
36 * always use only a small subset of dwm's features, so condencing dwm had been
37 * my wish for a long time.
38 *
39 * In aewl clients are either tagged or not (only one tag). Visible are either
40 * all tagged clients or all without the tag.
41 */
44 #include "config.h"
45 #include <errno.h>
46 #include <locale.h>
47 #include <regex.h>
48 #include <stdio.h>
49 #include <stdarg.h>
50 #include <stdlib.h>
51 #include <string.h>
52 #include <unistd.h>
53 #include <sys/select.h>
54 #include <sys/types.h>
55 #include <sys/wait.h>
56 #include <X11/cursorfont.h>
57 #include <X11/keysym.h>
58 #include <X11/Xatom.h>
59 #include <X11/Xlib.h>
60 #include <X11/Xproto.h>
61 #include <X11/Xutil.h>
63 /* mask shorthands, used in event.c and client.c */
64 #define BUTTONMASK (ButtonPressMask | ButtonReleaseMask)
66 enum { NetSupported, NetWMName, NetLast }; /* EWMH atoms */
67 enum { WMProtocols, WMDelete, WMState, WMLast }; /* default atoms */
68 enum { CurNormal, CurResize, CurMove, CurLast }; /* cursor */
69 enum { ColFG, ColBG, ColLast }; /* color */
71 typedef struct {
72 int ascent;
73 int descent;
74 int height;
75 XFontSet set;
76 XFontStruct *xfont;
77 } Fnt;
79 typedef struct {
80 int x, y, w, h;
81 unsigned long norm[ColLast];
82 unsigned long sel[ColLast];
83 Drawable drawable;
84 Fnt font;
85 GC gc;
86 } DC; /* draw context */
88 typedef struct Client Client;
89 struct Client {
90 char name[256];
91 int x, y, w, h;
92 int rx, ry, rw, rh; /* revert geometry */
93 int basew, baseh, incw, inch, maxw, maxh, minw, minh;
94 int minax, minay, maxax, maxay;
95 long flags;
96 unsigned int border;
97 Bool isfixed, isfloat, ismax;
98 Bool tag;
99 Client *next;
100 Client *prev;
101 Client *snext;
102 Window win;
103 };
105 typedef struct {
106 const char *clpattern;
107 int tag;
108 Bool isfloat;
109 } Rule;
111 typedef struct {
112 regex_t *clregex;
113 } RReg;
116 typedef struct {
117 unsigned long mod;
118 KeySym keysym;
119 void (*func)(const char* cmd);
120 const char* cmd;
121 } Key;
124 #define CLEANMASK(mask) (mask & ~(numlockmask | LockMask))
125 #define MOUSEMASK (BUTTONMASK | PointerMotionMask)
129 char stext[256]; /* status text */
130 int bh, bmw; /* bar height, bar mode label width */
131 int screen, sx, sy, sw, sh; /* screen geometry */
132 int wax, way, wah, waw; /* windowarea geometry */
133 unsigned int nmaster; /* number of master clients */
134 unsigned int numlockmask; /* dynamic lock mask */
135 void (*handler[LASTEvent])(XEvent *); /* event handler */
136 void (*arrange)(void); /* arrange function, indicates mode */
137 Atom wmatom[WMLast], netatom[NetLast];
138 Bool running, selscreen, seltag;
139 Client *clients, *sel, *stack; /* global client list and stack */
140 Cursor cursor[CurLast];
141 DC dc; /* global draw context */
142 Display *dpy;
143 Window root, barwin;
145 Bool running = True;
146 Bool selscreen = True;
147 Client *clients = NULL;
148 Client *sel = NULL;
149 Client *stack = NULL;
150 DC dc = {0};
152 static int (*xerrorxlib)(Display *, XErrorEvent *);
153 static Bool otherwm, readin;
154 static RReg *rreg = NULL;
155 static unsigned int len = 0;
158 RULES
161 /* client.c */
162 void configure(Client *c); /* send synthetic configure event */
163 void focus(Client *c); /* focus c, c may be NULL */
164 Client *getclient(Window w); /* return client of w */
165 Bool isprotodel(Client *c); /* returns True if c->win supports wmatom[WMDelete] */
166 void manage(Window w, XWindowAttributes *wa); /* manage new client */
167 void resize(Client *c, Bool sizehints); /* resize c*/
168 void updatesizehints(Client *c); /* update the size hint variables of c */
169 void updatetitle(Client *c); /* update the name of c */
170 void unmanage(Client *c); /* destroy c */
172 /* draw.c */
173 void drawstatus(void); /* draw the bar */
174 unsigned long getcolor(const char *colstr); /* return color of colstr */
175 void setfont(const char *fontstr); /* set the font for DC */
176 unsigned int textw(const char *text); /* return the width of text in px*/
178 /* event.c */
179 void grabkeys(void); /* grab all keys defined in config.h */
180 void procevent(void); /* process pending X events */
182 /* main.c */
183 void sendevent(Window w, Atom a, long value); /* send synthetic event to w */
184 int xerror(Display *dsply, XErrorEvent *ee); /* dwm's X error handler */
186 /* tag.c */
187 void initrregs(void); /* initialize regexps of rules defined in config.h */
188 Client *getnext(Client *c); /* returns next visible client */
189 void settag(Client *c, Client *trans); /* sets tag of c */
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 */
195 /* view.c */
196 void detach(Client *c); /* detaches c from global client list */
197 void dotile(void); /* arranges all windows tiled */
198 void domax(void); /* arranges all windows fullscreen */
199 Bool isvisible(Client *c); /* returns True if client is visible */
200 void restack(void); /* restores z layers of all clients */
203 void toggleview(void); /* toggle the view */
204 void focusnext(void); /* focuses next visible client */
205 void zoom(void); /* zooms the focused client to master area */
206 void killclient(void); /* kill c nicely */
207 void quit(void); /* quit dwm nicely */
208 void togglemode(void); /* toggles global arrange function (dotile/domax) */
209 void togglefloat(void); /* toggles focusesd client between floating/non-floating state */
210 void incnmaster(void); /* increments nmaster */
211 void decnmaster(void); /* decrements nmaster */
212 void toggletag(void); /* toggles tag of c */
213 void spawn(const char* cmd); /* forks a new subprocess with cmd */
224 /* from view.c */
225 /* static */
227 static Client *
228 nexttiled(Client *c) {
229 for(c = getnext(c); c && c->isfloat; c = getnext(c->next));
230 return c;
231 }
233 static void
234 togglemax(Client *c) {
235 XEvent ev;
237 if(c->isfixed)
238 return;
240 if((c->ismax = !c->ismax)) {
241 c->rx = c->x; c->x = wax;
242 c->ry = c->y; c->y = way;
243 c->rw = c->w; c->w = waw - 2 * BORDERPX;
244 c->rh = c->h; c->h = wah - 2 * BORDERPX;
245 }
246 else {
247 c->x = c->rx;
248 c->y = c->ry;
249 c->w = c->rw;
250 c->h = c->rh;
251 }
252 resize(c, True);
253 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
254 }
258 void (*arrange)(void) = DEFMODE;
260 void
261 detach(Client *c) {
262 if(c->prev)
263 c->prev->next = c->next;
264 if(c->next)
265 c->next->prev = c->prev;
266 if(c == clients)
267 clients = c->next;
268 c->next = c->prev = NULL;
269 }
271 void
272 dotile(void) {
273 unsigned int i, n, mw, mh, tw, th;
274 Client *c;
276 for(n = 0, c = nexttiled(clients); c; c = nexttiled(c->next))
277 n++;
278 /* window geoms */
279 mh = (n > nmaster) ? wah / nmaster : wah / (n > 0 ? n : 1);
280 mw = (n > nmaster) ? waw / 2 : waw;
281 th = (n > nmaster) ? wah / (n - nmaster) : 0;
282 tw = waw - mw;
284 for(i = 0, c = clients; c; c = c->next)
285 if(isvisible(c)) {
286 if(c->isfloat) {
287 resize(c, True);
288 continue;
289 }
290 c->ismax = False;
291 c->x = wax;
292 c->y = way;
293 if(i < nmaster) {
294 c->y += i * mh;
295 c->w = mw - 2 * BORDERPX;
296 c->h = mh - 2 * BORDERPX;
297 }
298 else { /* tile window */
299 c->x += mw;
300 c->w = tw - 2 * BORDERPX;
301 if(th > 2 * BORDERPX) {
302 c->y += (i - nmaster) * th;
303 c->h = th - 2 * BORDERPX;
304 }
305 else /* fallback if th <= 2 * BORDERPX */
306 c->h = wah - 2 * BORDERPX;
307 }
308 resize(c, False);
309 i++;
310 }
311 else
312 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
313 if(!sel || !isvisible(sel)) {
314 for(c = stack; c && !isvisible(c); c = c->snext);
315 focus(c);
316 }
317 restack();
318 }
320 /* begin code by mitch */
321 void
322 arrangemax(Client *c) {
323 if(c == sel) {
324 c->ismax = True;
325 c->x = sx;
326 c->y = bh;
327 c->w = sw - 2 * BORDERPX;
328 c->h = sh - bh - 2 * BORDERPX;
329 XRaiseWindow(dpy, c->win);
330 } else {
331 c->ismax = False;
332 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
333 XLowerWindow(dpy, c->win);
334 }
335 }
337 void
338 domax(void) {
339 Client *c;
341 for(c = clients; c; c = c->next) {
342 if(isvisible(c)) {
343 if(c->isfloat) {
344 resize(c, True);
345 continue;
346 }
347 arrangemax(c);
348 resize(c, False);
349 } else {
350 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
351 }
353 }
354 if(!sel || !isvisible(sel)) {
355 for(c = stack; c && !isvisible(c); c = c->snext);
356 focus(c);
357 }
358 restack();
359 }
360 /* end code by mitch */
362 void
363 focusnext() {
364 Client *c;
366 if(!sel)
367 return;
368 if(!(c = getnext(sel->next)))
369 c = getnext(clients);
370 if(c) {
371 focus(c);
372 restack();
373 }
374 }
376 void
377 incnmaster() {
378 if(wah / (nmaster + 1) <= 2 * BORDERPX)
379 return;
380 nmaster++;
381 if(sel)
382 arrange();
383 else
384 drawstatus();
385 }
387 void
388 decnmaster() {
389 if(nmaster <= 1)
390 return;
391 nmaster--;
392 if(sel)
393 arrange();
394 else
395 drawstatus();
396 }
398 Bool
399 isvisible(Client *c) {
400 return (c->tag == seltag);
401 }
403 void
404 restack(void) {
405 Client *c;
406 XEvent ev;
408 drawstatus();
409 if(!sel)
410 return;
411 if(sel->isfloat)
412 XRaiseWindow(dpy, sel->win);
414 /* begin code by mitch */
415 if(arrange == domax) {
416 for(c = nexttiled(clients); c; c = nexttiled(c->next)) {
417 arrangemax(c);
418 resize(c, False);
419 }
421 } else if (arrange == dotile) {
422 /* end code by mitch */
424 if(!sel->isfloat)
425 XLowerWindow(dpy, sel->win);
426 for(c = nexttiled(clients); c; c = nexttiled(c->next)) {
427 if(c == sel)
428 continue;
429 XLowerWindow(dpy, c->win);
430 }
431 }
432 XSync(dpy, False);
433 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
434 }
436 void
437 togglefloat() {
438 if (!sel)
439 return;
440 sel->isfloat = !sel->isfloat;
441 arrange();
442 }
444 void
445 togglemode() {
446 /* only toggle between tile and max - float is just available through togglefloat */
447 arrange = (arrange == dotile) ? domax : dotile;
448 if(sel)
449 arrange();
450 else
451 drawstatus();
452 }
454 void
455 toggleview() {
456 seltag = !seltag;
457 arrange();
458 }
460 void
461 zoom() {
462 unsigned int n;
463 Client *c;
465 if(!sel)
466 return;
467 if(sel->isfloat) {
468 togglemax(sel);
469 return;
470 }
471 for(n = 0, c = nexttiled(clients); c; c = nexttiled(c->next))
472 n++;
474 if((c = sel) == nexttiled(clients))
475 if(!(c = nexttiled(c->next)))
476 return;
477 detach(c);
478 if(clients)
479 clients->prev = c;
480 c->next = clients;
481 clients = c;
482 focus(c);
483 arrange();
484 }
501 /* from util.c */
504 void *
505 emallocz(unsigned int size) {
506 void *res = calloc(1, size);
508 if(!res)
509 eprint("fatal: could not malloc() %u bytes\n", size);
510 return res;
511 }
513 void
514 eprint(const char *errstr, ...) {
515 va_list ap;
517 va_start(ap, errstr);
518 vfprintf(stderr, errstr, ap);
519 va_end(ap);
520 exit(EXIT_FAILURE);
521 }
523 void
524 spawn(const char* cmd) {
525 static char *shell = NULL;
527 if(!shell && !(shell = getenv("SHELL")))
528 shell = "/bin/sh";
529 if(!cmd)
530 return;
531 /* The double-fork construct avoids zombie processes and keeps the code
532 * clean from stupid signal handlers. */
533 if(fork() == 0) {
534 if(fork() == 0) {
535 if(dpy)
536 close(ConnectionNumber(dpy));
537 setsid();
538 execl(shell, shell, "-c", cmd, (char *)NULL);
539 fprintf(stderr, "dwm: execl '%s -c %s'", shell, cmd);
540 perror(" failed");
541 }
542 exit(0);
543 }
544 wait(0);
545 }
559 /* from tag.c */
561 /* static */
563 Client *
564 getnext(Client *c) {
565 for(; c && !isvisible(c); c = c->next);
566 return c;
567 }
569 void
570 initrregs(void) {
571 unsigned int i;
572 regex_t *reg;
574 if(rreg)
575 return;
576 len = sizeof rule / sizeof rule[0];
577 rreg = emallocz(len * sizeof(RReg));
578 for(i = 0; i < len; i++) {
579 if(rule[i].clpattern) {
580 reg = emallocz(sizeof(regex_t));
581 if(regcomp(reg, rule[i].clpattern, REG_EXTENDED))
582 free(reg);
583 else
584 rreg[i].clregex = reg;
585 }
586 }
587 }
589 void
590 settag(Client *c, Client *trans) {
591 char prop[512];
592 unsigned int i;
593 regmatch_t tmp;
594 Bool matched = (trans != NULL);
595 XClassHint ch = { 0 };
597 if(matched) {
598 c->tag = trans->tag;
599 } else {
600 XGetClassHint(dpy, c->win, &ch);
601 snprintf(prop, sizeof prop, "%s:%s:%s",
602 ch.res_class ? ch.res_class : "",
603 ch.res_name ? ch.res_name : "", c->name);
604 for(i = 0; i < len && !matched; i++)
605 if(rreg[i].clregex && !regexec(rreg[i].clregex, prop, 1, &tmp, 0)) {
606 c->isfloat = rule[i].isfloat;
607 if (rule[i].tag < 0) {
608 c->tag = seltag;
609 } else if (rule[i].tag) {
610 c->tag = True;
611 } else {
612 c->tag = False;
613 }
614 matched = True;
615 }
616 if(ch.res_class)
617 XFree(ch.res_class);
618 if(ch.res_name)
619 XFree(ch.res_name);
620 }
621 if(!matched) {
622 c->tag = seltag;
623 }
624 }
626 void
627 toggletag() {
628 if(!sel)
629 return;
630 sel->tag = !sel->tag;
631 toggleview();
632 }
650 /* from event.c */
651 /* static */
653 KEYS
657 static void
658 movemouse(Client *c) {
659 int x1, y1, ocx, ocy, di;
660 unsigned int dui;
661 Window dummy;
662 XEvent ev;
664 ocx = c->x;
665 ocy = c->y;
666 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
667 None, cursor[CurMove], CurrentTime) != GrabSuccess)
668 return;
669 c->ismax = False;
670 XQueryPointer(dpy, root, &dummy, &dummy, &x1, &y1, &di, &di, &dui);
671 for(;;) {
672 XMaskEvent(dpy, MOUSEMASK | ExposureMask | SubstructureRedirectMask, &ev);
673 switch (ev.type) {
674 case ButtonRelease:
675 resize(c, True);
676 XUngrabPointer(dpy, CurrentTime);
677 return;
678 case ConfigureRequest:
679 case Expose:
680 case MapRequest:
681 handler[ev.type](&ev);
682 break;
683 case MotionNotify:
684 XSync(dpy, False);
685 c->x = ocx + (ev.xmotion.x - x1);
686 c->y = ocy + (ev.xmotion.y - y1);
687 if(abs(wax + c->x) < SNAP)
688 c->x = wax;
689 else if(abs((wax + waw) - (c->x + c->w + 2 * c->border)) < SNAP)
690 c->x = wax + waw - c->w - 2 * c->border;
691 if(abs(way - c->y) < SNAP)
692 c->y = way;
693 else if(abs((way + wah) - (c->y + c->h + 2 * c->border)) < SNAP)
694 c->y = way + wah - c->h - 2 * c->border;
695 resize(c, False);
696 break;
697 }
698 }
699 }
701 static void
702 resizemouse(Client *c) {
703 int ocx, ocy;
704 int nw, nh;
705 XEvent ev;
707 ocx = c->x;
708 ocy = c->y;
709 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
710 None, cursor[CurResize], CurrentTime) != GrabSuccess)
711 return;
712 c->ismax = False;
713 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->border - 1, c->h + c->border - 1);
714 for(;;) {
715 XMaskEvent(dpy, MOUSEMASK | ExposureMask | SubstructureRedirectMask , &ev);
716 switch(ev.type) {
717 case ButtonRelease:
718 resize(c, True);
719 XUngrabPointer(dpy, CurrentTime);
720 return;
721 case ConfigureRequest:
722 case Expose:
723 case MapRequest:
724 handler[ev.type](&ev);
725 break;
726 case MotionNotify:
727 XSync(dpy, False);
728 nw = ev.xmotion.x - ocx - 2 * c->border + 1;
729 c->w = nw > 0 ? nw : 1;
730 nh = ev.xmotion.y - ocy - 2 * c->border + 1;
731 c->h = nh > 0 ? nh : 1;
732 resize(c, True);
733 break;
734 }
735 }
736 }
738 static void
739 buttonpress(XEvent *e) {
740 Client *c;
741 XButtonPressedEvent *ev = &e->xbutton;
743 if(barwin == ev->window) {
744 return;
745 }
746 if((c = getclient(ev->window))) {
747 focus(c);
748 if(CLEANMASK(ev->state) != MODKEY)
749 return;
750 if(ev->button == Button1 && c->isfloat) {
751 restack();
752 movemouse(c);
753 } else if(ev->button == Button3 && c->isfloat && !c->isfixed) {
754 restack();
755 resizemouse(c);
756 }
757 }
758 }
760 static void
761 configurerequest(XEvent *e) {
762 unsigned long newmask;
763 Client *c;
764 XConfigureRequestEvent *ev = &e->xconfigurerequest;
765 XWindowChanges wc;
767 if((c = getclient(ev->window))) {
768 c->ismax = False;
769 if(ev->value_mask & CWX)
770 c->x = ev->x;
771 if(ev->value_mask & CWY)
772 c->y = ev->y;
773 if(ev->value_mask & CWWidth)
774 c->w = ev->width;
775 if(ev->value_mask & CWHeight)
776 c->h = ev->height;
777 if(ev->value_mask & CWBorderWidth)
778 c->border = ev->border_width;
779 wc.x = c->x;
780 wc.y = c->y;
781 wc.width = c->w;
782 wc.height = c->h;
783 newmask = ev->value_mask & (~(CWSibling | CWStackMode | CWBorderWidth));
784 if(newmask)
785 XConfigureWindow(dpy, c->win, newmask, &wc);
786 else
787 configure(c);
788 XSync(dpy, False);
789 if(c->isfloat) {
790 resize(c, False);
791 if(!isvisible(c))
792 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
793 }
794 else
795 arrange();
796 } else {
797 wc.x = ev->x;
798 wc.y = ev->y;
799 wc.width = ev->width;
800 wc.height = ev->height;
801 wc.border_width = ev->border_width;
802 wc.sibling = ev->above;
803 wc.stack_mode = ev->detail;
804 XConfigureWindow(dpy, ev->window, ev->value_mask, &wc);
805 XSync(dpy, False);
806 }
807 }
809 static void
810 destroynotify(XEvent *e) {
811 Client *c;
812 XDestroyWindowEvent *ev = &e->xdestroywindow;
814 if((c = getclient(ev->window)))
815 unmanage(c);
816 }
818 static void
819 enternotify(XEvent *e) {
820 Client *c;
821 XCrossingEvent *ev = &e->xcrossing;
823 if(ev->mode != NotifyNormal || ev->detail == NotifyInferior)
824 return;
825 if((c = getclient(ev->window)) && isvisible(c))
826 focus(c);
827 else if(ev->window == root) {
828 selscreen = True;
829 for(c = stack; c && !isvisible(c); c = c->snext);
830 focus(c);
831 }
832 }
834 static void
835 expose(XEvent *e) {
836 XExposeEvent *ev = &e->xexpose;
838 if(ev->count == 0) {
839 if(barwin == ev->window)
840 drawstatus();
841 }
842 }
844 static void
845 keypress(XEvent *e) {
846 static unsigned int len = sizeof key / sizeof key[0];
847 unsigned int i;
848 KeySym keysym;
849 XKeyEvent *ev = &e->xkey;
851 keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
852 for(i = 0; i < len; i++) {
853 if(keysym == key[i].keysym && CLEANMASK(key[i].mod) == CLEANMASK(ev->state)) {
854 if(key[i].func)
855 key[i].func(key[i].cmd);
856 }
857 }
858 }
860 static void
861 leavenotify(XEvent *e) {
862 XCrossingEvent *ev = &e->xcrossing;
864 if((ev->window == root) && !ev->same_screen) {
865 selscreen = False;
866 focus(NULL);
867 }
868 }
870 static void
871 mappingnotify(XEvent *e) {
872 XMappingEvent *ev = &e->xmapping;
874 XRefreshKeyboardMapping(ev);
875 if(ev->request == MappingKeyboard)
876 grabkeys();
877 }
879 static void
880 maprequest(XEvent *e) {
881 static XWindowAttributes wa;
882 XMapRequestEvent *ev = &e->xmaprequest;
884 if(!XGetWindowAttributes(dpy, ev->window, &wa))
885 return;
886 if(wa.override_redirect) {
887 XSelectInput(dpy, ev->window,
888 (StructureNotifyMask | PropertyChangeMask));
889 return;
890 }
891 if(!getclient(ev->window))
892 manage(ev->window, &wa);
893 }
895 static void
896 propertynotify(XEvent *e) {
897 Client *c;
898 Window trans;
899 XPropertyEvent *ev = &e->xproperty;
901 if(ev->state == PropertyDelete)
902 return; /* ignore */
903 if((c = getclient(ev->window))) {
904 switch (ev->atom) {
905 default: break;
906 case XA_WM_TRANSIENT_FOR:
907 XGetTransientForHint(dpy, c->win, &trans);
908 if(!c->isfloat && (c->isfloat = (trans != 0)))
909 arrange();
910 break;
911 case XA_WM_NORMAL_HINTS:
912 updatesizehints(c);
913 break;
914 }
915 if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
916 updatetitle(c);
917 if(c == sel)
918 drawstatus();
919 }
920 }
921 }
923 static void
924 unmapnotify(XEvent *e) {
925 Client *c;
926 XUnmapEvent *ev = &e->xunmap;
928 if((c = getclient(ev->window)))
929 unmanage(c);
930 }
934 void (*handler[LASTEvent]) (XEvent *) = {
935 [ButtonPress] = buttonpress,
936 [ConfigureRequest] = configurerequest,
937 [DestroyNotify] = destroynotify,
938 [EnterNotify] = enternotify,
939 [LeaveNotify] = leavenotify,
940 [Expose] = expose,
941 [KeyPress] = keypress,
942 [MappingNotify] = mappingnotify,
943 [MapRequest] = maprequest,
944 [PropertyNotify] = propertynotify,
945 [UnmapNotify] = unmapnotify
946 };
948 void
949 grabkeys(void) {
950 static unsigned int len = sizeof key / sizeof key[0];
951 unsigned int i;
952 KeyCode code;
954 XUngrabKey(dpy, AnyKey, AnyModifier, root);
955 for(i = 0; i < len; i++) {
956 code = XKeysymToKeycode(dpy, key[i].keysym);
957 XGrabKey(dpy, code, key[i].mod, root, True,
958 GrabModeAsync, GrabModeAsync);
959 XGrabKey(dpy, code, key[i].mod | LockMask, root, True,
960 GrabModeAsync, GrabModeAsync);
961 XGrabKey(dpy, code, key[i].mod | numlockmask, root, True,
962 GrabModeAsync, GrabModeAsync);
963 XGrabKey(dpy, code, key[i].mod | numlockmask | LockMask, root, True,
964 GrabModeAsync, GrabModeAsync);
965 }
966 }
968 void
969 procevent(void) {
970 XEvent ev;
972 while(XPending(dpy)) {
973 XNextEvent(dpy, &ev);
974 if(handler[ev.type])
975 (handler[ev.type])(&ev); /* call handler */
976 }
977 }
993 /* from draw.c */
994 /* static */
996 static unsigned int
997 textnw(const char *text, unsigned int len) {
998 XRectangle r;
1000 if(dc.font.set) {
1001 XmbTextExtents(dc.font.set, text, len, NULL, &r);
1002 return r.width;
1004 return XTextWidth(dc.font.xfont, text, len);
1007 static void
1008 drawtext(const char *text, unsigned long col[ColLast]) {
1009 int x, y, w, h;
1010 static char buf[256];
1011 unsigned int len, olen;
1012 XGCValues gcv;
1013 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
1015 XSetForeground(dpy, dc.gc, col[ColBG]);
1016 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
1017 if(!text)
1018 return;
1019 w = 0;
1020 olen = len = strlen(text);
1021 if(len >= sizeof buf)
1022 len = sizeof buf - 1;
1023 memcpy(buf, text, len);
1024 buf[len] = 0;
1025 h = dc.font.ascent + dc.font.descent;
1026 y = dc.y + (dc.h / 2) - (h / 2) + dc.font.ascent;
1027 x = dc.x + (h / 2);
1028 /* shorten text if necessary */
1029 while(len && (w = textnw(buf, len)) > dc.w - h)
1030 buf[--len] = 0;
1031 if(len < olen) {
1032 if(len > 1)
1033 buf[len - 1] = '.';
1034 if(len > 2)
1035 buf[len - 2] = '.';
1036 if(len > 3)
1037 buf[len - 3] = '.';
1039 if(w > dc.w)
1040 return; /* too long */
1041 gcv.foreground = col[ColFG];
1042 if(dc.font.set) {
1043 XChangeGC(dpy, dc.gc, GCForeground, &gcv);
1044 XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
1045 } else {
1046 gcv.font = dc.font.xfont->fid;
1047 XChangeGC(dpy, dc.gc, GCForeground | GCFont, &gcv);
1048 XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
1054 void
1055 drawstatus(void) {
1056 int x;
1058 dc.x = dc.y = 0;
1059 dc.w = textw(NAMETAGGED);
1060 drawtext(NAMETAGGED, ( seltag ? dc.sel : dc.norm ));
1061 dc.x += dc.w + 1;
1062 dc.w = textw(NAMEUNTAGGED);
1063 drawtext(NAMEUNTAGGED, ( seltag ? dc.norm : dc.sel ));
1064 dc.x += dc.w + 1;
1065 dc.w = bmw;
1066 drawtext("", dc.norm);
1067 x = dc.x + dc.w;
1068 dc.w = textw(stext);
1069 dc.x = sw - dc.w;
1070 if(dc.x < x) {
1071 dc.x = x;
1072 dc.w = sw - x;
1074 drawtext(stext, dc.norm);
1075 if((dc.w = dc.x - x) > bh) {
1076 dc.x = x;
1077 drawtext(sel ? sel->name : NULL, dc.norm);
1079 XCopyArea(dpy, dc.drawable, barwin, dc.gc, 0, 0, sw, bh, 0, 0);
1080 XSync(dpy, False);
1083 unsigned long
1084 getcolor(const char *colstr) {
1085 Colormap cmap = DefaultColormap(dpy, screen);
1086 XColor color;
1088 if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
1089 eprint("error, cannot allocate color '%s'\n", colstr);
1090 return color.pixel;
1093 void
1094 setfont(const char *fontstr) {
1095 char *def, **missing;
1096 int i, n;
1098 missing = NULL;
1099 if(dc.font.set)
1100 XFreeFontSet(dpy, dc.font.set);
1101 dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
1102 if(missing) {
1103 while(n--)
1104 fprintf(stderr, "missing fontset: %s\n", missing[n]);
1105 XFreeStringList(missing);
1107 if(dc.font.set) {
1108 XFontSetExtents *font_extents;
1109 XFontStruct **xfonts;
1110 char **font_names;
1111 dc.font.ascent = dc.font.descent = 0;
1112 font_extents = XExtentsOfFontSet(dc.font.set);
1113 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
1114 for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
1115 if(dc.font.ascent < (*xfonts)->ascent)
1116 dc.font.ascent = (*xfonts)->ascent;
1117 if(dc.font.descent < (*xfonts)->descent)
1118 dc.font.descent = (*xfonts)->descent;
1119 xfonts++;
1121 } else {
1122 if(dc.font.xfont)
1123 XFreeFont(dpy, dc.font.xfont);
1124 dc.font.xfont = NULL;
1125 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr)))
1126 eprint("error, cannot load font: '%s'\n", fontstr);
1127 dc.font.ascent = dc.font.xfont->ascent;
1128 dc.font.descent = dc.font.xfont->descent;
1130 dc.font.height = dc.font.ascent + dc.font.descent;
1133 unsigned int
1134 textw(const char *text) {
1135 return textnw(text, strlen(text)) + dc.font.height;
1148 /* from client.c */
1149 /* static */
1151 static void
1152 detachstack(Client *c) {
1153 Client **tc;
1154 for(tc=&stack; *tc && *tc != c; tc=&(*tc)->snext);
1155 *tc = c->snext;
1158 static void
1159 grabbuttons(Client *c, Bool focused) {
1160 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1162 if(focused) {
1163 XGrabButton(dpy, Button1, MODKEY, c->win, False, BUTTONMASK,
1164 GrabModeAsync, GrabModeSync, None, None);
1165 XGrabButton(dpy, Button1, MODKEY | LockMask, c->win, False, BUTTONMASK,
1166 GrabModeAsync, GrabModeSync, None, None);
1167 XGrabButton(dpy, Button1, MODKEY | numlockmask, c->win, False, BUTTONMASK,
1168 GrabModeAsync, GrabModeSync, None, None);
1169 XGrabButton(dpy, Button1, MODKEY | numlockmask | LockMask, c->win, False, BUTTONMASK,
1170 GrabModeAsync, GrabModeSync, None, None);
1172 XGrabButton(dpy, Button2, MODKEY, c->win, False, BUTTONMASK,
1173 GrabModeAsync, GrabModeSync, None, None);
1174 XGrabButton(dpy, Button2, MODKEY | LockMask, c->win, False, BUTTONMASK,
1175 GrabModeAsync, GrabModeSync, None, None);
1176 XGrabButton(dpy, Button2, MODKEY | numlockmask, c->win, False, BUTTONMASK,
1177 GrabModeAsync, GrabModeSync, None, None);
1178 XGrabButton(dpy, Button2, MODKEY | numlockmask | LockMask, c->win, False, BUTTONMASK,
1179 GrabModeAsync, GrabModeSync, None, None);
1181 XGrabButton(dpy, Button3, MODKEY, c->win, False, BUTTONMASK,
1182 GrabModeAsync, GrabModeSync, None, None);
1183 XGrabButton(dpy, Button3, MODKEY | LockMask, c->win, False, BUTTONMASK,
1184 GrabModeAsync, GrabModeSync, None, None);
1185 XGrabButton(dpy, Button3, MODKEY | numlockmask, c->win, False, BUTTONMASK,
1186 GrabModeAsync, GrabModeSync, None, None);
1187 XGrabButton(dpy, Button3, MODKEY | numlockmask | LockMask, c->win, False, BUTTONMASK,
1188 GrabModeAsync, GrabModeSync, None, None);
1189 } else {
1190 XGrabButton(dpy, AnyButton, AnyModifier, c->win, False, BUTTONMASK,
1191 GrabModeAsync, GrabModeSync, None, None);
1195 static void
1196 setclientstate(Client *c, long state) {
1197 long data[] = {state, None};
1198 XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1199 PropModeReplace, (unsigned char *)data, 2);
1202 static int
1203 xerrordummy(Display *dsply, XErrorEvent *ee) {
1204 return 0;
1209 void
1210 configure(Client *c) {
1211 XEvent synev;
1213 synev.type = ConfigureNotify;
1214 synev.xconfigure.display = dpy;
1215 synev.xconfigure.event = c->win;
1216 synev.xconfigure.window = c->win;
1217 synev.xconfigure.x = c->x;
1218 synev.xconfigure.y = c->y;
1219 synev.xconfigure.width = c->w;
1220 synev.xconfigure.height = c->h;
1221 synev.xconfigure.border_width = c->border;
1222 synev.xconfigure.above = None;
1223 XSendEvent(dpy, c->win, True, NoEventMask, &synev);
1226 void
1227 focus(Client *c) {
1228 if(c && !isvisible(c))
1229 return;
1230 if(sel && sel != c) {
1231 grabbuttons(sel, False);
1232 XSetWindowBorder(dpy, sel->win, dc.norm[ColBG]);
1234 if(c) {
1235 detachstack(c);
1236 c->snext = stack;
1237 stack = c;
1238 grabbuttons(c, True);
1240 sel = c;
1241 drawstatus();
1242 if(!selscreen)
1243 return;
1244 if(c) {
1245 XSetWindowBorder(dpy, c->win, dc.sel[ColBG]);
1246 XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
1247 } else {
1248 XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
1252 Client *
1253 getclient(Window w) {
1254 Client *c;
1256 for(c = clients; c; c = c->next) {
1257 if(c->win == w) {
1258 return c;
1261 return NULL;
1264 Bool
1265 isprotodel(Client *c) {
1266 int i, n;
1267 Atom *protocols;
1268 Bool ret = False;
1270 if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
1271 for(i = 0; !ret && i < n; i++)
1272 if(protocols[i] == wmatom[WMDelete])
1273 ret = True;
1274 XFree(protocols);
1276 return ret;
1279 void
1280 killclient() {
1281 if(!sel)
1282 return;
1283 if(isprotodel(sel))
1284 sendevent(sel->win, wmatom[WMProtocols], wmatom[WMDelete]);
1285 else
1286 XKillClient(dpy, sel->win);
1289 void
1290 manage(Window w, XWindowAttributes *wa) {
1291 Client *c;
1292 Window trans;
1294 c = emallocz(sizeof(Client));
1295 c->tag = True;
1296 c->win = w;
1297 c->x = wa->x;
1298 c->y = wa->y;
1299 c->w = wa->width;
1300 c->h = wa->height;
1301 if(c->w == sw && c->h == sh) {
1302 c->border = 0;
1303 c->x = sx;
1304 c->y = sy;
1305 } else {
1306 c->border = BORDERPX;
1307 if(c->x + c->w + 2 * c->border > wax + waw)
1308 c->x = wax + waw - c->w - 2 * c->border;
1309 if(c->y + c->h + 2 * c->border > way + wah)
1310 c->y = way + wah - c->h - 2 * c->border;
1311 if(c->x < wax)
1312 c->x = wax;
1313 if(c->y < way)
1314 c->y = way;
1316 updatesizehints(c);
1317 XSelectInput(dpy, c->win,
1318 StructureNotifyMask | PropertyChangeMask | EnterWindowMask);
1319 XGetTransientForHint(dpy, c->win, &trans);
1320 grabbuttons(c, False);
1321 XSetWindowBorder(dpy, c->win, dc.norm[ColBG]);
1322 updatetitle(c);
1323 settag(c, getclient(trans));
1324 if(!c->isfloat)
1325 c->isfloat = trans || c->isfixed;
1326 if(clients)
1327 clients->prev = c;
1328 c->next = clients;
1329 c->snext = stack;
1330 stack = clients = c;
1331 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
1332 XMapWindow(dpy, c->win);
1333 setclientstate(c, NormalState);
1334 if(isvisible(c))
1335 focus(c);
1336 arrange();
1339 void
1340 resize(Client *c, Bool sizehints) {
1341 float actual, dx, dy, max, min;
1342 XWindowChanges wc;
1344 if(c->w <= 0 || c->h <= 0)
1345 return;
1346 if(sizehints) {
1347 if(c->minw && c->w < c->minw)
1348 c->w = c->minw;
1349 if(c->minh && c->h < c->minh)
1350 c->h = c->minh;
1351 if(c->maxw && c->w > c->maxw)
1352 c->w = c->maxw;
1353 if(c->maxh && c->h > c->maxh)
1354 c->h = c->maxh;
1355 /* inspired by algorithm from fluxbox */
1356 if(c->minay > 0 && c->maxay && (c->h - c->baseh) > 0) {
1357 dx = (float)(c->w - c->basew);
1358 dy = (float)(c->h - c->baseh);
1359 min = (float)(c->minax) / (float)(c->minay);
1360 max = (float)(c->maxax) / (float)(c->maxay);
1361 actual = dx / dy;
1362 if(max > 0 && min > 0 && actual > 0) {
1363 if(actual < min) {
1364 dy = (dx * min + dy) / (min * min + 1);
1365 dx = dy * min;
1366 c->w = (int)dx + c->basew;
1367 c->h = (int)dy + c->baseh;
1369 else if(actual > max) {
1370 dy = (dx * min + dy) / (max * max + 1);
1371 dx = dy * min;
1372 c->w = (int)dx + c->basew;
1373 c->h = (int)dy + c->baseh;
1377 if(c->incw)
1378 c->w -= (c->w - c->basew) % c->incw;
1379 if(c->inch)
1380 c->h -= (c->h - c->baseh) % c->inch;
1382 if(c->w == sw && c->h == sh)
1383 c->border = 0;
1384 else
1385 c->border = BORDERPX;
1386 /* offscreen appearance fixes */
1387 if(c->x > sw)
1388 c->x = sw - c->w - 2 * c->border;
1389 if(c->y > sh)
1390 c->y = sh - c->h - 2 * c->border;
1391 if(c->x + c->w + 2 * c->border < sx)
1392 c->x = sx;
1393 if(c->y + c->h + 2 * c->border < sy)
1394 c->y = sy;
1395 wc.x = c->x;
1396 wc.y = c->y;
1397 wc.width = c->w;
1398 wc.height = c->h;
1399 wc.border_width = c->border;
1400 XConfigureWindow(dpy, c->win, CWX | CWY | CWWidth | CWHeight | CWBorderWidth, &wc);
1401 configure(c);
1402 XSync(dpy, False);
1405 void
1406 updatesizehints(Client *c) {
1407 long msize;
1408 XSizeHints size;
1410 if(!XGetWMNormalHints(dpy, c->win, &size, &msize) || !size.flags)
1411 size.flags = PSize;
1412 c->flags = size.flags;
1413 if(c->flags & PBaseSize) {
1414 c->basew = size.base_width;
1415 c->baseh = size.base_height;
1416 } else {
1417 c->basew = c->baseh = 0;
1419 if(c->flags & PResizeInc) {
1420 c->incw = size.width_inc;
1421 c->inch = size.height_inc;
1422 } else {
1423 c->incw = c->inch = 0;
1425 if(c->flags & PMaxSize) {
1426 c->maxw = size.max_width;
1427 c->maxh = size.max_height;
1428 } else {
1429 c->maxw = c->maxh = 0;
1431 if(c->flags & PMinSize) {
1432 c->minw = size.min_width;
1433 c->minh = size.min_height;
1434 } else {
1435 c->minw = c->minh = 0;
1437 if(c->flags & PAspect) {
1438 c->minax = size.min_aspect.x;
1439 c->minay = size.min_aspect.y;
1440 c->maxax = size.max_aspect.x;
1441 c->maxay = size.max_aspect.y;
1442 } else {
1443 c->minax = c->minay = c->maxax = c->maxay = 0;
1445 c->isfixed = (c->maxw && c->minw && c->maxh && c->minh &&
1446 c->maxw == c->minw && c->maxh == c->minh);
1449 void
1450 updatetitle(Client *c) {
1451 char **list = NULL;
1452 int n;
1453 XTextProperty name;
1455 name.nitems = 0;
1456 c->name[0] = 0;
1457 XGetTextProperty(dpy, c->win, &name, netatom[NetWMName]);
1458 if(!name.nitems)
1459 XGetWMName(dpy, c->win, &name);
1460 if(!name.nitems)
1461 return;
1462 if(name.encoding == XA_STRING)
1463 strncpy(c->name, (char *)name.value, sizeof c->name);
1464 else {
1465 if(XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success && n > 0 && *list) {
1466 strncpy(c->name, *list, sizeof c->name);
1467 XFreeStringList(list);
1470 XFree(name.value);
1473 void
1474 unmanage(Client *c) {
1475 Client *nc;
1477 /* The server grab construct avoids race conditions. */
1478 XGrabServer(dpy);
1479 XSetErrorHandler(xerrordummy);
1480 detach(c);
1481 detachstack(c);
1482 if(sel == c) {
1483 for(nc = stack; nc && !isvisible(nc); nc = nc->snext);
1484 focus(nc);
1486 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1487 setclientstate(c, WithdrawnState);
1488 free(c);
1489 XSync(dpy, False);
1490 XSetErrorHandler(xerror);
1491 XUngrabServer(dpy);
1492 arrange();
1513 /* static */
1516 static void
1517 cleanup(void) {
1518 close(STDIN_FILENO);
1519 while(stack) {
1520 resize(stack, True);
1521 unmanage(stack);
1523 if(dc.font.set)
1524 XFreeFontSet(dpy, dc.font.set);
1525 else
1526 XFreeFont(dpy, dc.font.xfont);
1527 XUngrabKey(dpy, AnyKey, AnyModifier, root);
1528 XFreePixmap(dpy, dc.drawable);
1529 XFreeGC(dpy, dc.gc);
1530 XDestroyWindow(dpy, barwin);
1531 XFreeCursor(dpy, cursor[CurNormal]);
1532 XFreeCursor(dpy, cursor[CurResize]);
1533 XFreeCursor(dpy, cursor[CurMove]);
1534 XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime);
1535 XSync(dpy, False);
1538 static void
1539 scan(void) {
1540 unsigned int i, num;
1541 Window *wins, d1, d2;
1542 XWindowAttributes wa;
1544 wins = NULL;
1545 if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1546 for(i = 0; i < num; i++) {
1547 if(!XGetWindowAttributes(dpy, wins[i], &wa))
1548 continue;
1549 if(wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1550 continue;
1551 if(wa.map_state == IsViewable)
1552 manage(wins[i], &wa);
1555 if(wins)
1556 XFree(wins);
1559 static void
1560 setup(void) {
1561 int i, j;
1562 unsigned int mask;
1563 Window w;
1564 XModifierKeymap *modmap;
1565 XSetWindowAttributes wa;
1567 /* init atoms */
1568 wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1569 wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1570 wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1571 netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1572 netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1573 XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1574 PropModeReplace, (unsigned char *) netatom, NetLast);
1575 /* init cursors */
1576 cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1577 cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1578 cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1579 /* init modifier map */
1580 numlockmask = 0;
1581 modmap = XGetModifierMapping(dpy);
1582 for (i = 0; i < 8; i++) {
1583 for (j = 0; j < modmap->max_keypermod; j++) {
1584 if(modmap->modifiermap[i * modmap->max_keypermod + j] == XKeysymToKeycode(dpy, XK_Num_Lock))
1585 numlockmask = (1 << i);
1588 XFreeModifiermap(modmap);
1589 /* select for events */
1590 wa.event_mask = SubstructureRedirectMask | SubstructureNotifyMask
1591 | EnterWindowMask | LeaveWindowMask;
1592 wa.cursor = cursor[CurNormal];
1593 XChangeWindowAttributes(dpy, root, CWEventMask | CWCursor, &wa);
1594 grabkeys();
1595 initrregs();
1596 seltag = True;
1597 /* style */
1598 dc.norm[ColBG] = getcolor(NORMBGCOLOR);
1599 dc.norm[ColFG] = getcolor(NORMFGCOLOR);
1600 dc.sel[ColBG] = getcolor(SELBGCOLOR);
1601 dc.sel[ColFG] = getcolor(SELFGCOLOR);
1602 setfont(FONT);
1603 /* geometry */
1604 sx = sy = 0;
1605 sw = DisplayWidth(dpy, screen);
1606 sh = DisplayHeight(dpy, screen);
1607 nmaster = NMASTER;
1608 bmw = 1;
1609 /* bar */
1610 dc.h = bh = dc.font.height + 2;
1611 wa.override_redirect = 1;
1612 wa.background_pixmap = ParentRelative;
1613 wa.event_mask = ButtonPressMask | ExposureMask;
1614 barwin = XCreateWindow(dpy, root, sx, sy, sw, bh, 0,
1615 DefaultDepth(dpy, screen), CopyFromParent, DefaultVisual(dpy, screen),
1616 CWOverrideRedirect | CWBackPixmap | CWEventMask, &wa);
1617 XDefineCursor(dpy, barwin, cursor[CurNormal]);
1618 XMapRaised(dpy, barwin);
1619 strcpy(stext, "dwm-"VERSION);
1620 /* windowarea */
1621 wax = sx;
1622 way = sy + bh;
1623 wah = sh - bh;
1624 waw = sw;
1625 /* pixmap for everything */
1626 dc.drawable = XCreatePixmap(dpy, root, sw, bh, DefaultDepth(dpy, screen));
1627 dc.gc = XCreateGC(dpy, root, 0, 0);
1628 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
1629 /* multihead support */
1630 selscreen = XQueryPointer(dpy, root, &w, &w, &i, &i, &i, &i, &mask);
1633 /*
1634 * Startup Error handler to check if another window manager
1635 * is already running.
1636 */
1637 static int
1638 xerrorstart(Display *dsply, XErrorEvent *ee) {
1639 otherwm = True;
1640 return -1;
1645 void
1646 sendevent(Window w, Atom a, long value) {
1647 XEvent e;
1649 e.type = ClientMessage;
1650 e.xclient.window = w;
1651 e.xclient.message_type = a;
1652 e.xclient.format = 32;
1653 e.xclient.data.l[0] = value;
1654 e.xclient.data.l[1] = CurrentTime;
1655 XSendEvent(dpy, w, False, NoEventMask, &e);
1656 XSync(dpy, False);
1659 void
1660 quit() {
1661 readin = running = False;
1664 /* There's no way to check accesses to destroyed windows, thus those cases are
1665 * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
1666 * default error handler, which may call exit.
1667 */
1668 int
1669 xerror(Display *dpy, XErrorEvent *ee) {
1670 if(ee->error_code == BadWindow
1671 || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1672 || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1673 || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1674 || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1675 || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1676 || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1677 || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1678 return 0;
1679 fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1680 ee->request_code, ee->error_code);
1681 return xerrorxlib(dpy, ee); /* may call exit */
1684 int
1685 main(int argc, char *argv[]) {
1686 char *p;
1687 int r, xfd;
1688 fd_set rd;
1690 if(argc == 2 && !strncmp("-v", argv[1], 3)) {
1691 fputs("dwm-"VERSION", (C)opyright MMVI-MMVII Anselm R. Garbe\n", stdout);
1692 exit(EXIT_SUCCESS);
1693 } else if(argc != 1) {
1694 eprint("usage: dwm [-v]\n");
1696 setlocale(LC_CTYPE, "");
1697 dpy = XOpenDisplay(0);
1698 if(!dpy) {
1699 eprint("dwm: cannot open display\n");
1701 xfd = ConnectionNumber(dpy);
1702 screen = DefaultScreen(dpy);
1703 root = RootWindow(dpy, screen);
1704 otherwm = False;
1705 XSetErrorHandler(xerrorstart);
1706 /* this causes an error if some other window manager is running */
1707 XSelectInput(dpy, root, SubstructureRedirectMask);
1708 XSync(dpy, False);
1709 if(otherwm) {
1710 eprint("dwm: another window manager is already running\n");
1713 XSync(dpy, False);
1714 XSetErrorHandler(NULL);
1715 xerrorxlib = XSetErrorHandler(xerror);
1716 XSync(dpy, False);
1717 setup();
1718 drawstatus();
1719 scan();
1721 /* main event loop, also reads status text from stdin */
1722 XSync(dpy, False);
1723 procevent();
1724 readin = True;
1725 while(running) {
1726 FD_ZERO(&rd);
1727 if(readin)
1728 FD_SET(STDIN_FILENO, &rd);
1729 FD_SET(xfd, &rd);
1730 if(select(xfd + 1, &rd, NULL, NULL, NULL) == -1) {
1731 if(errno == EINTR)
1732 continue;
1733 eprint("select failed\n");
1735 if(FD_ISSET(STDIN_FILENO, &rd)) {
1736 switch(r = read(STDIN_FILENO, stext, sizeof stext - 1)) {
1737 case -1:
1738 strncpy(stext, strerror(errno), sizeof stext - 1);
1739 stext[sizeof stext - 1] = '\0';
1740 readin = False;
1741 break;
1742 case 0:
1743 strncpy(stext, "EOF", 4);
1744 readin = False;
1745 break;
1746 default:
1747 for(stext[r] = '\0', p = stext + strlen(stext) - 1; p >= stext && *p == '\n'; *p-- = '\0');
1748 for(; p >= stext && *p != '\n'; --p);
1749 if(p > stext)
1750 strncpy(stext, p + 1, sizeof stext);
1752 drawstatus();
1754 if(FD_ISSET(xfd, &rd))
1755 procevent();
1757 cleanup();
1758 XCloseDisplay(dpy);
1759 return 0;