aewl

view aewl.c @ 767:706991d15451

removed rexexp for old strstr matching; simplifications
author meillo@marmaro.de
date Fri, 05 Dec 2008 20:50:31 +0100
parents 3f7c68a720b5
children a1c6805aa018
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 <stdio.h>
48 #include <stdarg.h>
49 #include <stdlib.h>
50 #include <string.h>
51 #include <unistd.h>
52 #include <sys/select.h>
53 #include <sys/types.h>
54 #include <sys/wait.h>
55 #include <X11/cursorfont.h>
56 #include <X11/keysym.h>
57 #include <X11/Xatom.h>
58 #include <X11/Xlib.h>
59 #include <X11/Xproto.h>
60 #include <X11/Xutil.h>
62 /* mask shorthands, used in event.c and client.c */
63 #define BUTTONMASK (ButtonPressMask | ButtonReleaseMask)
65 enum { NetSupported, NetWMName, NetLast }; /* EWMH atoms */
66 enum { WMProtocols, WMDelete, WMState, WMLast }; /* default atoms */
67 enum { CurNormal, CurResize, CurMove, CurLast }; /* cursor */
68 enum { ColFG, ColBG, ColLast }; /* color */
70 typedef struct {
71 int ascent;
72 int descent;
73 int height;
74 XFontSet set;
75 XFontStruct *xfont;
76 } Fnt;
78 typedef struct {
79 int x, y, w, h;
80 unsigned long norm[ColLast];
81 unsigned long sel[ColLast];
82 Drawable drawable;
83 Fnt font;
84 GC gc;
85 } DC; /* draw context */
87 typedef struct Client Client;
88 struct Client {
89 char name[256];
90 int x, y, w, h;
91 int rx, ry, rw, rh; /* revert geometry */
92 int basew, baseh, incw, inch, maxw, maxh, minw, minh;
93 int minax, minay, maxax, maxay;
94 long flags;
95 unsigned int border;
96 Bool isfixed, isfloat, ismax;
97 Bool tag;
98 Client *next;
99 Client *prev;
100 Client *snext;
101 Window win;
102 };
104 typedef struct {
105 const char* class;
106 const char* instance;
107 const char* title;
108 int tag;
109 Bool isfloat;
110 } Rule;
113 typedef struct {
114 unsigned long mod;
115 KeySym keysym;
116 void (*func)(const char* cmd);
117 const char* cmd;
118 } Key;
121 #define CLEANMASK(mask) (mask & ~(numlockmask | LockMask))
122 #define MOUSEMASK (BUTTONMASK | PointerMotionMask)
126 char stext[256]; /* status text */
127 int bh, bmw; /* bar height, bar mode label width */
128 int screen, sx, sy, sw, sh; /* screen geometry */
129 int wax, way, wah, waw; /* windowarea geometry */
130 unsigned int nmaster; /* number of master clients */
131 unsigned int numlockmask; /* dynamic lock mask */
132 void (*handler[LASTEvent])(XEvent *); /* event handler */
133 void (*arrange)(void); /* arrange function, indicates mode */
134 Atom wmatom[WMLast], netatom[NetLast];
135 Bool running, selscreen, seltag;
136 Client *clients, *sel, *stack; /* global client list and stack */
137 Cursor cursor[CurLast];
138 DC dc; /* global draw context */
139 Display *dpy;
140 Window root, barwin;
142 Bool running = True;
143 Bool selscreen = True;
144 Client *clients = NULL;
145 Client *sel = NULL;
146 Client *stack = NULL;
147 DC dc = {0};
149 static int (*xerrorxlib)(Display *, XErrorEvent *);
150 static Bool otherwm, readin;
151 static unsigned int len = 0;
154 RULES
157 /* client.c */
158 void configure(Client *c); /* send synthetic configure event */
159 void focus(Client *c); /* focus c, c may be NULL */
160 Client *getclient(Window w); /* return client of w */
161 Bool isprotodel(Client *c); /* returns True if c->win supports wmatom[WMDelete] */
162 void manage(Window w, XWindowAttributes *wa); /* manage new client */
163 void resize(Client *c, Bool sizehints); /* resize c*/
164 void updatesizehints(Client *c); /* update the size hint variables of c */
165 void updatetitle(Client *c); /* update the name of c */
166 void unmanage(Client *c); /* destroy c */
168 /* draw.c */
169 void drawstatus(void); /* draw the bar */
170 unsigned long getcolor(const char *colstr); /* return color of colstr */
171 void setfont(const char *fontstr); /* set the font for DC */
172 unsigned int textw(const char *text); /* return the width of text in px*/
174 /* event.c */
175 void grabkeys(void); /* grab all keys defined in config.h */
176 void procevent(void); /* process pending X events */
178 /* main.c */
179 void sendevent(Window w, Atom a, long value); /* send synthetic event to w */
180 int xerror(Display *dsply, XErrorEvent *ee); /* dwm's X error handler */
182 /* tag.c */
183 Client *getnext(Client *c); /* returns next visible client */
184 void settag(Client *c, Client *trans); /* sets tag of c */
186 /* util.c */
187 void *emallocz(unsigned int size); /* allocates zero-initialized memory, exits on error */
188 void eprint(const char *errstr, ...); /* prints errstr and exits with 1 */
190 /* view.c */
191 void detach(Client *c); /* detaches c from global client list */
192 void dotile(void); /* arranges all windows tiled */
193 void domax(void); /* arranges all windows fullscreen */
194 Bool isvisible(Client *c); /* returns True if client is visible */
195 void restack(void); /* restores z layers of all clients */
198 void toggleview(void); /* toggle the view */
199 void focusnext(void); /* focuses next visible client */
200 void zoom(void); /* zooms the focused client to master area */
201 void killclient(void); /* kill c nicely */
202 void quit(void); /* quit dwm nicely */
203 void togglemode(void); /* toggles global arrange function (dotile/domax) */
204 void togglefloat(void); /* toggles focusesd client between floating/non-floating state */
205 void incnmaster(void); /* increments nmaster */
206 void decnmaster(void); /* decrements nmaster */
207 void toggletag(void); /* toggles tag of c */
208 void spawn(const char* cmd); /* forks a new subprocess with cmd */
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 dotile(void) {
268 unsigned int i, n, mw, mh, tw, th;
269 Client *c;
271 for(n = 0, c = nexttiled(clients); c; c = nexttiled(c->next))
272 n++;
273 /* window geoms */
274 mh = (n > nmaster) ? wah / nmaster : wah / (n > 0 ? n : 1);
275 mw = (n > nmaster) ? waw / 2 : waw;
276 th = (n > nmaster) ? wah / (n - nmaster) : 0;
277 tw = waw - mw;
279 for(i = 0, c = clients; c; c = c->next)
280 if(isvisible(c)) {
281 if(c->isfloat) {
282 resize(c, True);
283 continue;
284 }
285 c->ismax = False;
286 c->x = wax;
287 c->y = way;
288 if(i < nmaster) {
289 c->y += i * mh;
290 c->w = mw - 2 * BORDERPX;
291 c->h = mh - 2 * BORDERPX;
292 }
293 else { /* tile window */
294 c->x += mw;
295 c->w = tw - 2 * BORDERPX;
296 if(th > 2 * BORDERPX) {
297 c->y += (i - nmaster) * th;
298 c->h = th - 2 * BORDERPX;
299 }
300 else /* fallback if th <= 2 * BORDERPX */
301 c->h = wah - 2 * BORDERPX;
302 }
303 resize(c, False);
304 i++;
305 }
306 else
307 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
308 if(!sel || !isvisible(sel)) {
309 for(c = stack; c && !isvisible(c); c = c->snext);
310 focus(c);
311 }
312 restack();
313 }
315 /* begin code by mitch */
316 void
317 arrangemax(Client *c) {
318 if(c == sel) {
319 c->ismax = True;
320 c->x = sx;
321 c->y = bh;
322 c->w = sw - 2 * BORDERPX;
323 c->h = sh - bh - 2 * BORDERPX;
324 XRaiseWindow(dpy, c->win);
325 } else {
326 c->ismax = False;
327 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
328 XLowerWindow(dpy, c->win);
329 }
330 }
332 void
333 domax(void) {
334 Client *c;
336 for(c = clients; c; c = c->next) {
337 if(isvisible(c)) {
338 if(c->isfloat) {
339 resize(c, True);
340 continue;
341 }
342 arrangemax(c);
343 resize(c, False);
344 } else {
345 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
346 }
348 }
349 if(!sel || !isvisible(sel)) {
350 for(c = stack; c && !isvisible(c); c = c->snext);
351 focus(c);
352 }
353 restack();
354 }
355 /* end code by mitch */
357 void
358 focusnext() {
359 Client *c;
361 if(!sel)
362 return;
363 if(!(c = getnext(sel->next)))
364 c = getnext(clients);
365 if(c) {
366 focus(c);
367 restack();
368 }
369 }
371 void
372 incnmaster() {
373 if(wah / (nmaster + 1) <= 2 * BORDERPX)
374 return;
375 nmaster++;
376 if(sel)
377 arrange();
378 else
379 drawstatus();
380 }
382 void
383 decnmaster() {
384 if(nmaster <= 1)
385 return;
386 nmaster--;
387 if(sel)
388 arrange();
389 else
390 drawstatus();
391 }
393 Bool
394 isvisible(Client *c) {
395 return (c->tag == seltag);
396 }
398 void
399 restack(void) {
400 Client *c;
401 XEvent ev;
403 drawstatus();
404 if(!sel)
405 return;
406 if(sel->isfloat)
407 XRaiseWindow(dpy, sel->win);
409 /* begin code by mitch */
410 if(arrange == domax) {
411 for(c = nexttiled(clients); c; c = nexttiled(c->next)) {
412 arrangemax(c);
413 resize(c, False);
414 }
416 } else if (arrange == dotile) {
417 /* end code by mitch */
419 if(!sel->isfloat)
420 XLowerWindow(dpy, sel->win);
421 for(c = nexttiled(clients); c; c = nexttiled(c->next)) {
422 if(c == sel)
423 continue;
424 XLowerWindow(dpy, c->win);
425 }
426 }
427 XSync(dpy, False);
428 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
429 }
431 void
432 togglefloat() {
433 if (!sel)
434 return;
435 sel->isfloat = !sel->isfloat;
436 arrange();
437 }
439 void
440 togglemode() {
441 /* only toggle between tile and max - float is just available through togglefloat */
442 arrange = (arrange == dotile) ? domax : dotile;
443 if(sel)
444 arrange();
445 else
446 drawstatus();
447 }
449 void
450 toggleview() {
451 seltag = !seltag;
452 arrange();
453 }
455 void
456 zoom() {
457 unsigned int n;
458 Client *c;
460 if(!sel)
461 return;
462 if(sel->isfloat) {
463 togglemax(sel);
464 return;
465 }
466 for(n = 0, c = nexttiled(clients); c; c = nexttiled(c->next))
467 n++;
469 if((c = sel) == nexttiled(clients))
470 if(!(c = nexttiled(c->next)))
471 return;
472 detach(c);
473 if(clients)
474 clients->prev = c;
475 c->next = clients;
476 clients = c;
477 focus(c);
478 arrange();
479 }
496 /* from util.c */
499 void *
500 emallocz(unsigned int size) {
501 void *res = calloc(1, size);
503 if(!res)
504 eprint("fatal: could not malloc() %u bytes\n", size);
505 return res;
506 }
508 void
509 eprint(const char *errstr, ...) {
510 va_list ap;
512 va_start(ap, errstr);
513 vfprintf(stderr, errstr, ap);
514 va_end(ap);
515 exit(EXIT_FAILURE);
516 }
518 void
519 spawn(const char* cmd) {
520 static char *shell = NULL;
522 if(!shell && !(shell = getenv("SHELL")))
523 shell = "/bin/sh";
524 if(!cmd)
525 return;
526 /* The double-fork construct avoids zombie processes and keeps the code
527 * clean from stupid signal handlers. */
528 if(fork() == 0) {
529 if(fork() == 0) {
530 if(dpy)
531 close(ConnectionNumber(dpy));
532 setsid();
533 execl(shell, shell, "-c", cmd, (char *)NULL);
534 fprintf(stderr, "dwm: execl '%s -c %s'", shell, cmd);
535 perror(" failed");
536 }
537 exit(0);
538 }
539 wait(0);
540 }
554 /* from tag.c */
556 /* static */
558 Client *
559 getnext(Client *c) {
560 for(; c && !isvisible(c); c = c->next);
561 return c;
562 }
564 void
565 settag(Client *c, Client *trans) {
566 unsigned int i;
567 XClassHint ch = { 0 };
569 if(trans) {
570 c->tag = trans->tag;
571 return;
572 }
573 c->tag = seltag; /* default */
574 XGetClassHint(dpy, c->win, &ch);
575 len = sizeof rule / sizeof rule[0];
576 for(i = 0; i < len; i++) {
577 if((rule[i].title && strstr(c->name, rule[i].title))
578 || (ch.res_class && rule[i].class && strstr(ch.res_class, rule[i].class))
579 || (ch.res_name && rule[i].instance && strstr(ch.res_name, rule[i].instance))) {
580 c->isfloat = rule[i].isfloat;
581 if (rule[i].tag < 0) {
582 c->tag = seltag;
583 } else if (rule[i].tag) {
584 c->tag = True;
585 } else {
586 c->tag = False;
587 }
588 break;
589 }
590 }
591 if(ch.res_class)
592 XFree(ch.res_class);
593 if(ch.res_name)
594 XFree(ch.res_name);
595 }
597 void
598 toggletag() {
599 if(!sel)
600 return;
601 sel->tag = !sel->tag;
602 toggleview();
603 }
621 /* from event.c */
622 /* static */
624 KEYS
628 static void
629 movemouse(Client *c) {
630 int x1, y1, ocx, ocy, di;
631 unsigned int dui;
632 Window dummy;
633 XEvent ev;
635 ocx = c->x;
636 ocy = c->y;
637 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
638 None, cursor[CurMove], CurrentTime) != GrabSuccess)
639 return;
640 c->ismax = False;
641 XQueryPointer(dpy, root, &dummy, &dummy, &x1, &y1, &di, &di, &dui);
642 for(;;) {
643 XMaskEvent(dpy, MOUSEMASK | ExposureMask | SubstructureRedirectMask, &ev);
644 switch (ev.type) {
645 case ButtonRelease:
646 resize(c, True);
647 XUngrabPointer(dpy, CurrentTime);
648 return;
649 case ConfigureRequest:
650 case Expose:
651 case MapRequest:
652 handler[ev.type](&ev);
653 break;
654 case MotionNotify:
655 XSync(dpy, False);
656 c->x = ocx + (ev.xmotion.x - x1);
657 c->y = ocy + (ev.xmotion.y - y1);
658 if(abs(wax + c->x) < SNAP)
659 c->x = wax;
660 else if(abs((wax + waw) - (c->x + c->w + 2 * c->border)) < SNAP)
661 c->x = wax + waw - c->w - 2 * c->border;
662 if(abs(way - c->y) < SNAP)
663 c->y = way;
664 else if(abs((way + wah) - (c->y + c->h + 2 * c->border)) < SNAP)
665 c->y = way + wah - c->h - 2 * c->border;
666 resize(c, False);
667 break;
668 }
669 }
670 }
672 static void
673 resizemouse(Client *c) {
674 int ocx, ocy;
675 int nw, nh;
676 XEvent ev;
678 ocx = c->x;
679 ocy = c->y;
680 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
681 None, cursor[CurResize], CurrentTime) != GrabSuccess)
682 return;
683 c->ismax = False;
684 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->border - 1, c->h + c->border - 1);
685 for(;;) {
686 XMaskEvent(dpy, MOUSEMASK | ExposureMask | SubstructureRedirectMask , &ev);
687 switch(ev.type) {
688 case ButtonRelease:
689 resize(c, True);
690 XUngrabPointer(dpy, CurrentTime);
691 return;
692 case ConfigureRequest:
693 case Expose:
694 case MapRequest:
695 handler[ev.type](&ev);
696 break;
697 case MotionNotify:
698 XSync(dpy, False);
699 nw = ev.xmotion.x - ocx - 2 * c->border + 1;
700 c->w = nw > 0 ? nw : 1;
701 nh = ev.xmotion.y - ocy - 2 * c->border + 1;
702 c->h = nh > 0 ? nh : 1;
703 resize(c, True);
704 break;
705 }
706 }
707 }
709 static void
710 buttonpress(XEvent *e) {
711 Client *c;
712 XButtonPressedEvent *ev = &e->xbutton;
714 if(barwin == ev->window) {
715 return;
716 }
717 if((c = getclient(ev->window))) {
718 focus(c);
719 if(CLEANMASK(ev->state) != MODKEY)
720 return;
721 if(ev->button == Button1 && c->isfloat) {
722 restack();
723 movemouse(c);
724 } else if(ev->button == Button3 && c->isfloat && !c->isfixed) {
725 restack();
726 resizemouse(c);
727 }
728 }
729 }
731 static void
732 configurerequest(XEvent *e) {
733 unsigned long newmask;
734 Client *c;
735 XConfigureRequestEvent *ev = &e->xconfigurerequest;
736 XWindowChanges wc;
738 if((c = getclient(ev->window))) {
739 c->ismax = False;
740 if(ev->value_mask & CWX)
741 c->x = ev->x;
742 if(ev->value_mask & CWY)
743 c->y = ev->y;
744 if(ev->value_mask & CWWidth)
745 c->w = ev->width;
746 if(ev->value_mask & CWHeight)
747 c->h = ev->height;
748 if(ev->value_mask & CWBorderWidth)
749 c->border = ev->border_width;
750 wc.x = c->x;
751 wc.y = c->y;
752 wc.width = c->w;
753 wc.height = c->h;
754 newmask = ev->value_mask & (~(CWSibling | CWStackMode | CWBorderWidth));
755 if(newmask)
756 XConfigureWindow(dpy, c->win, newmask, &wc);
757 else
758 configure(c);
759 XSync(dpy, False);
760 if(c->isfloat) {
761 resize(c, False);
762 if(!isvisible(c))
763 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
764 }
765 else
766 arrange();
767 } else {
768 wc.x = ev->x;
769 wc.y = ev->y;
770 wc.width = ev->width;
771 wc.height = ev->height;
772 wc.border_width = ev->border_width;
773 wc.sibling = ev->above;
774 wc.stack_mode = ev->detail;
775 XConfigureWindow(dpy, ev->window, ev->value_mask, &wc);
776 XSync(dpy, False);
777 }
778 }
780 static void
781 destroynotify(XEvent *e) {
782 Client *c;
783 XDestroyWindowEvent *ev = &e->xdestroywindow;
785 if((c = getclient(ev->window)))
786 unmanage(c);
787 }
789 static void
790 enternotify(XEvent *e) {
791 Client *c;
792 XCrossingEvent *ev = &e->xcrossing;
794 if(ev->mode != NotifyNormal || ev->detail == NotifyInferior)
795 return;
796 if((c = getclient(ev->window)) && isvisible(c))
797 focus(c);
798 else if(ev->window == root) {
799 selscreen = True;
800 for(c = stack; c && !isvisible(c); c = c->snext);
801 focus(c);
802 }
803 }
805 static void
806 expose(XEvent *e) {
807 XExposeEvent *ev = &e->xexpose;
809 if(ev->count == 0) {
810 if(barwin == ev->window)
811 drawstatus();
812 }
813 }
815 static void
816 keypress(XEvent *e) {
817 static unsigned int len = sizeof key / sizeof key[0];
818 unsigned int i;
819 KeySym keysym;
820 XKeyEvent *ev = &e->xkey;
822 keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
823 for(i = 0; i < len; i++) {
824 if(keysym == key[i].keysym && CLEANMASK(key[i].mod) == CLEANMASK(ev->state)) {
825 if(key[i].func)
826 key[i].func(key[i].cmd);
827 }
828 }
829 }
831 static void
832 leavenotify(XEvent *e) {
833 XCrossingEvent *ev = &e->xcrossing;
835 if((ev->window == root) && !ev->same_screen) {
836 selscreen = False;
837 focus(NULL);
838 }
839 }
841 static void
842 mappingnotify(XEvent *e) {
843 XMappingEvent *ev = &e->xmapping;
845 XRefreshKeyboardMapping(ev);
846 if(ev->request == MappingKeyboard)
847 grabkeys();
848 }
850 static void
851 maprequest(XEvent *e) {
852 static XWindowAttributes wa;
853 XMapRequestEvent *ev = &e->xmaprequest;
855 if(!XGetWindowAttributes(dpy, ev->window, &wa))
856 return;
857 if(wa.override_redirect) {
858 XSelectInput(dpy, ev->window,
859 (StructureNotifyMask | PropertyChangeMask));
860 return;
861 }
862 if(!getclient(ev->window))
863 manage(ev->window, &wa);
864 }
866 static void
867 propertynotify(XEvent *e) {
868 Client *c;
869 Window trans;
870 XPropertyEvent *ev = &e->xproperty;
872 if(ev->state == PropertyDelete)
873 return; /* ignore */
874 if((c = getclient(ev->window))) {
875 switch (ev->atom) {
876 default: break;
877 case XA_WM_TRANSIENT_FOR:
878 XGetTransientForHint(dpy, c->win, &trans);
879 if(!c->isfloat && (c->isfloat = (trans != 0)))
880 arrange();
881 break;
882 case XA_WM_NORMAL_HINTS:
883 updatesizehints(c);
884 break;
885 }
886 if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
887 updatetitle(c);
888 if(c == sel)
889 drawstatus();
890 }
891 }
892 }
894 static void
895 unmapnotify(XEvent *e) {
896 Client *c;
897 XUnmapEvent *ev = &e->xunmap;
899 if((c = getclient(ev->window)))
900 unmanage(c);
901 }
905 void (*handler[LASTEvent]) (XEvent *) = {
906 [ButtonPress] = buttonpress,
907 [ConfigureRequest] = configurerequest,
908 [DestroyNotify] = destroynotify,
909 [EnterNotify] = enternotify,
910 [LeaveNotify] = leavenotify,
911 [Expose] = expose,
912 [KeyPress] = keypress,
913 [MappingNotify] = mappingnotify,
914 [MapRequest] = maprequest,
915 [PropertyNotify] = propertynotify,
916 [UnmapNotify] = unmapnotify
917 };
919 void
920 grabkeys(void) {
921 static unsigned int len = sizeof key / sizeof key[0];
922 unsigned int i;
923 KeyCode code;
925 XUngrabKey(dpy, AnyKey, AnyModifier, root);
926 for(i = 0; i < len; i++) {
927 code = XKeysymToKeycode(dpy, key[i].keysym);
928 XGrabKey(dpy, code, key[i].mod, root, True,
929 GrabModeAsync, GrabModeAsync);
930 XGrabKey(dpy, code, key[i].mod | LockMask, root, True,
931 GrabModeAsync, GrabModeAsync);
932 XGrabKey(dpy, code, key[i].mod | numlockmask, root, True,
933 GrabModeAsync, GrabModeAsync);
934 XGrabKey(dpy, code, key[i].mod | numlockmask | LockMask, root, True,
935 GrabModeAsync, GrabModeAsync);
936 }
937 }
939 void
940 procevent(void) {
941 XEvent ev;
943 while(XPending(dpy)) {
944 XNextEvent(dpy, &ev);
945 if(handler[ev.type])
946 (handler[ev.type])(&ev); /* call handler */
947 }
948 }
964 /* from draw.c */
965 /* static */
967 static unsigned int
968 textnw(const char *text, unsigned int len) {
969 XRectangle r;
971 if(dc.font.set) {
972 XmbTextExtents(dc.font.set, text, len, NULL, &r);
973 return r.width;
974 }
975 return XTextWidth(dc.font.xfont, text, len);
976 }
978 static void
979 drawtext(const char *text, unsigned long col[ColLast]) {
980 int x, y, w, h;
981 static char buf[256];
982 unsigned int len, olen;
983 XGCValues gcv;
984 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
986 XSetForeground(dpy, dc.gc, col[ColBG]);
987 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
988 if(!text)
989 return;
990 w = 0;
991 olen = len = strlen(text);
992 if(len >= sizeof buf)
993 len = sizeof buf - 1;
994 memcpy(buf, text, len);
995 buf[len] = 0;
996 h = dc.font.ascent + dc.font.descent;
997 y = dc.y + (dc.h / 2) - (h / 2) + dc.font.ascent;
998 x = dc.x + (h / 2);
999 /* shorten text if necessary */
1000 while(len && (w = textnw(buf, len)) > dc.w - h)
1001 buf[--len] = 0;
1002 if(len < olen) {
1003 if(len > 1)
1004 buf[len - 1] = '.';
1005 if(len > 2)
1006 buf[len - 2] = '.';
1007 if(len > 3)
1008 buf[len - 3] = '.';
1010 if(w > dc.w)
1011 return; /* too long */
1012 gcv.foreground = col[ColFG];
1013 if(dc.font.set) {
1014 XChangeGC(dpy, dc.gc, GCForeground, &gcv);
1015 XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
1016 } else {
1017 gcv.font = dc.font.xfont->fid;
1018 XChangeGC(dpy, dc.gc, GCForeground | GCFont, &gcv);
1019 XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
1025 void
1026 drawstatus(void) {
1027 int x;
1029 dc.x = dc.y = 0;
1030 dc.w = textw(NAMETAGGED);
1031 drawtext(NAMETAGGED, ( seltag ? dc.sel : dc.norm ));
1032 dc.x += dc.w + 1;
1033 dc.w = textw(NAMEUNTAGGED);
1034 drawtext(NAMEUNTAGGED, ( seltag ? dc.norm : dc.sel ));
1035 dc.x += dc.w + 1;
1036 dc.w = bmw;
1037 drawtext("", dc.norm);
1038 x = dc.x + dc.w;
1039 dc.w = textw(stext);
1040 dc.x = sw - dc.w;
1041 if(dc.x < x) {
1042 dc.x = x;
1043 dc.w = sw - x;
1045 drawtext(stext, dc.norm);
1046 if((dc.w = dc.x - x) > bh) {
1047 dc.x = x;
1048 drawtext(sel ? sel->name : NULL, dc.norm);
1050 XCopyArea(dpy, dc.drawable, barwin, dc.gc, 0, 0, sw, bh, 0, 0);
1051 XSync(dpy, False);
1054 unsigned long
1055 getcolor(const char *colstr) {
1056 Colormap cmap = DefaultColormap(dpy, screen);
1057 XColor color;
1059 if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
1060 eprint("error, cannot allocate color '%s'\n", colstr);
1061 return color.pixel;
1064 void
1065 setfont(const char *fontstr) {
1066 char *def, **missing;
1067 int i, n;
1069 missing = NULL;
1070 if(dc.font.set)
1071 XFreeFontSet(dpy, dc.font.set);
1072 dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
1073 if(missing) {
1074 while(n--)
1075 fprintf(stderr, "missing fontset: %s\n", missing[n]);
1076 XFreeStringList(missing);
1078 if(dc.font.set) {
1079 XFontSetExtents *font_extents;
1080 XFontStruct **xfonts;
1081 char **font_names;
1082 dc.font.ascent = dc.font.descent = 0;
1083 font_extents = XExtentsOfFontSet(dc.font.set);
1084 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
1085 for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
1086 if(dc.font.ascent < (*xfonts)->ascent)
1087 dc.font.ascent = (*xfonts)->ascent;
1088 if(dc.font.descent < (*xfonts)->descent)
1089 dc.font.descent = (*xfonts)->descent;
1090 xfonts++;
1092 } else {
1093 if(dc.font.xfont)
1094 XFreeFont(dpy, dc.font.xfont);
1095 dc.font.xfont = NULL;
1096 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr)))
1097 eprint("error, cannot load font: '%s'\n", fontstr);
1098 dc.font.ascent = dc.font.xfont->ascent;
1099 dc.font.descent = dc.font.xfont->descent;
1101 dc.font.height = dc.font.ascent + dc.font.descent;
1104 unsigned int
1105 textw(const char *text) {
1106 return textnw(text, strlen(text)) + dc.font.height;
1119 /* from client.c */
1120 /* static */
1122 static void
1123 detachstack(Client *c) {
1124 Client **tc;
1125 for(tc=&stack; *tc && *tc != c; tc=&(*tc)->snext);
1126 *tc = c->snext;
1129 static void
1130 grabbuttons(Client *c, Bool focused) {
1131 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1133 if(focused) {
1134 XGrabButton(dpy, Button1, MODKEY, c->win, False, BUTTONMASK,
1135 GrabModeAsync, GrabModeSync, None, None);
1136 XGrabButton(dpy, Button1, MODKEY | LockMask, c->win, False, BUTTONMASK,
1137 GrabModeAsync, GrabModeSync, None, None);
1138 XGrabButton(dpy, Button1, MODKEY | numlockmask, c->win, False, BUTTONMASK,
1139 GrabModeAsync, GrabModeSync, None, None);
1140 XGrabButton(dpy, Button1, MODKEY | numlockmask | LockMask, c->win, False, BUTTONMASK,
1141 GrabModeAsync, GrabModeSync, None, None);
1143 XGrabButton(dpy, Button2, MODKEY, c->win, False, BUTTONMASK,
1144 GrabModeAsync, GrabModeSync, None, None);
1145 XGrabButton(dpy, Button2, MODKEY | LockMask, c->win, False, BUTTONMASK,
1146 GrabModeAsync, GrabModeSync, None, None);
1147 XGrabButton(dpy, Button2, MODKEY | numlockmask, c->win, False, BUTTONMASK,
1148 GrabModeAsync, GrabModeSync, None, None);
1149 XGrabButton(dpy, Button2, MODKEY | numlockmask | LockMask, c->win, False, BUTTONMASK,
1150 GrabModeAsync, GrabModeSync, None, None);
1152 XGrabButton(dpy, Button3, MODKEY, c->win, False, BUTTONMASK,
1153 GrabModeAsync, GrabModeSync, None, None);
1154 XGrabButton(dpy, Button3, MODKEY | LockMask, c->win, False, BUTTONMASK,
1155 GrabModeAsync, GrabModeSync, None, None);
1156 XGrabButton(dpy, Button3, MODKEY | numlockmask, c->win, False, BUTTONMASK,
1157 GrabModeAsync, GrabModeSync, None, None);
1158 XGrabButton(dpy, Button3, MODKEY | numlockmask | LockMask, c->win, False, BUTTONMASK,
1159 GrabModeAsync, GrabModeSync, None, None);
1160 } else {
1161 XGrabButton(dpy, AnyButton, AnyModifier, c->win, False, BUTTONMASK,
1162 GrabModeAsync, GrabModeSync, None, None);
1166 static void
1167 setclientstate(Client *c, long state) {
1168 long data[] = {state, None};
1169 XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1170 PropModeReplace, (unsigned char *)data, 2);
1173 static int
1174 xerrordummy(Display *dsply, XErrorEvent *ee) {
1175 return 0;
1180 void
1181 configure(Client *c) {
1182 XEvent synev;
1184 synev.type = ConfigureNotify;
1185 synev.xconfigure.display = dpy;
1186 synev.xconfigure.event = c->win;
1187 synev.xconfigure.window = c->win;
1188 synev.xconfigure.x = c->x;
1189 synev.xconfigure.y = c->y;
1190 synev.xconfigure.width = c->w;
1191 synev.xconfigure.height = c->h;
1192 synev.xconfigure.border_width = c->border;
1193 synev.xconfigure.above = None;
1194 XSendEvent(dpy, c->win, True, NoEventMask, &synev);
1197 void
1198 focus(Client *c) {
1199 if(c && !isvisible(c))
1200 return;
1201 if(sel && sel != c) {
1202 grabbuttons(sel, False);
1203 XSetWindowBorder(dpy, sel->win, dc.norm[ColBG]);
1205 if(c) {
1206 detachstack(c);
1207 c->snext = stack;
1208 stack = c;
1209 grabbuttons(c, True);
1211 sel = c;
1212 drawstatus();
1213 if(!selscreen)
1214 return;
1215 if(c) {
1216 XSetWindowBorder(dpy, c->win, dc.sel[ColBG]);
1217 XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
1218 } else {
1219 XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
1223 Client *
1224 getclient(Window w) {
1225 Client *c;
1227 for(c = clients; c; c = c->next) {
1228 if(c->win == w) {
1229 return c;
1232 return NULL;
1235 Bool
1236 isprotodel(Client *c) {
1237 int i, n;
1238 Atom *protocols;
1239 Bool ret = False;
1241 if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
1242 for(i = 0; !ret && i < n; i++)
1243 if(protocols[i] == wmatom[WMDelete])
1244 ret = True;
1245 XFree(protocols);
1247 return ret;
1250 void
1251 killclient() {
1252 if(!sel)
1253 return;
1254 if(isprotodel(sel))
1255 sendevent(sel->win, wmatom[WMProtocols], wmatom[WMDelete]);
1256 else
1257 XKillClient(dpy, sel->win);
1260 void
1261 manage(Window w, XWindowAttributes *wa) {
1262 Client *c;
1263 Window trans;
1265 c = emallocz(sizeof(Client));
1266 c->tag = True;
1267 c->win = w;
1268 c->x = wa->x;
1269 c->y = wa->y;
1270 c->w = wa->width;
1271 c->h = wa->height;
1272 if(c->w == sw && c->h == sh) {
1273 c->border = 0;
1274 c->x = sx;
1275 c->y = sy;
1276 } else {
1277 c->border = BORDERPX;
1278 if(c->x + c->w + 2 * c->border > wax + waw)
1279 c->x = wax + waw - c->w - 2 * c->border;
1280 if(c->y + c->h + 2 * c->border > way + wah)
1281 c->y = way + wah - c->h - 2 * c->border;
1282 if(c->x < wax)
1283 c->x = wax;
1284 if(c->y < way)
1285 c->y = way;
1287 updatesizehints(c);
1288 XSelectInput(dpy, c->win,
1289 StructureNotifyMask | PropertyChangeMask | EnterWindowMask);
1290 XGetTransientForHint(dpy, c->win, &trans);
1291 grabbuttons(c, False);
1292 XSetWindowBorder(dpy, c->win, dc.norm[ColBG]);
1293 updatetitle(c);
1294 settag(c, getclient(trans));
1295 if(!c->isfloat)
1296 c->isfloat = trans || c->isfixed;
1297 if(clients)
1298 clients->prev = c;
1299 c->next = clients;
1300 c->snext = stack;
1301 stack = clients = c;
1302 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
1303 XMapWindow(dpy, c->win);
1304 setclientstate(c, NormalState);
1305 if(isvisible(c))
1306 focus(c);
1307 arrange();
1310 void
1311 resize(Client *c, Bool sizehints) {
1312 float actual, dx, dy, max, min;
1313 XWindowChanges wc;
1315 if(c->w <= 0 || c->h <= 0)
1316 return;
1317 if(sizehints) {
1318 if(c->minw && c->w < c->minw)
1319 c->w = c->minw;
1320 if(c->minh && c->h < c->minh)
1321 c->h = c->minh;
1322 if(c->maxw && c->w > c->maxw)
1323 c->w = c->maxw;
1324 if(c->maxh && c->h > c->maxh)
1325 c->h = c->maxh;
1326 /* inspired by algorithm from fluxbox */
1327 if(c->minay > 0 && c->maxay && (c->h - c->baseh) > 0) {
1328 dx = (float)(c->w - c->basew);
1329 dy = (float)(c->h - c->baseh);
1330 min = (float)(c->minax) / (float)(c->minay);
1331 max = (float)(c->maxax) / (float)(c->maxay);
1332 actual = dx / dy;
1333 if(max > 0 && min > 0 && actual > 0) {
1334 if(actual < min) {
1335 dy = (dx * min + dy) / (min * min + 1);
1336 dx = dy * min;
1337 c->w = (int)dx + c->basew;
1338 c->h = (int)dy + c->baseh;
1340 else if(actual > max) {
1341 dy = (dx * min + dy) / (max * max + 1);
1342 dx = dy * min;
1343 c->w = (int)dx + c->basew;
1344 c->h = (int)dy + c->baseh;
1348 if(c->incw)
1349 c->w -= (c->w - c->basew) % c->incw;
1350 if(c->inch)
1351 c->h -= (c->h - c->baseh) % c->inch;
1353 if(c->w == sw && c->h == sh)
1354 c->border = 0;
1355 else
1356 c->border = BORDERPX;
1357 /* offscreen appearance fixes */
1358 if(c->x > sw)
1359 c->x = sw - c->w - 2 * c->border;
1360 if(c->y > sh)
1361 c->y = sh - c->h - 2 * c->border;
1362 if(c->x + c->w + 2 * c->border < sx)
1363 c->x = sx;
1364 if(c->y + c->h + 2 * c->border < sy)
1365 c->y = sy;
1366 wc.x = c->x;
1367 wc.y = c->y;
1368 wc.width = c->w;
1369 wc.height = c->h;
1370 wc.border_width = c->border;
1371 XConfigureWindow(dpy, c->win, CWX | CWY | CWWidth | CWHeight | CWBorderWidth, &wc);
1372 configure(c);
1373 XSync(dpy, False);
1376 void
1377 updatesizehints(Client *c) {
1378 long msize;
1379 XSizeHints size;
1381 if(!XGetWMNormalHints(dpy, c->win, &size, &msize) || !size.flags)
1382 size.flags = PSize;
1383 c->flags = size.flags;
1384 if(c->flags & PBaseSize) {
1385 c->basew = size.base_width;
1386 c->baseh = size.base_height;
1387 } else {
1388 c->basew = c->baseh = 0;
1390 if(c->flags & PResizeInc) {
1391 c->incw = size.width_inc;
1392 c->inch = size.height_inc;
1393 } else {
1394 c->incw = c->inch = 0;
1396 if(c->flags & PMaxSize) {
1397 c->maxw = size.max_width;
1398 c->maxh = size.max_height;
1399 } else {
1400 c->maxw = c->maxh = 0;
1402 if(c->flags & PMinSize) {
1403 c->minw = size.min_width;
1404 c->minh = size.min_height;
1405 } else {
1406 c->minw = c->minh = 0;
1408 if(c->flags & PAspect) {
1409 c->minax = size.min_aspect.x;
1410 c->minay = size.min_aspect.y;
1411 c->maxax = size.max_aspect.x;
1412 c->maxay = size.max_aspect.y;
1413 } else {
1414 c->minax = c->minay = c->maxax = c->maxay = 0;
1416 c->isfixed = (c->maxw && c->minw && c->maxh && c->minh &&
1417 c->maxw == c->minw && c->maxh == c->minh);
1420 void
1421 updatetitle(Client *c) {
1422 char **list = NULL;
1423 int n;
1424 XTextProperty name;
1426 name.nitems = 0;
1427 c->name[0] = 0;
1428 XGetTextProperty(dpy, c->win, &name, netatom[NetWMName]);
1429 if(!name.nitems)
1430 XGetWMName(dpy, c->win, &name);
1431 if(!name.nitems)
1432 return;
1433 if(name.encoding == XA_STRING)
1434 strncpy(c->name, (char *)name.value, sizeof c->name);
1435 else {
1436 if(XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success && n > 0 && *list) {
1437 strncpy(c->name, *list, sizeof c->name);
1438 XFreeStringList(list);
1441 XFree(name.value);
1444 void
1445 unmanage(Client *c) {
1446 Client *nc;
1448 /* The server grab construct avoids race conditions. */
1449 XGrabServer(dpy);
1450 XSetErrorHandler(xerrordummy);
1451 detach(c);
1452 detachstack(c);
1453 if(sel == c) {
1454 for(nc = stack; nc && !isvisible(nc); nc = nc->snext);
1455 focus(nc);
1457 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1458 setclientstate(c, WithdrawnState);
1459 free(c);
1460 XSync(dpy, False);
1461 XSetErrorHandler(xerror);
1462 XUngrabServer(dpy);
1463 arrange();
1484 /* static */
1487 static void
1488 cleanup(void) {
1489 close(STDIN_FILENO);
1490 while(stack) {
1491 resize(stack, True);
1492 unmanage(stack);
1494 if(dc.font.set)
1495 XFreeFontSet(dpy, dc.font.set);
1496 else
1497 XFreeFont(dpy, dc.font.xfont);
1498 XUngrabKey(dpy, AnyKey, AnyModifier, root);
1499 XFreePixmap(dpy, dc.drawable);
1500 XFreeGC(dpy, dc.gc);
1501 XDestroyWindow(dpy, barwin);
1502 XFreeCursor(dpy, cursor[CurNormal]);
1503 XFreeCursor(dpy, cursor[CurResize]);
1504 XFreeCursor(dpy, cursor[CurMove]);
1505 XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime);
1506 XSync(dpy, False);
1509 static void
1510 scan(void) {
1511 unsigned int i, num;
1512 Window *wins, d1, d2;
1513 XWindowAttributes wa;
1515 wins = NULL;
1516 if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1517 for(i = 0; i < num; i++) {
1518 if(!XGetWindowAttributes(dpy, wins[i], &wa))
1519 continue;
1520 if(wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1521 continue;
1522 if(wa.map_state == IsViewable)
1523 manage(wins[i], &wa);
1526 if(wins)
1527 XFree(wins);
1530 static void
1531 setup(void) {
1532 int i, j;
1533 unsigned int mask;
1534 Window w;
1535 XModifierKeymap *modmap;
1536 XSetWindowAttributes wa;
1538 /* init atoms */
1539 wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1540 wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1541 wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1542 netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1543 netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1544 XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1545 PropModeReplace, (unsigned char *) netatom, NetLast);
1546 /* init cursors */
1547 cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1548 cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1549 cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1550 /* init modifier map */
1551 numlockmask = 0;
1552 modmap = XGetModifierMapping(dpy);
1553 for (i = 0; i < 8; i++) {
1554 for (j = 0; j < modmap->max_keypermod; j++) {
1555 if(modmap->modifiermap[i * modmap->max_keypermod + j] == XKeysymToKeycode(dpy, XK_Num_Lock))
1556 numlockmask = (1 << i);
1559 XFreeModifiermap(modmap);
1560 /* select for events */
1561 wa.event_mask = SubstructureRedirectMask | SubstructureNotifyMask
1562 | EnterWindowMask | LeaveWindowMask;
1563 wa.cursor = cursor[CurNormal];
1564 XChangeWindowAttributes(dpy, root, CWEventMask | CWCursor, &wa);
1565 grabkeys();
1566 seltag = True;
1567 /* style */
1568 dc.norm[ColBG] = getcolor(NORMBGCOLOR);
1569 dc.norm[ColFG] = getcolor(NORMFGCOLOR);
1570 dc.sel[ColBG] = getcolor(SELBGCOLOR);
1571 dc.sel[ColFG] = getcolor(SELFGCOLOR);
1572 setfont(FONT);
1573 /* geometry */
1574 sx = sy = 0;
1575 sw = DisplayWidth(dpy, screen);
1576 sh = DisplayHeight(dpy, screen);
1577 nmaster = NMASTER;
1578 bmw = 1;
1579 /* bar */
1580 dc.h = bh = dc.font.height + 2;
1581 wa.override_redirect = 1;
1582 wa.background_pixmap = ParentRelative;
1583 wa.event_mask = ButtonPressMask | ExposureMask;
1584 barwin = XCreateWindow(dpy, root, sx, sy, sw, bh, 0,
1585 DefaultDepth(dpy, screen), CopyFromParent, DefaultVisual(dpy, screen),
1586 CWOverrideRedirect | CWBackPixmap | CWEventMask, &wa);
1587 XDefineCursor(dpy, barwin, cursor[CurNormal]);
1588 XMapRaised(dpy, barwin);
1589 strcpy(stext, "dwm-"VERSION);
1590 /* windowarea */
1591 wax = sx;
1592 way = sy + bh;
1593 wah = sh - bh;
1594 waw = sw;
1595 /* pixmap for everything */
1596 dc.drawable = XCreatePixmap(dpy, root, sw, bh, DefaultDepth(dpy, screen));
1597 dc.gc = XCreateGC(dpy, root, 0, 0);
1598 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
1599 /* multihead support */
1600 selscreen = XQueryPointer(dpy, root, &w, &w, &i, &i, &i, &i, &mask);
1603 /*
1604 * Startup Error handler to check if another window manager
1605 * is already running.
1606 */
1607 static int
1608 xerrorstart(Display *dsply, XErrorEvent *ee) {
1609 otherwm = True;
1610 return -1;
1615 void
1616 sendevent(Window w, Atom a, long value) {
1617 XEvent e;
1619 e.type = ClientMessage;
1620 e.xclient.window = w;
1621 e.xclient.message_type = a;
1622 e.xclient.format = 32;
1623 e.xclient.data.l[0] = value;
1624 e.xclient.data.l[1] = CurrentTime;
1625 XSendEvent(dpy, w, False, NoEventMask, &e);
1626 XSync(dpy, False);
1629 void
1630 quit() {
1631 readin = running = False;
1634 /* There's no way to check accesses to destroyed windows, thus those cases are
1635 * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
1636 * default error handler, which may call exit.
1637 */
1638 int
1639 xerror(Display *dpy, XErrorEvent *ee) {
1640 if(ee->error_code == BadWindow
1641 || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1642 || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1643 || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1644 || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1645 || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1646 || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1647 || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1648 return 0;
1649 fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1650 ee->request_code, ee->error_code);
1651 return xerrorxlib(dpy, ee); /* may call exit */
1654 int
1655 main(int argc, char *argv[]) {
1656 char *p;
1657 int r, xfd;
1658 fd_set rd;
1660 if(argc == 2 && !strncmp("-v", argv[1], 3)) {
1661 fputs("dwm-"VERSION", (C)opyright MMVI-MMVII Anselm R. Garbe\n", stdout);
1662 exit(EXIT_SUCCESS);
1663 } else if(argc != 1) {
1664 eprint("usage: dwm [-v]\n");
1666 setlocale(LC_CTYPE, "");
1667 dpy = XOpenDisplay(0);
1668 if(!dpy) {
1669 eprint("dwm: cannot open display\n");
1671 xfd = ConnectionNumber(dpy);
1672 screen = DefaultScreen(dpy);
1673 root = RootWindow(dpy, screen);
1674 otherwm = False;
1675 XSetErrorHandler(xerrorstart);
1676 /* this causes an error if some other window manager is running */
1677 XSelectInput(dpy, root, SubstructureRedirectMask);
1678 XSync(dpy, False);
1679 if(otherwm) {
1680 eprint("dwm: another window manager is already running\n");
1683 XSync(dpy, False);
1684 XSetErrorHandler(NULL);
1685 xerrorxlib = XSetErrorHandler(xerror);
1686 XSync(dpy, False);
1687 setup();
1688 drawstatus();
1689 scan();
1691 /* main event loop, also reads status text from stdin */
1692 XSync(dpy, False);
1693 procevent();
1694 readin = True;
1695 while(running) {
1696 FD_ZERO(&rd);
1697 if(readin)
1698 FD_SET(STDIN_FILENO, &rd);
1699 FD_SET(xfd, &rd);
1700 if(select(xfd + 1, &rd, NULL, NULL, NULL) == -1) {
1701 if(errno == EINTR)
1702 continue;
1703 eprint("select failed\n");
1705 if(FD_ISSET(STDIN_FILENO, &rd)) {
1706 switch(r = read(STDIN_FILENO, stext, sizeof stext - 1)) {
1707 case -1:
1708 strncpy(stext, strerror(errno), sizeof stext - 1);
1709 stext[sizeof stext - 1] = '\0';
1710 readin = False;
1711 break;
1712 case 0:
1713 strncpy(stext, "EOF", 4);
1714 readin = False;
1715 break;
1716 default:
1717 for(stext[r] = '\0', p = stext + strlen(stext) - 1; p >= stext && *p == '\n'; *p-- = '\0');
1718 for(; p >= stext && *p != '\n'; --p);
1719 if(p > stext)
1720 strncpy(stext, p + 1, sizeof stext);
1722 drawstatus();
1724 if(FD_ISSET(xfd, &rd))
1725 procevent();
1727 cleanup();
1728 XCloseDisplay(dpy);
1729 return 0;