aewl

view aewl.c @ 760:014c4cb1ae4a

removed some compiler warnings
author meillo@marmaro.de
date Fri, 30 May 2008 22:36:38 +0200
parents 45f23169563e
children 59ce221b9a37
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. Each client contains an array of Bools of the same size as the
22 * global tags array to indicate the tags of a client. For each client dwm
23 * creates a small title window, which is resized whenever the (_NET_)WM_NAME
24 * properties are updated or the client is moved/resized.
25 *
26 * Keys and tagging rules are organized as arrays and defined in the config.h
27 * file. These arrays are kept static in event.o and tag.o respectively,
28 * because no other part of dwm needs access to them. The current mode is
29 * represented by the arrange() function pointer, which wether points to
30 * dofloat() or dotile().
31 *
32 * To understand everything else, start reading main.c:main().
33 */
35 #include "config.h"
36 #include <errno.h>
37 #include <locale.h>
38 #include <regex.h>
39 #include <stdio.h>
40 #include <stdarg.h>
41 #include <stdlib.h>
42 #include <string.h>
43 #include <unistd.h>
44 #include <sys/select.h>
45 #include <sys/types.h>
46 #include <sys/wait.h>
47 #include <X11/cursorfont.h>
48 #include <X11/keysym.h>
49 #include <X11/Xatom.h>
50 #include <X11/Xlib.h>
51 #include <X11/Xproto.h>
52 #include <X11/Xutil.h>
54 /* mask shorthands, used in event.c and client.c */
55 #define BUTTONMASK (ButtonPressMask | ButtonReleaseMask)
57 enum { NetSupported, NetWMName, NetLast }; /* EWMH atoms */
58 enum { WMProtocols, WMDelete, WMState, WMLast }; /* default atoms */
59 enum { CurNormal, CurResize, CurMove, CurLast }; /* cursor */
60 enum { ColBorder, ColFG, ColBG, ColLast }; /* color */
62 typedef struct {
63 int ascent;
64 int descent;
65 int height;
66 XFontSet set;
67 XFontStruct *xfont;
68 } Fnt;
70 typedef struct {
71 int x, y, w, h;
72 unsigned long norm[ColLast];
73 unsigned long sel[ColLast];
74 Drawable drawable;
75 Fnt font;
76 GC gc;
77 } DC; /* draw context */
79 typedef struct Client Client;
80 struct Client {
81 char name[256];
82 int x, y, w, h;
83 int rx, ry, rw, rh; /* revert geometry */
84 int basew, baseh, incw, inch, maxw, maxh, minw, minh;
85 int minax, minay, maxax, maxay;
86 long flags;
87 unsigned int border;
88 Bool isfixed, isfloat, ismax;
89 Bool tag;
90 Client *next;
91 Client *prev;
92 Client *snext;
93 Window win;
94 };
96 typedef struct {
97 const char *clpattern;
98 int tag;
99 Bool isfloat;
100 } Rule;
102 typedef struct {
103 regex_t *clregex;
104 } RReg;
107 typedef struct {
108 unsigned long mod;
109 KeySym keysym;
110 void (*func)(const char* cmd);
111 const char* cmd;
112 } Key;
115 #define CLEANMASK(mask) (mask & ~(numlockmask | LockMask))
116 #define MOUSEMASK (BUTTONMASK | PointerMotionMask)
120 const char *tags[]; /* all tags */
121 char stext[256]; /* status text */
122 int bh, bmw; /* bar height, bar mode label width */
123 int screen, sx, sy, sw, sh; /* screen geometry */
124 int wax, way, wah, waw; /* windowarea geometry */
125 unsigned int nmaster; /* number of master clients */
126 unsigned int ntags, numlockmask; /* number of tags, dynamic lock mask */
127 void (*handler[LASTEvent])(XEvent *); /* event handler */
128 void (*arrange)(void); /* arrange function, indicates mode */
129 Atom wmatom[WMLast], netatom[NetLast];
130 Bool running, selscreen, seltag; /* seltag is array of Bool */
131 Client *clients, *sel, *stack; /* global client list and stack */
132 Cursor cursor[CurLast];
133 DC dc; /* global draw context */
134 Display *dpy;
135 Window root, barwin;
137 Bool running = True;
138 Bool selscreen = True;
139 Client *clients = NULL;
140 Client *sel = NULL;
141 Client *stack = NULL;
142 DC dc = {0};
144 static int (*xerrorxlib)(Display *, XErrorEvent *);
145 static Bool otherwm, readin;
146 static RReg *rreg = NULL;
147 static unsigned int len = 0;
150 TAGS
151 RULES
154 /* client.c */
155 void configure(Client *c); /* send synthetic configure event */
156 void focus(Client *c); /* focus c, c may be NULL */
157 Client *getclient(Window w); /* return client of w */
158 Bool isprotodel(Client *c); /* returns True if c->win supports wmatom[WMDelete] */
159 void manage(Window w, XWindowAttributes *wa); /* manage new client */
160 void resize(Client *c, Bool sizehints); /* resize c*/
161 void updatesizehints(Client *c); /* update the size hint variables of c */
162 void updatetitle(Client *c); /* update the name of c */
163 void unmanage(Client *c); /* destroy c */
165 /* draw.c */
166 void drawstatus(void); /* draw the bar */
167 unsigned long getcolor(const char *colstr); /* return color of colstr */
168 void setfont(const char *fontstr); /* set the font for DC */
169 unsigned int textw(const char *text); /* return the width of text in px*/
171 /* event.c */
172 void grabkeys(void); /* grab all keys defined in config.h */
173 void procevent(void); /* process pending X events */
175 /* main.c */
176 void sendevent(Window w, Atom a, long value); /* send synthetic event to w */
177 int xerror(Display *dsply, XErrorEvent *ee); /* dwm's X error handler */
179 /* tag.c */
180 void initrregs(void); /* initialize regexps of rules defined in config.h */
181 Client *getnext(Client *c); /* returns next visible client */
182 void settags(Client *c, Client *trans); /* sets tags of c */
184 /* util.c */
185 void *emallocz(unsigned int size); /* allocates zero-initialized memory, exits on error */
186 void eprint(const char *errstr, ...); /* prints errstr and exits with 1 */
188 /* view.c */
189 void detach(Client *c); /* detaches c from global client list */
190 void dofloat(void); /* arranges all windows floating */
191 void dotile(void); /* arranges all windows tiled */
192 void domax(void); /* arranges all windows fullscreen */
193 Bool isvisible(Client *c); /* returns True if client is visible */
194 void restack(void); /* restores z layers of all clients */
197 void toggleview(void); /* toggle the viewed tag */
198 void focusnext(void); /* focuses next visible client */
199 void zoom(void); /* zooms the focused client to master area */
200 void killclient(void); /* kill c nicely */
201 void quit(void); /* quit dwm nicely */
202 void togglemode(void); /* toggles global arrange function (dotile/dofloat) */
203 void togglefloat(void); /* toggles focusesd client between floating/non-floating state */
204 void incnmaster(void); /* increments nmaster */
205 void decnmaster(void); /* decrements nmaster */
206 void toggletag(void); /* toggles c tag */
207 void spawn(const char* cmd); /* forks a new subprocess with cmd */
218 /* from view.c */
219 /* static */
221 static Client *
222 nexttiled(Client *c) {
223 for(c = getnext(c); c && c->isfloat; c = getnext(c->next));
224 return c;
225 }
227 static void
228 togglemax(Client *c) {
229 XEvent ev;
231 if(c->isfixed)
232 return;
234 if((c->ismax = !c->ismax)) {
235 c->rx = c->x; c->x = wax;
236 c->ry = c->y; c->y = way;
237 c->rw = c->w; c->w = waw - 2 * BORDERPX;
238 c->rh = c->h; c->h = wah - 2 * BORDERPX;
239 }
240 else {
241 c->x = c->rx;
242 c->y = c->ry;
243 c->w = c->rw;
244 c->h = c->rh;
245 }
246 resize(c, True);
247 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
248 }
252 void (*arrange)(void) = DEFMODE;
254 void
255 detach(Client *c) {
256 if(c->prev)
257 c->prev->next = c->next;
258 if(c->next)
259 c->next->prev = c->prev;
260 if(c == clients)
261 clients = c->next;
262 c->next = c->prev = NULL;
263 }
265 void
266 dofloat(void) {
267 Client *c;
269 for(c = clients; c; c = c->next) {
270 if(isvisible(c)) {
271 resize(c, True);
272 }
273 else
274 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
275 }
276 if(!sel || !isvisible(sel)) {
277 for(c = stack; c && !isvisible(c); c = c->snext);
278 focus(c);
279 }
280 restack();
281 }
283 void
284 dotile(void) {
285 unsigned int i, n, mw, mh, tw, th;
286 Client *c;
288 for(n = 0, c = nexttiled(clients); c; c = nexttiled(c->next))
289 n++;
290 /* window geoms */
291 mh = (n > nmaster) ? wah / nmaster : wah / (n > 0 ? n : 1);
292 mw = (n > nmaster) ? waw / 2 : waw;
293 th = (n > nmaster) ? wah / (n - nmaster) : 0;
294 tw = waw - mw;
296 for(i = 0, c = clients; c; c = c->next)
297 if(isvisible(c)) {
298 if(c->isfloat) {
299 resize(c, True);
300 continue;
301 }
302 c->ismax = False;
303 c->x = wax;
304 c->y = way;
305 if(i < nmaster) {
306 c->y += i * mh;
307 c->w = mw - 2 * BORDERPX;
308 c->h = mh - 2 * BORDERPX;
309 }
310 else { /* tile window */
311 c->x += mw;
312 c->w = tw - 2 * BORDERPX;
313 if(th > 2 * BORDERPX) {
314 c->y += (i - nmaster) * th;
315 c->h = th - 2 * BORDERPX;
316 }
317 else /* fallback if th <= 2 * BORDERPX */
318 c->h = wah - 2 * BORDERPX;
319 }
320 resize(c, False);
321 i++;
322 }
323 else
324 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
325 if(!sel || !isvisible(sel)) {
326 for(c = stack; c && !isvisible(c); c = c->snext);
327 focus(c);
328 }
329 restack();
330 }
332 /* begin code by mitch */
333 void
334 arrangemax(Client *c) {
335 if(c == sel) {
336 c->ismax = True;
337 c->x = sx;
338 c->y = bh;
339 c->w = sw - 2 * BORDERPX;
340 c->h = sh - bh - 2 * BORDERPX;
341 XRaiseWindow(dpy, c->win);
342 } else {
343 c->ismax = False;
344 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
345 XLowerWindow(dpy, c->win);
346 }
347 }
349 void
350 domax(void) {
351 Client *c;
353 for(c = clients; c; c = c->next) {
354 if(isvisible(c)) {
355 if(c->isfloat) {
356 resize(c, True);
357 continue;
358 }
359 arrangemax(c);
360 resize(c, False);
361 } else {
362 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
363 }
365 }
366 if(!sel || !isvisible(sel)) {
367 for(c = stack; c && !isvisible(c); c = c->snext);
368 focus(c);
369 }
370 restack();
371 }
372 /* end code by mitch */
374 void
375 focusnext() {
376 Client *c;
378 if(!sel)
379 return;
380 if(!(c = getnext(sel->next)))
381 c = getnext(clients);
382 if(c) {
383 focus(c);
384 restack();
385 }
386 }
388 void
389 incnmaster() {
390 if((arrange == dofloat) || (wah / (nmaster + 1) <= 2 * BORDERPX))
391 return;
392 nmaster++;
393 if(sel)
394 arrange();
395 else
396 drawstatus();
397 }
399 void
400 decnmaster() {
401 if((arrange == dofloat) || (nmaster <= 1))
402 return;
403 nmaster--;
404 if(sel)
405 arrange();
406 else
407 drawstatus();
408 }
410 Bool
411 isvisible(Client *c) {
412 if((c->tag && seltag) || (!c->tag && !seltag)) {
413 return True;
414 }
415 return False;
416 }
418 void
419 restack(void) {
420 Client *c;
421 XEvent ev;
423 drawstatus();
424 if(!sel)
425 return;
426 if(sel->isfloat || arrange == dofloat)
427 XRaiseWindow(dpy, sel->win);
429 /* begin code by mitch */
430 if(arrange == domax) {
431 for(c = nexttiled(clients); c; c = nexttiled(c->next)) {
432 arrangemax(c);
433 resize(c, False);
434 }
436 } else if (arrange == dotile) {
437 /* end code by mitch */
439 if(!sel->isfloat)
440 XLowerWindow(dpy, sel->win);
441 for(c = nexttiled(clients); c; c = nexttiled(c->next)) {
442 if(c == sel)
443 continue;
444 XLowerWindow(dpy, c->win);
445 }
446 }
447 XSync(dpy, False);
448 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
449 }
451 void
452 togglefloat() {
453 if (!sel || arrange == dofloat)
454 return;
455 sel->isfloat = !sel->isfloat;
456 arrange();
457 }
459 void
460 togglemode() {
461 /* only toggle between tile and max - float is just available through togglefloat */
462 arrange = (arrange == dotile) ? domax : dotile;
463 if(sel)
464 arrange();
465 else
466 drawstatus();
467 }
469 void
470 toggleview() {
471 seltag = !seltag;
472 arrange();
473 }
475 void
476 zoom() {
477 unsigned int n;
478 Client *c;
480 if(!sel)
481 return;
482 if(sel->isfloat || (arrange == dofloat)) {
483 togglemax(sel);
484 return;
485 }
486 for(n = 0, c = nexttiled(clients); c; c = nexttiled(c->next))
487 n++;
489 if((c = sel) == nexttiled(clients))
490 if(!(c = nexttiled(c->next)))
491 return;
492 detach(c);
493 if(clients)
494 clients->prev = c;
495 c->next = clients;
496 clients = c;
497 focus(c);
498 arrange();
499 }
516 /* from util.c */
519 void *
520 emallocz(unsigned int size) {
521 void *res = calloc(1, size);
523 if(!res)
524 eprint("fatal: could not malloc() %u bytes\n", size);
525 return res;
526 }
528 void
529 eprint(const char *errstr, ...) {
530 va_list ap;
532 va_start(ap, errstr);
533 vfprintf(stderr, errstr, ap);
534 va_end(ap);
535 exit(EXIT_FAILURE);
536 }
538 void
539 spawn(const char* cmd) {
540 static char *shell = NULL;
542 if(!shell && !(shell = getenv("SHELL")))
543 shell = "/bin/sh";
544 if(!cmd)
545 return;
546 /* The double-fork construct avoids zombie processes and keeps the code
547 * clean from stupid signal handlers. */
548 if(fork() == 0) {
549 if(fork() == 0) {
550 if(dpy)
551 close(ConnectionNumber(dpy));
552 setsid();
553 execl(shell, shell, "-c", cmd, (char *)NULL);
554 fprintf(stderr, "dwm: execl '%s -c %s'", shell, cmd);
555 perror(" failed");
556 }
557 exit(0);
558 }
559 wait(0);
560 }
574 /* from tag.c */
576 /* static */
578 Client *
579 getnext(Client *c) {
580 for(; c && !isvisible(c); c = c->next);
581 return c;
582 }
584 void
585 initrregs(void) {
586 unsigned int i;
587 regex_t *reg;
589 if(rreg)
590 return;
591 len = sizeof rule / sizeof rule[0];
592 rreg = emallocz(len * sizeof(RReg));
593 for(i = 0; i < len; i++) {
594 if(rule[i].clpattern) {
595 reg = emallocz(sizeof(regex_t));
596 if(regcomp(reg, rule[i].clpattern, REG_EXTENDED))
597 free(reg);
598 else
599 rreg[i].clregex = reg;
600 }
601 }
602 }
604 void
605 settags(Client *c, Client *trans) {
606 char prop[512];
607 unsigned int i;
608 regmatch_t tmp;
609 Bool matched = trans != NULL;
610 XClassHint ch = { 0 };
612 if(matched) {
613 c->tag = trans->tag;
614 } else {
615 XGetClassHint(dpy, c->win, &ch);
616 snprintf(prop, sizeof prop, "%s:%s:%s",
617 ch.res_class ? ch.res_class : "",
618 ch.res_name ? ch.res_name : "", c->name);
619 for(i = 0; i < len; i++)
620 if(rreg[i].clregex && !regexec(rreg[i].clregex, prop, 1, &tmp, 0)) {
621 c->isfloat = rule[i].isfloat;
622 if (rule[i].tag < 0) {
623 c->tag = seltag;
624 } else if (rule[i].tag == 0) {
625 c->tag = True;
626 } else {
627 c->tag = False;
628 }
629 matched = True;
630 break; /* perform only the first rule matching */
631 }
632 if(ch.res_class)
633 XFree(ch.res_class);
634 if(ch.res_name)
635 XFree(ch.res_name);
636 }
637 if(!matched) {
638 c->tag = seltag;
639 }
640 }
642 void
643 toggletag() {
644 if(!sel)
645 return;
646 sel->tag = !sel->tag;
647 toggleview();
648 }
666 /* from event.c */
667 /* static */
669 KEYS
673 static void
674 movemouse(Client *c) {
675 int x1, y1, ocx, ocy, di;
676 unsigned int dui;
677 Window dummy;
678 XEvent ev;
680 ocx = c->x;
681 ocy = c->y;
682 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
683 None, cursor[CurMove], CurrentTime) != GrabSuccess)
684 return;
685 c->ismax = False;
686 XQueryPointer(dpy, root, &dummy, &dummy, &x1, &y1, &di, &di, &dui);
687 for(;;) {
688 XMaskEvent(dpy, MOUSEMASK | ExposureMask | SubstructureRedirectMask, &ev);
689 switch (ev.type) {
690 case ButtonRelease:
691 resize(c, True);
692 XUngrabPointer(dpy, CurrentTime);
693 return;
694 case ConfigureRequest:
695 case Expose:
696 case MapRequest:
697 handler[ev.type](&ev);
698 break;
699 case MotionNotify:
700 XSync(dpy, False);
701 c->x = ocx + (ev.xmotion.x - x1);
702 c->y = ocy + (ev.xmotion.y - y1);
703 if(abs(wax + c->x) < SNAP)
704 c->x = wax;
705 else if(abs((wax + waw) - (c->x + c->w + 2 * c->border)) < SNAP)
706 c->x = wax + waw - c->w - 2 * c->border;
707 if(abs(way - c->y) < SNAP)
708 c->y = way;
709 else if(abs((way + wah) - (c->y + c->h + 2 * c->border)) < SNAP)
710 c->y = way + wah - c->h - 2 * c->border;
711 resize(c, False);
712 break;
713 }
714 }
715 }
717 static void
718 resizemouse(Client *c) {
719 int ocx, ocy;
720 int nw, nh;
721 XEvent ev;
723 ocx = c->x;
724 ocy = c->y;
725 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
726 None, cursor[CurResize], CurrentTime) != GrabSuccess)
727 return;
728 c->ismax = False;
729 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->border - 1, c->h + c->border - 1);
730 for(;;) {
731 XMaskEvent(dpy, MOUSEMASK | ExposureMask | SubstructureRedirectMask , &ev);
732 switch(ev.type) {
733 case ButtonRelease:
734 resize(c, True);
735 XUngrabPointer(dpy, CurrentTime);
736 return;
737 case ConfigureRequest:
738 case Expose:
739 case MapRequest:
740 handler[ev.type](&ev);
741 break;
742 case MotionNotify:
743 XSync(dpy, False);
744 nw = ev.xmotion.x - ocx - 2 * c->border + 1;
745 c->w = nw > 0 ? nw : 1;
746 nh = ev.xmotion.y - ocy - 2 * c->border + 1;
747 c->h = nh > 0 ? nh : 1;
748 resize(c, True);
749 break;
750 }
751 }
752 }
754 static void
755 buttonpress(XEvent *e) {
756 Client *c;
757 XButtonPressedEvent *ev = &e->xbutton;
759 if(barwin == ev->window) {
760 if(ev->button == Button1) {
761 toggleview();
762 }
763 return;
764 } else if((c = getclient(ev->window))) {
765 focus(c);
766 if(CLEANMASK(ev->state) != MODKEY)
767 return;
768 if(ev->button == Button1 && (arrange == dofloat || c->isfloat)) {
769 restack();
770 movemouse(c);
771 } else if(ev->button == Button3 && (arrange == dofloat || c->isfloat) && !c->isfixed) {
772 restack();
773 resizemouse(c);
774 }
775 }
776 }
778 static void
779 configurerequest(XEvent *e) {
780 unsigned long newmask;
781 Client *c;
782 XConfigureRequestEvent *ev = &e->xconfigurerequest;
783 XWindowChanges wc;
785 if((c = getclient(ev->window))) {
786 c->ismax = False;
787 if(ev->value_mask & CWX)
788 c->x = ev->x;
789 if(ev->value_mask & CWY)
790 c->y = ev->y;
791 if(ev->value_mask & CWWidth)
792 c->w = ev->width;
793 if(ev->value_mask & CWHeight)
794 c->h = ev->height;
795 if(ev->value_mask & CWBorderWidth)
796 c->border = ev->border_width;
797 wc.x = c->x;
798 wc.y = c->y;
799 wc.width = c->w;
800 wc.height = c->h;
801 newmask = ev->value_mask & (~(CWSibling | CWStackMode | CWBorderWidth));
802 if(newmask)
803 XConfigureWindow(dpy, c->win, newmask, &wc);
804 else
805 configure(c);
806 XSync(dpy, False);
807 if(c->isfloat) {
808 resize(c, False);
809 if(!isvisible(c))
810 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
811 }
812 else
813 arrange();
814 } else {
815 wc.x = ev->x;
816 wc.y = ev->y;
817 wc.width = ev->width;
818 wc.height = ev->height;
819 wc.border_width = ev->border_width;
820 wc.sibling = ev->above;
821 wc.stack_mode = ev->detail;
822 XConfigureWindow(dpy, ev->window, ev->value_mask, &wc);
823 XSync(dpy, False);
824 }
825 }
827 static void
828 destroynotify(XEvent *e) {
829 Client *c;
830 XDestroyWindowEvent *ev = &e->xdestroywindow;
832 if((c = getclient(ev->window)))
833 unmanage(c);
834 }
836 static void
837 enternotify(XEvent *e) {
838 Client *c;
839 XCrossingEvent *ev = &e->xcrossing;
841 if(ev->mode != NotifyNormal || ev->detail == NotifyInferior)
842 return;
843 if((c = getclient(ev->window)) && isvisible(c))
844 focus(c);
845 else if(ev->window == root) {
846 selscreen = True;
847 for(c = stack; c && !isvisible(c); c = c->snext);
848 focus(c);
849 }
850 }
852 static void
853 expose(XEvent *e) {
854 XExposeEvent *ev = &e->xexpose;
856 if(ev->count == 0) {
857 if(barwin == ev->window)
858 drawstatus();
859 }
860 }
862 static void
863 keypress(XEvent *e) {
864 static unsigned int len = sizeof key / sizeof key[0];
865 unsigned int i;
866 KeySym keysym;
867 XKeyEvent *ev = &e->xkey;
869 keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
870 for(i = 0; i < len; i++) {
871 if(keysym == key[i].keysym && CLEANMASK(key[i].mod) == CLEANMASK(ev->state)) {
872 if(key[i].func)
873 key[i].func(key[i].cmd);
874 }
875 }
876 }
878 static void
879 leavenotify(XEvent *e) {
880 XCrossingEvent *ev = &e->xcrossing;
882 if((ev->window == root) && !ev->same_screen) {
883 selscreen = False;
884 focus(NULL);
885 }
886 }
888 static void
889 mappingnotify(XEvent *e) {
890 XMappingEvent *ev = &e->xmapping;
892 XRefreshKeyboardMapping(ev);
893 if(ev->request == MappingKeyboard)
894 grabkeys();
895 }
897 static void
898 maprequest(XEvent *e) {
899 static XWindowAttributes wa;
900 XMapRequestEvent *ev = &e->xmaprequest;
902 if(!XGetWindowAttributes(dpy, ev->window, &wa))
903 return;
904 if(wa.override_redirect) {
905 XSelectInput(dpy, ev->window,
906 (StructureNotifyMask | PropertyChangeMask));
907 return;
908 }
909 if(!getclient(ev->window))
910 manage(ev->window, &wa);
911 }
913 static void
914 propertynotify(XEvent *e) {
915 Client *c;
916 Window trans;
917 XPropertyEvent *ev = &e->xproperty;
919 if(ev->state == PropertyDelete)
920 return; /* ignore */
921 if((c = getclient(ev->window))) {
922 switch (ev->atom) {
923 default: break;
924 case XA_WM_TRANSIENT_FOR:
925 XGetTransientForHint(dpy, c->win, &trans);
926 if(!c->isfloat && (c->isfloat = (trans != 0)))
927 arrange();
928 break;
929 case XA_WM_NORMAL_HINTS:
930 updatesizehints(c);
931 break;
932 }
933 if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
934 updatetitle(c);
935 if(c == sel)
936 drawstatus();
937 }
938 }
939 }
941 static void
942 unmapnotify(XEvent *e) {
943 Client *c;
944 XUnmapEvent *ev = &e->xunmap;
946 if((c = getclient(ev->window)))
947 unmanage(c);
948 }
952 void (*handler[LASTEvent]) (XEvent *) = {
953 [ButtonPress] = buttonpress,
954 [ConfigureRequest] = configurerequest,
955 [DestroyNotify] = destroynotify,
956 [EnterNotify] = enternotify,
957 [LeaveNotify] = leavenotify,
958 [Expose] = expose,
959 [KeyPress] = keypress,
960 [MappingNotify] = mappingnotify,
961 [MapRequest] = maprequest,
962 [PropertyNotify] = propertynotify,
963 [UnmapNotify] = unmapnotify
964 };
966 void
967 grabkeys(void) {
968 static unsigned int len = sizeof key / sizeof key[0];
969 unsigned int i;
970 KeyCode code;
972 XUngrabKey(dpy, AnyKey, AnyModifier, root);
973 for(i = 0; i < len; i++) {
974 code = XKeysymToKeycode(dpy, key[i].keysym);
975 XGrabKey(dpy, code, key[i].mod, root, True,
976 GrabModeAsync, GrabModeAsync);
977 XGrabKey(dpy, code, key[i].mod | LockMask, root, True,
978 GrabModeAsync, GrabModeAsync);
979 XGrabKey(dpy, code, key[i].mod | numlockmask, root, True,
980 GrabModeAsync, GrabModeAsync);
981 XGrabKey(dpy, code, key[i].mod | numlockmask | LockMask, root, True,
982 GrabModeAsync, GrabModeAsync);
983 }
984 }
986 void
987 procevent(void) {
988 XEvent ev;
990 while(XPending(dpy)) {
991 XNextEvent(dpy, &ev);
992 if(handler[ev.type])
993 (handler[ev.type])(&ev); /* call handler */
994 }
995 }
1011 /* from draw.c */
1012 /* static */
1014 static unsigned int
1015 textnw(const char *text, unsigned int len) {
1016 XRectangle r;
1018 if(dc.font.set) {
1019 XmbTextExtents(dc.font.set, text, len, NULL, &r);
1020 return r.width;
1022 return XTextWidth(dc.font.xfont, text, len);
1025 static void
1026 drawtext(const char *text, unsigned long col[ColLast]) {
1027 int x, y, w, h;
1028 static char buf[256];
1029 unsigned int len, olen;
1030 XGCValues gcv;
1031 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
1033 XSetForeground(dpy, dc.gc, col[ColBG]);
1034 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
1035 if(!text)
1036 return;
1037 w = 0;
1038 olen = len = strlen(text);
1039 if(len >= sizeof buf)
1040 len = sizeof buf - 1;
1041 memcpy(buf, text, len);
1042 buf[len] = 0;
1043 h = dc.font.ascent + dc.font.descent;
1044 y = dc.y + (dc.h / 2) - (h / 2) + dc.font.ascent;
1045 x = dc.x + (h / 2);
1046 /* shorten text if necessary */
1047 while(len && (w = textnw(buf, len)) > dc.w - h)
1048 buf[--len] = 0;
1049 if(len < olen) {
1050 if(len > 1)
1051 buf[len - 1] = '.';
1052 if(len > 2)
1053 buf[len - 2] = '.';
1054 if(len > 3)
1055 buf[len - 3] = '.';
1057 if(w > dc.w)
1058 return; /* too long */
1059 gcv.foreground = col[ColFG];
1060 if(dc.font.set) {
1061 XChangeGC(dpy, dc.gc, GCForeground, &gcv);
1062 XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
1063 } else {
1064 gcv.font = dc.font.xfont->fid;
1065 XChangeGC(dpy, dc.gc, GCForeground | GCFont, &gcv);
1066 XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
1072 void
1073 drawstatus(void) {
1074 int x;
1075 unsigned int i;
1077 dc.x = dc.y = 0;
1078 for(i = 0; i < ntags; i++) {
1079 dc.w = textw(tags[i]);
1080 drawtext(tags[i], ( ((i == 0 && seltag) || (i == 1 && !seltag)) ? dc.sel : dc.norm));
1081 dc.x += dc.w + 1;
1083 dc.w = bmw;
1084 drawtext("", dc.norm);
1085 x = dc.x + dc.w;
1086 dc.w = textw(stext);
1087 dc.x = sw - dc.w;
1088 if(dc.x < x) {
1089 dc.x = x;
1090 dc.w = sw - x;
1092 drawtext(stext, dc.norm);
1093 if((dc.w = dc.x - x) > bh) {
1094 dc.x = x;
1095 drawtext(sel ? sel->name : NULL, dc.norm);
1097 XCopyArea(dpy, dc.drawable, barwin, dc.gc, 0, 0, sw, bh, 0, 0);
1098 XSync(dpy, False);
1101 unsigned long
1102 getcolor(const char *colstr) {
1103 Colormap cmap = DefaultColormap(dpy, screen);
1104 XColor color;
1106 if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
1107 eprint("error, cannot allocate color '%s'\n", colstr);
1108 return color.pixel;
1111 void
1112 setfont(const char *fontstr) {
1113 char *def, **missing;
1114 int i, n;
1116 missing = NULL;
1117 if(dc.font.set)
1118 XFreeFontSet(dpy, dc.font.set);
1119 dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
1120 if(missing) {
1121 while(n--)
1122 fprintf(stderr, "missing fontset: %s\n", missing[n]);
1123 XFreeStringList(missing);
1125 if(dc.font.set) {
1126 XFontSetExtents *font_extents;
1127 XFontStruct **xfonts;
1128 char **font_names;
1129 dc.font.ascent = dc.font.descent = 0;
1130 font_extents = XExtentsOfFontSet(dc.font.set);
1131 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
1132 for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
1133 if(dc.font.ascent < (*xfonts)->ascent)
1134 dc.font.ascent = (*xfonts)->ascent;
1135 if(dc.font.descent < (*xfonts)->descent)
1136 dc.font.descent = (*xfonts)->descent;
1137 xfonts++;
1139 } else {
1140 if(dc.font.xfont)
1141 XFreeFont(dpy, dc.font.xfont);
1142 dc.font.xfont = NULL;
1143 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr)))
1144 eprint("error, cannot load font: '%s'\n", fontstr);
1145 dc.font.ascent = dc.font.xfont->ascent;
1146 dc.font.descent = dc.font.xfont->descent;
1148 dc.font.height = dc.font.ascent + dc.font.descent;
1151 unsigned int
1152 textw(const char *text) {
1153 return textnw(text, strlen(text)) + dc.font.height;
1166 /* from client.c */
1167 /* static */
1169 static void
1170 detachstack(Client *c) {
1171 Client **tc;
1172 for(tc=&stack; *tc && *tc != c; tc=&(*tc)->snext);
1173 *tc = c->snext;
1176 static void
1177 grabbuttons(Client *c, Bool focused) {
1178 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1180 if(focused) {
1181 XGrabButton(dpy, Button1, MODKEY, c->win, False, BUTTONMASK,
1182 GrabModeAsync, GrabModeSync, None, None);
1183 XGrabButton(dpy, Button1, MODKEY | LockMask, c->win, False, BUTTONMASK,
1184 GrabModeAsync, GrabModeSync, None, None);
1185 XGrabButton(dpy, Button1, MODKEY | numlockmask, c->win, False, BUTTONMASK,
1186 GrabModeAsync, GrabModeSync, None, None);
1187 XGrabButton(dpy, Button1, MODKEY | numlockmask | LockMask, c->win, False, BUTTONMASK,
1188 GrabModeAsync, GrabModeSync, None, None);
1190 XGrabButton(dpy, Button2, MODKEY, c->win, False, BUTTONMASK,
1191 GrabModeAsync, GrabModeSync, None, None);
1192 XGrabButton(dpy, Button2, MODKEY | LockMask, c->win, False, BUTTONMASK,
1193 GrabModeAsync, GrabModeSync, None, None);
1194 XGrabButton(dpy, Button2, MODKEY | numlockmask, c->win, False, BUTTONMASK,
1195 GrabModeAsync, GrabModeSync, None, None);
1196 XGrabButton(dpy, Button2, MODKEY | numlockmask | LockMask, c->win, False, BUTTONMASK,
1197 GrabModeAsync, GrabModeSync, None, None);
1199 XGrabButton(dpy, Button3, MODKEY, c->win, False, BUTTONMASK,
1200 GrabModeAsync, GrabModeSync, None, None);
1201 XGrabButton(dpy, Button3, MODKEY | LockMask, c->win, False, BUTTONMASK,
1202 GrabModeAsync, GrabModeSync, None, None);
1203 XGrabButton(dpy, Button3, MODKEY | numlockmask, c->win, False, BUTTONMASK,
1204 GrabModeAsync, GrabModeSync, None, None);
1205 XGrabButton(dpy, Button3, MODKEY | numlockmask | LockMask, c->win, False, BUTTONMASK,
1206 GrabModeAsync, GrabModeSync, None, None);
1207 } else {
1208 XGrabButton(dpy, AnyButton, AnyModifier, c->win, False, BUTTONMASK,
1209 GrabModeAsync, GrabModeSync, None, None);
1213 static void
1214 setclientstate(Client *c, long state) {
1215 long data[] = {state, None};
1216 XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1217 PropModeReplace, (unsigned char *)data, 2);
1220 static int
1221 xerrordummy(Display *dsply, XErrorEvent *ee) {
1222 return 0;
1227 void
1228 configure(Client *c) {
1229 XEvent synev;
1231 synev.type = ConfigureNotify;
1232 synev.xconfigure.display = dpy;
1233 synev.xconfigure.event = c->win;
1234 synev.xconfigure.window = c->win;
1235 synev.xconfigure.x = c->x;
1236 synev.xconfigure.y = c->y;
1237 synev.xconfigure.width = c->w;
1238 synev.xconfigure.height = c->h;
1239 synev.xconfigure.border_width = c->border;
1240 synev.xconfigure.above = None;
1241 XSendEvent(dpy, c->win, True, NoEventMask, &synev);
1244 void
1245 focus(Client *c) {
1246 if(c && !isvisible(c))
1247 return;
1248 if(sel && sel != c) {
1249 grabbuttons(sel, False);
1250 XSetWindowBorder(dpy, sel->win, dc.norm[ColBorder]);
1252 if(c) {
1253 detachstack(c);
1254 c->snext = stack;
1255 stack = c;
1256 grabbuttons(c, True);
1258 sel = c;
1259 drawstatus();
1260 if(!selscreen)
1261 return;
1262 if(c) {
1263 XSetWindowBorder(dpy, c->win, dc.sel[ColBorder]);
1264 XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
1265 } else {
1266 XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
1270 Client *
1271 getclient(Window w) {
1272 Client *c;
1274 for(c = clients; c; c = c->next) {
1275 if(c->win == w) {
1276 return c;
1279 return NULL;
1282 Bool
1283 isprotodel(Client *c) {
1284 int i, n;
1285 Atom *protocols;
1286 Bool ret = False;
1288 if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
1289 for(i = 0; !ret && i < n; i++)
1290 if(protocols[i] == wmatom[WMDelete])
1291 ret = True;
1292 XFree(protocols);
1294 return ret;
1297 void
1298 killclient() {
1299 if(!sel)
1300 return;
1301 if(isprotodel(sel))
1302 sendevent(sel->win, wmatom[WMProtocols], wmatom[WMDelete]);
1303 else
1304 XKillClient(dpy, sel->win);
1307 void
1308 manage(Window w, XWindowAttributes *wa) {
1309 Client *c;
1310 Window trans;
1312 c = emallocz(sizeof(Client));
1313 c->tag = True;
1314 c->win = w;
1315 c->x = wa->x;
1316 c->y = wa->y;
1317 c->w = wa->width;
1318 c->h = wa->height;
1319 if(c->w == sw && c->h == sh) {
1320 c->border = 0;
1321 c->x = sx;
1322 c->y = sy;
1323 } else {
1324 c->border = BORDERPX;
1325 if(c->x + c->w + 2 * c->border > wax + waw)
1326 c->x = wax + waw - c->w - 2 * c->border;
1327 if(c->y + c->h + 2 * c->border > way + wah)
1328 c->y = way + wah - c->h - 2 * c->border;
1329 if(c->x < wax)
1330 c->x = wax;
1331 if(c->y < way)
1332 c->y = way;
1334 updatesizehints(c);
1335 XSelectInput(dpy, c->win,
1336 StructureNotifyMask | PropertyChangeMask | EnterWindowMask);
1337 XGetTransientForHint(dpy, c->win, &trans);
1338 grabbuttons(c, False);
1339 XSetWindowBorder(dpy, c->win, dc.norm[ColBorder]);
1340 updatetitle(c);
1341 settags(c, getclient(trans));
1342 if(!c->isfloat)
1343 c->isfloat = trans || c->isfixed;
1344 if(clients)
1345 clients->prev = c;
1346 c->next = clients;
1347 c->snext = stack;
1348 stack = clients = c;
1349 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
1350 XMapWindow(dpy, c->win);
1351 setclientstate(c, NormalState);
1352 if(isvisible(c))
1353 focus(c);
1354 arrange();
1357 void
1358 resize(Client *c, Bool sizehints) {
1359 float actual, dx, dy, max, min;
1360 XWindowChanges wc;
1362 if(c->w <= 0 || c->h <= 0)
1363 return;
1364 if(sizehints) {
1365 if(c->minw && c->w < c->minw)
1366 c->w = c->minw;
1367 if(c->minh && c->h < c->minh)
1368 c->h = c->minh;
1369 if(c->maxw && c->w > c->maxw)
1370 c->w = c->maxw;
1371 if(c->maxh && c->h > c->maxh)
1372 c->h = c->maxh;
1373 /* inspired by algorithm from fluxbox */
1374 if(c->minay > 0 && c->maxay && (c->h - c->baseh) > 0) {
1375 dx = (float)(c->w - c->basew);
1376 dy = (float)(c->h - c->baseh);
1377 min = (float)(c->minax) / (float)(c->minay);
1378 max = (float)(c->maxax) / (float)(c->maxay);
1379 actual = dx / dy;
1380 if(max > 0 && min > 0 && actual > 0) {
1381 if(actual < min) {
1382 dy = (dx * min + dy) / (min * min + 1);
1383 dx = dy * min;
1384 c->w = (int)dx + c->basew;
1385 c->h = (int)dy + c->baseh;
1387 else if(actual > max) {
1388 dy = (dx * min + dy) / (max * max + 1);
1389 dx = dy * min;
1390 c->w = (int)dx + c->basew;
1391 c->h = (int)dy + c->baseh;
1395 if(c->incw)
1396 c->w -= (c->w - c->basew) % c->incw;
1397 if(c->inch)
1398 c->h -= (c->h - c->baseh) % c->inch;
1400 if(c->w == sw && c->h == sh)
1401 c->border = 0;
1402 else
1403 c->border = BORDERPX;
1404 /* offscreen appearance fixes */
1405 if(c->x > sw)
1406 c->x = sw - c->w - 2 * c->border;
1407 if(c->y > sh)
1408 c->y = sh - c->h - 2 * c->border;
1409 if(c->x + c->w + 2 * c->border < sx)
1410 c->x = sx;
1411 if(c->y + c->h + 2 * c->border < sy)
1412 c->y = sy;
1413 wc.x = c->x;
1414 wc.y = c->y;
1415 wc.width = c->w;
1416 wc.height = c->h;
1417 wc.border_width = c->border;
1418 XConfigureWindow(dpy, c->win, CWX | CWY | CWWidth | CWHeight | CWBorderWidth, &wc);
1419 configure(c);
1420 XSync(dpy, False);
1423 void
1424 updatesizehints(Client *c) {
1425 long msize;
1426 XSizeHints size;
1428 if(!XGetWMNormalHints(dpy, c->win, &size, &msize) || !size.flags)
1429 size.flags = PSize;
1430 c->flags = size.flags;
1431 if(c->flags & PBaseSize) {
1432 c->basew = size.base_width;
1433 c->baseh = size.base_height;
1434 } else {
1435 c->basew = c->baseh = 0;
1437 if(c->flags & PResizeInc) {
1438 c->incw = size.width_inc;
1439 c->inch = size.height_inc;
1440 } else {
1441 c->incw = c->inch = 0;
1443 if(c->flags & PMaxSize) {
1444 c->maxw = size.max_width;
1445 c->maxh = size.max_height;
1446 } else {
1447 c->maxw = c->maxh = 0;
1449 if(c->flags & PMinSize) {
1450 c->minw = size.min_width;
1451 c->minh = size.min_height;
1452 } else {
1453 c->minw = c->minh = 0;
1455 if(c->flags & PAspect) {
1456 c->minax = size.min_aspect.x;
1457 c->minay = size.min_aspect.y;
1458 c->maxax = size.max_aspect.x;
1459 c->maxay = size.max_aspect.y;
1460 } else {
1461 c->minax = c->minay = c->maxax = c->maxay = 0;
1463 c->isfixed = (c->maxw && c->minw && c->maxh && c->minh &&
1464 c->maxw == c->minw && c->maxh == c->minh);
1467 void
1468 updatetitle(Client *c) {
1469 char **list = NULL;
1470 int n;
1471 XTextProperty name;
1473 name.nitems = 0;
1474 c->name[0] = 0;
1475 XGetTextProperty(dpy, c->win, &name, netatom[NetWMName]);
1476 if(!name.nitems)
1477 XGetWMName(dpy, c->win, &name);
1478 if(!name.nitems)
1479 return;
1480 if(name.encoding == XA_STRING)
1481 strncpy(c->name, (char *)name.value, sizeof c->name);
1482 else {
1483 if(XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success && n > 0 && *list) {
1484 strncpy(c->name, *list, sizeof c->name);
1485 XFreeStringList(list);
1488 XFree(name.value);
1491 void
1492 unmanage(Client *c) {
1493 Client *nc;
1495 /* The server grab construct avoids race conditions. */
1496 XGrabServer(dpy);
1497 XSetErrorHandler(xerrordummy);
1498 detach(c);
1499 detachstack(c);
1500 if(sel == c) {
1501 for(nc = stack; nc && !isvisible(nc); nc = nc->snext);
1502 focus(nc);
1504 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1505 setclientstate(c, WithdrawnState);
1506 free(c);
1507 XSync(dpy, False);
1508 XSetErrorHandler(xerror);
1509 XUngrabServer(dpy);
1510 arrange();
1531 /* static */
1534 static void
1535 cleanup(void) {
1536 close(STDIN_FILENO);
1537 while(stack) {
1538 resize(stack, True);
1539 unmanage(stack);
1541 if(dc.font.set)
1542 XFreeFontSet(dpy, dc.font.set);
1543 else
1544 XFreeFont(dpy, dc.font.xfont);
1545 XUngrabKey(dpy, AnyKey, AnyModifier, root);
1546 XFreePixmap(dpy, dc.drawable);
1547 XFreeGC(dpy, dc.gc);
1548 XDestroyWindow(dpy, barwin);
1549 XFreeCursor(dpy, cursor[CurNormal]);
1550 XFreeCursor(dpy, cursor[CurResize]);
1551 XFreeCursor(dpy, cursor[CurMove]);
1552 XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime);
1553 XSync(dpy, False);
1556 static void
1557 scan(void) {
1558 unsigned int i, num;
1559 Window *wins, d1, d2;
1560 XWindowAttributes wa;
1562 wins = NULL;
1563 if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1564 for(i = 0; i < num; i++) {
1565 if(!XGetWindowAttributes(dpy, wins[i], &wa))
1566 continue;
1567 if(wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1568 continue;
1569 if(wa.map_state == IsViewable)
1570 manage(wins[i], &wa);
1573 if(wins)
1574 XFree(wins);
1577 static void
1578 setup(void) {
1579 int i, j;
1580 unsigned int mask;
1581 Window w;
1582 XModifierKeymap *modmap;
1583 XSetWindowAttributes wa;
1585 /* init atoms */
1586 wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1587 wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1588 wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1589 netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1590 netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1591 XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1592 PropModeReplace, (unsigned char *) netatom, NetLast);
1593 /* init cursors */
1594 cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1595 cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1596 cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1597 /* init modifier map */
1598 numlockmask = 0;
1599 modmap = XGetModifierMapping(dpy);
1600 for (i = 0; i < 8; i++) {
1601 for (j = 0; j < modmap->max_keypermod; j++) {
1602 if(modmap->modifiermap[i * modmap->max_keypermod + j] == XKeysymToKeycode(dpy, XK_Num_Lock))
1603 numlockmask = (1 << i);
1606 XFreeModifiermap(modmap);
1607 /* select for events */
1608 wa.event_mask = SubstructureRedirectMask | SubstructureNotifyMask
1609 | EnterWindowMask | LeaveWindowMask;
1610 wa.cursor = cursor[CurNormal];
1611 XChangeWindowAttributes(dpy, root, CWEventMask | CWCursor, &wa);
1612 grabkeys();
1613 initrregs();
1614 ntags = 2;
1615 seltag = True;
1616 /* style */
1617 dc.norm[ColBorder] = getcolor(NORMBORDERCOLOR);
1618 dc.norm[ColBG] = getcolor(NORMBGCOLOR);
1619 dc.norm[ColFG] = getcolor(NORMFGCOLOR);
1620 dc.sel[ColBorder] = getcolor(SELBORDERCOLOR);
1621 dc.sel[ColBG] = getcolor(SELBGCOLOR);
1622 dc.sel[ColFG] = getcolor(SELFGCOLOR);
1623 setfont(FONT);
1624 /* geometry */
1625 sx = sy = 0;
1626 sw = DisplayWidth(dpy, screen);
1627 sh = DisplayHeight(dpy, screen);
1628 nmaster = NMASTER;
1629 bmw = 1;
1630 /* bar */
1631 dc.h = bh = dc.font.height + 2;
1632 wa.override_redirect = 1;
1633 wa.background_pixmap = ParentRelative;
1634 wa.event_mask = ButtonPressMask | ExposureMask;
1635 barwin = XCreateWindow(dpy, root, sx, sy, sw, bh, 0,
1636 DefaultDepth(dpy, screen), CopyFromParent, DefaultVisual(dpy, screen),
1637 CWOverrideRedirect | CWBackPixmap | CWEventMask, &wa);
1638 XDefineCursor(dpy, barwin, cursor[CurNormal]);
1639 XMapRaised(dpy, barwin);
1640 strcpy(stext, "dwm-"VERSION);
1641 /* windowarea */
1642 wax = sx;
1643 way = sy + bh;
1644 wah = sh - bh;
1645 waw = sw;
1646 /* pixmap for everything */
1647 dc.drawable = XCreatePixmap(dpy, root, sw, bh, DefaultDepth(dpy, screen));
1648 dc.gc = XCreateGC(dpy, root, 0, 0);
1649 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
1650 /* multihead support */
1651 selscreen = XQueryPointer(dpy, root, &w, &w, &i, &i, &i, &i, &mask);
1654 /*
1655 * Startup Error handler to check if another window manager
1656 * is already running.
1657 */
1658 static int
1659 xerrorstart(Display *dsply, XErrorEvent *ee) {
1660 otherwm = True;
1661 return -1;
1666 void
1667 sendevent(Window w, Atom a, long value) {
1668 XEvent e;
1670 e.type = ClientMessage;
1671 e.xclient.window = w;
1672 e.xclient.message_type = a;
1673 e.xclient.format = 32;
1674 e.xclient.data.l[0] = value;
1675 e.xclient.data.l[1] = CurrentTime;
1676 XSendEvent(dpy, w, False, NoEventMask, &e);
1677 XSync(dpy, False);
1680 void
1681 quit() {
1682 readin = running = False;
1685 /* There's no way to check accesses to destroyed windows, thus those cases are
1686 * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
1687 * default error handler, which may call exit.
1688 */
1689 int
1690 xerror(Display *dpy, XErrorEvent *ee) {
1691 if(ee->error_code == BadWindow
1692 || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1693 || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1694 || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1695 || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1696 || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1697 || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1698 || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1699 return 0;
1700 fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1701 ee->request_code, ee->error_code);
1702 return xerrorxlib(dpy, ee); /* may call exit */
1705 int
1706 main(int argc, char *argv[]) {
1707 char *p;
1708 int r, xfd;
1709 fd_set rd;
1711 if(argc == 2 && !strncmp("-v", argv[1], 3)) {
1712 fputs("dwm-"VERSION", (C)opyright MMVI-MMVII Anselm R. Garbe\n", stdout);
1713 exit(EXIT_SUCCESS);
1714 } else if(argc != 1) {
1715 eprint("usage: dwm [-v]\n");
1717 setlocale(LC_CTYPE, "");
1718 dpy = XOpenDisplay(0);
1719 if(!dpy) {
1720 eprint("dwm: cannot open display\n");
1722 xfd = ConnectionNumber(dpy);
1723 screen = DefaultScreen(dpy);
1724 root = RootWindow(dpy, screen);
1725 otherwm = False;
1726 XSetErrorHandler(xerrorstart);
1727 /* this causes an error if some other window manager is running */
1728 XSelectInput(dpy, root, SubstructureRedirectMask);
1729 XSync(dpy, False);
1730 if(otherwm) {
1731 eprint("dwm: another window manager is already running\n");
1734 XSync(dpy, False);
1735 XSetErrorHandler(NULL);
1736 xerrorxlib = XSetErrorHandler(xerror);
1737 XSync(dpy, False);
1738 setup();
1739 drawstatus();
1740 scan();
1742 /* main event loop, also reads status text from stdin */
1743 XSync(dpy, False);
1744 procevent();
1745 readin = True;
1746 while(running) {
1747 FD_ZERO(&rd);
1748 if(readin)
1749 FD_SET(STDIN_FILENO, &rd);
1750 FD_SET(xfd, &rd);
1751 if(select(xfd + 1, &rd, NULL, NULL, NULL) == -1) {
1752 if(errno == EINTR)
1753 continue;
1754 eprint("select failed\n");
1756 if(FD_ISSET(STDIN_FILENO, &rd)) {
1757 switch(r = read(STDIN_FILENO, stext, sizeof stext - 1)) {
1758 case -1:
1759 strncpy(stext, strerror(errno), sizeof stext - 1);
1760 stext[sizeof stext - 1] = '\0';
1761 readin = False;
1762 break;
1763 case 0:
1764 strncpy(stext, "EOF", 4);
1765 readin = False;
1766 break;
1767 default:
1768 for(stext[r] = '\0', p = stext + strlen(stext) - 1; p >= stext && *p == '\n'; *p-- = '\0');
1769 for(; p >= stext && *p != '\n'; --p);
1770 if(p > stext)
1771 strncpy(stext, p + 1, sizeof stext);
1773 drawstatus();
1775 if(FD_ISSET(xfd, &rd))
1776 procevent();
1778 cleanup();
1779 XCloseDisplay(dpy);
1780 return 0;