aewl

view aewl.c @ 759:45f23169563e

renamed dwm to aewl updated copyright notices updated man page
author meillo@marmaro.de
date Fri, 30 May 2008 22:18:18 +0200
parents dwm.c@bc512840e5a5
children 014c4cb1ae4a
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(); /* toggle the viewed tag */
198 void focusnext(); /* focuses next visible client */
199 void zoom(); /* zooms the focused client to master area */
200 void killclient(); /* kill c nicely */
201 void quit(); /* quit dwm nicely */
202 void togglemode(); /* toggles global arrange function (dotile/dofloat) */
203 void togglefloat(); /* toggles focusesd client between floating/non-floating state */
204 void incnmaster(); /* increments nmaster */
205 void decnmaster(); /* decrements nmaster */
206 void toggletag(); /* 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 int x;
757 int i;
758 Client *c;
759 XButtonPressedEvent *ev = &e->xbutton;
761 if(barwin == ev->window) {
762 if(ev->button == Button1) {
763 toggleview();
764 }
765 return;
766 } else if((c = getclient(ev->window))) {
767 focus(c);
768 if(CLEANMASK(ev->state) != MODKEY)
769 return;
770 if(ev->button == Button1 && (arrange == dofloat || c->isfloat)) {
771 restack();
772 movemouse(c);
773 } else if(ev->button == Button3 && (arrange == dofloat || c->isfloat) && !c->isfixed) {
774 restack();
775 resizemouse(c);
776 }
777 }
778 }
780 static void
781 configurerequest(XEvent *e) {
782 unsigned long newmask;
783 Client *c;
784 XConfigureRequestEvent *ev = &e->xconfigurerequest;
785 XWindowChanges wc;
787 if((c = getclient(ev->window))) {
788 c->ismax = False;
789 if(ev->value_mask & CWX)
790 c->x = ev->x;
791 if(ev->value_mask & CWY)
792 c->y = ev->y;
793 if(ev->value_mask & CWWidth)
794 c->w = ev->width;
795 if(ev->value_mask & CWHeight)
796 c->h = ev->height;
797 if(ev->value_mask & CWBorderWidth)
798 c->border = ev->border_width;
799 wc.x = c->x;
800 wc.y = c->y;
801 wc.width = c->w;
802 wc.height = c->h;
803 newmask = ev->value_mask & (~(CWSibling | CWStackMode | CWBorderWidth));
804 if(newmask)
805 XConfigureWindow(dpy, c->win, newmask, &wc);
806 else
807 configure(c);
808 XSync(dpy, False);
809 if(c->isfloat) {
810 resize(c, False);
811 if(!isvisible(c))
812 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
813 }
814 else
815 arrange();
816 } else {
817 wc.x = ev->x;
818 wc.y = ev->y;
819 wc.width = ev->width;
820 wc.height = ev->height;
821 wc.border_width = ev->border_width;
822 wc.sibling = ev->above;
823 wc.stack_mode = ev->detail;
824 XConfigureWindow(dpy, ev->window, ev->value_mask, &wc);
825 XSync(dpy, False);
826 }
827 }
829 static void
830 destroynotify(XEvent *e) {
831 Client *c;
832 XDestroyWindowEvent *ev = &e->xdestroywindow;
834 if((c = getclient(ev->window)))
835 unmanage(c);
836 }
838 static void
839 enternotify(XEvent *e) {
840 Client *c;
841 XCrossingEvent *ev = &e->xcrossing;
843 if(ev->mode != NotifyNormal || ev->detail == NotifyInferior)
844 return;
845 if((c = getclient(ev->window)) && isvisible(c))
846 focus(c);
847 else if(ev->window == root) {
848 selscreen = True;
849 for(c = stack; c && !isvisible(c); c = c->snext);
850 focus(c);
851 }
852 }
854 static void
855 expose(XEvent *e) {
856 XExposeEvent *ev = &e->xexpose;
858 if(ev->count == 0) {
859 if(barwin == ev->window)
860 drawstatus();
861 }
862 }
864 static void
865 keypress(XEvent *e) {
866 static unsigned int len = sizeof key / sizeof key[0];
867 unsigned int i;
868 KeySym keysym;
869 XKeyEvent *ev = &e->xkey;
871 keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
872 for(i = 0; i < len; i++) {
873 if(keysym == key[i].keysym && CLEANMASK(key[i].mod) == CLEANMASK(ev->state)) {
874 if(key[i].func)
875 key[i].func(key[i].cmd);
876 }
877 }
878 }
880 static void
881 leavenotify(XEvent *e) {
882 XCrossingEvent *ev = &e->xcrossing;
884 if((ev->window == root) && !ev->same_screen) {
885 selscreen = False;
886 focus(NULL);
887 }
888 }
890 static void
891 mappingnotify(XEvent *e) {
892 XMappingEvent *ev = &e->xmapping;
894 XRefreshKeyboardMapping(ev);
895 if(ev->request == MappingKeyboard)
896 grabkeys();
897 }
899 static void
900 maprequest(XEvent *e) {
901 static XWindowAttributes wa;
902 XMapRequestEvent *ev = &e->xmaprequest;
904 if(!XGetWindowAttributes(dpy, ev->window, &wa))
905 return;
906 if(wa.override_redirect) {
907 XSelectInput(dpy, ev->window,
908 (StructureNotifyMask | PropertyChangeMask));
909 return;
910 }
911 if(!getclient(ev->window))
912 manage(ev->window, &wa);
913 }
915 static void
916 propertynotify(XEvent *e) {
917 Client *c;
918 Window trans;
919 XPropertyEvent *ev = &e->xproperty;
921 if(ev->state == PropertyDelete)
922 return; /* ignore */
923 if((c = getclient(ev->window))) {
924 switch (ev->atom) {
925 default: break;
926 case XA_WM_TRANSIENT_FOR:
927 XGetTransientForHint(dpy, c->win, &trans);
928 if(!c->isfloat && (c->isfloat = (trans != 0)))
929 arrange();
930 break;
931 case XA_WM_NORMAL_HINTS:
932 updatesizehints(c);
933 break;
934 }
935 if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
936 updatetitle(c);
937 if(c == sel)
938 drawstatus();
939 }
940 }
941 }
943 static void
944 unmapnotify(XEvent *e) {
945 Client *c;
946 XUnmapEvent *ev = &e->xunmap;
948 if((c = getclient(ev->window)))
949 unmanage(c);
950 }
954 void (*handler[LASTEvent]) (XEvent *) = {
955 [ButtonPress] = buttonpress,
956 [ConfigureRequest] = configurerequest,
957 [DestroyNotify] = destroynotify,
958 [EnterNotify] = enternotify,
959 [LeaveNotify] = leavenotify,
960 [Expose] = expose,
961 [KeyPress] = keypress,
962 [MappingNotify] = mappingnotify,
963 [MapRequest] = maprequest,
964 [PropertyNotify] = propertynotify,
965 [UnmapNotify] = unmapnotify
966 };
968 void
969 grabkeys(void) {
970 static unsigned int len = sizeof key / sizeof key[0];
971 unsigned int i;
972 KeyCode code;
974 XUngrabKey(dpy, AnyKey, AnyModifier, root);
975 for(i = 0; i < len; i++) {
976 code = XKeysymToKeycode(dpy, key[i].keysym);
977 XGrabKey(dpy, code, key[i].mod, root, True,
978 GrabModeAsync, GrabModeAsync);
979 XGrabKey(dpy, code, key[i].mod | LockMask, root, True,
980 GrabModeAsync, GrabModeAsync);
981 XGrabKey(dpy, code, key[i].mod | numlockmask, root, True,
982 GrabModeAsync, GrabModeAsync);
983 XGrabKey(dpy, code, key[i].mod | numlockmask | LockMask, root, True,
984 GrabModeAsync, GrabModeAsync);
985 }
986 }
988 void
989 procevent(void) {
990 XEvent ev;
992 while(XPending(dpy)) {
993 XNextEvent(dpy, &ev);
994 if(handler[ev.type])
995 (handler[ev.type])(&ev); /* call handler */
996 }
997 }
1013 /* from draw.c */
1014 /* static */
1016 static unsigned int
1017 textnw(const char *text, unsigned int len) {
1018 XRectangle r;
1020 if(dc.font.set) {
1021 XmbTextExtents(dc.font.set, text, len, NULL, &r);
1022 return r.width;
1024 return XTextWidth(dc.font.xfont, text, len);
1027 static void
1028 drawtext(const char *text, unsigned long col[ColLast]) {
1029 int x, y, w, h;
1030 static char buf[256];
1031 unsigned int len, olen;
1032 XGCValues gcv;
1033 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
1035 XSetForeground(dpy, dc.gc, col[ColBG]);
1036 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
1037 if(!text)
1038 return;
1039 w = 0;
1040 olen = len = strlen(text);
1041 if(len >= sizeof buf)
1042 len = sizeof buf - 1;
1043 memcpy(buf, text, len);
1044 buf[len] = 0;
1045 h = dc.font.ascent + dc.font.descent;
1046 y = dc.y + (dc.h / 2) - (h / 2) + dc.font.ascent;
1047 x = dc.x + (h / 2);
1048 /* shorten text if necessary */
1049 while(len && (w = textnw(buf, len)) > dc.w - h)
1050 buf[--len] = 0;
1051 if(len < olen) {
1052 if(len > 1)
1053 buf[len - 1] = '.';
1054 if(len > 2)
1055 buf[len - 2] = '.';
1056 if(len > 3)
1057 buf[len - 3] = '.';
1059 if(w > dc.w)
1060 return; /* too long */
1061 gcv.foreground = col[ColFG];
1062 if(dc.font.set) {
1063 XChangeGC(dpy, dc.gc, GCForeground, &gcv);
1064 XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
1065 } else {
1066 gcv.font = dc.font.xfont->fid;
1067 XChangeGC(dpy, dc.gc, GCForeground | GCFont, &gcv);
1068 XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
1074 void
1075 drawstatus(void) {
1076 int x;
1077 unsigned int i;
1079 dc.x = dc.y = 0;
1080 for(i = 0; i < ntags; i++) {
1081 dc.w = textw(tags[i]);
1082 drawtext(tags[i], ( ((i == 0 && seltag) || (i == 1 && !seltag)) ? dc.sel : dc.norm));
1083 dc.x += dc.w + 1;
1085 dc.w = bmw;
1086 drawtext("", dc.norm);
1087 x = dc.x + dc.w;
1088 dc.w = textw(stext);
1089 dc.x = sw - dc.w;
1090 if(dc.x < x) {
1091 dc.x = x;
1092 dc.w = sw - x;
1094 drawtext(stext, dc.norm);
1095 if((dc.w = dc.x - x) > bh) {
1096 dc.x = x;
1097 drawtext(sel ? sel->name : NULL, dc.norm);
1099 XCopyArea(dpy, dc.drawable, barwin, dc.gc, 0, 0, sw, bh, 0, 0);
1100 XSync(dpy, False);
1103 unsigned long
1104 getcolor(const char *colstr) {
1105 Colormap cmap = DefaultColormap(dpy, screen);
1106 XColor color;
1108 if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
1109 eprint("error, cannot allocate color '%s'\n", colstr);
1110 return color.pixel;
1113 void
1114 setfont(const char *fontstr) {
1115 char *def, **missing;
1116 int i, n;
1118 missing = NULL;
1119 if(dc.font.set)
1120 XFreeFontSet(dpy, dc.font.set);
1121 dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
1122 if(missing) {
1123 while(n--)
1124 fprintf(stderr, "missing fontset: %s\n", missing[n]);
1125 XFreeStringList(missing);
1127 if(dc.font.set) {
1128 XFontSetExtents *font_extents;
1129 XFontStruct **xfonts;
1130 char **font_names;
1131 dc.font.ascent = dc.font.descent = 0;
1132 font_extents = XExtentsOfFontSet(dc.font.set);
1133 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
1134 for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
1135 if(dc.font.ascent < (*xfonts)->ascent)
1136 dc.font.ascent = (*xfonts)->ascent;
1137 if(dc.font.descent < (*xfonts)->descent)
1138 dc.font.descent = (*xfonts)->descent;
1139 xfonts++;
1141 } else {
1142 if(dc.font.xfont)
1143 XFreeFont(dpy, dc.font.xfont);
1144 dc.font.xfont = NULL;
1145 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr)))
1146 eprint("error, cannot load font: '%s'\n", fontstr);
1147 dc.font.ascent = dc.font.xfont->ascent;
1148 dc.font.descent = dc.font.xfont->descent;
1150 dc.font.height = dc.font.ascent + dc.font.descent;
1153 unsigned int
1154 textw(const char *text) {
1155 return textnw(text, strlen(text)) + dc.font.height;
1168 /* from client.c */
1169 /* static */
1171 static void
1172 detachstack(Client *c) {
1173 Client **tc;
1174 for(tc=&stack; *tc && *tc != c; tc=&(*tc)->snext);
1175 *tc = c->snext;
1178 static void
1179 grabbuttons(Client *c, Bool focused) {
1180 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1182 if(focused) {
1183 XGrabButton(dpy, Button1, MODKEY, c->win, False, BUTTONMASK,
1184 GrabModeAsync, GrabModeSync, None, None);
1185 XGrabButton(dpy, Button1, MODKEY | LockMask, c->win, False, BUTTONMASK,
1186 GrabModeAsync, GrabModeSync, None, None);
1187 XGrabButton(dpy, Button1, MODKEY | numlockmask, c->win, False, BUTTONMASK,
1188 GrabModeAsync, GrabModeSync, None, None);
1189 XGrabButton(dpy, Button1, MODKEY | numlockmask | LockMask, c->win, False, BUTTONMASK,
1190 GrabModeAsync, GrabModeSync, None, None);
1192 XGrabButton(dpy, Button2, MODKEY, c->win, False, BUTTONMASK,
1193 GrabModeAsync, GrabModeSync, None, None);
1194 XGrabButton(dpy, Button2, MODKEY | LockMask, c->win, False, BUTTONMASK,
1195 GrabModeAsync, GrabModeSync, None, None);
1196 XGrabButton(dpy, Button2, MODKEY | numlockmask, c->win, False, BUTTONMASK,
1197 GrabModeAsync, GrabModeSync, None, None);
1198 XGrabButton(dpy, Button2, MODKEY | numlockmask | LockMask, c->win, False, BUTTONMASK,
1199 GrabModeAsync, GrabModeSync, None, None);
1201 XGrabButton(dpy, Button3, MODKEY, c->win, False, BUTTONMASK,
1202 GrabModeAsync, GrabModeSync, None, None);
1203 XGrabButton(dpy, Button3, MODKEY | LockMask, c->win, False, BUTTONMASK,
1204 GrabModeAsync, GrabModeSync, None, None);
1205 XGrabButton(dpy, Button3, MODKEY | numlockmask, c->win, False, BUTTONMASK,
1206 GrabModeAsync, GrabModeSync, None, None);
1207 XGrabButton(dpy, Button3, MODKEY | numlockmask | LockMask, c->win, False, BUTTONMASK,
1208 GrabModeAsync, GrabModeSync, None, None);
1209 } else {
1210 XGrabButton(dpy, AnyButton, AnyModifier, c->win, False, BUTTONMASK,
1211 GrabModeAsync, GrabModeSync, None, None);
1215 static void
1216 setclientstate(Client *c, long state) {
1217 long data[] = {state, None};
1218 XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1219 PropModeReplace, (unsigned char *)data, 2);
1222 static int
1223 xerrordummy(Display *dsply, XErrorEvent *ee) {
1224 return 0;
1229 void
1230 configure(Client *c) {
1231 XEvent synev;
1233 synev.type = ConfigureNotify;
1234 synev.xconfigure.display = dpy;
1235 synev.xconfigure.event = c->win;
1236 synev.xconfigure.window = c->win;
1237 synev.xconfigure.x = c->x;
1238 synev.xconfigure.y = c->y;
1239 synev.xconfigure.width = c->w;
1240 synev.xconfigure.height = c->h;
1241 synev.xconfigure.border_width = c->border;
1242 synev.xconfigure.above = None;
1243 XSendEvent(dpy, c->win, True, NoEventMask, &synev);
1246 void
1247 focus(Client *c) {
1248 if(c && !isvisible(c))
1249 return;
1250 if(sel && sel != c) {
1251 grabbuttons(sel, False);
1252 XSetWindowBorder(dpy, sel->win, dc.norm[ColBorder]);
1254 if(c) {
1255 detachstack(c);
1256 c->snext = stack;
1257 stack = c;
1258 grabbuttons(c, True);
1260 sel = c;
1261 drawstatus();
1262 if(!selscreen)
1263 return;
1264 if(c) {
1265 XSetWindowBorder(dpy, c->win, dc.sel[ColBorder]);
1266 XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
1267 } else {
1268 XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
1272 Client *
1273 getclient(Window w) {
1274 Client *c;
1276 for(c = clients; c; c = c->next) {
1277 if(c->win == w) {
1278 return c;
1281 return NULL;
1284 Bool
1285 isprotodel(Client *c) {
1286 int i, n;
1287 Atom *protocols;
1288 Bool ret = False;
1290 if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
1291 for(i = 0; !ret && i < n; i++)
1292 if(protocols[i] == wmatom[WMDelete])
1293 ret = True;
1294 XFree(protocols);
1296 return ret;
1299 void
1300 killclient() {
1301 if(!sel)
1302 return;
1303 if(isprotodel(sel))
1304 sendevent(sel->win, wmatom[WMProtocols], wmatom[WMDelete]);
1305 else
1306 XKillClient(dpy, sel->win);
1309 void
1310 manage(Window w, XWindowAttributes *wa) {
1311 Client *c;
1312 Window trans;
1314 c = emallocz(sizeof(Client));
1315 c->tag = True;
1316 c->win = w;
1317 c->x = wa->x;
1318 c->y = wa->y;
1319 c->w = wa->width;
1320 c->h = wa->height;
1321 if(c->w == sw && c->h == sh) {
1322 c->border = 0;
1323 c->x = sx;
1324 c->y = sy;
1325 } else {
1326 c->border = BORDERPX;
1327 if(c->x + c->w + 2 * c->border > wax + waw)
1328 c->x = wax + waw - c->w - 2 * c->border;
1329 if(c->y + c->h + 2 * c->border > way + wah)
1330 c->y = way + wah - c->h - 2 * c->border;
1331 if(c->x < wax)
1332 c->x = wax;
1333 if(c->y < way)
1334 c->y = way;
1336 updatesizehints(c);
1337 XSelectInput(dpy, c->win,
1338 StructureNotifyMask | PropertyChangeMask | EnterWindowMask);
1339 XGetTransientForHint(dpy, c->win, &trans);
1340 grabbuttons(c, False);
1341 XSetWindowBorder(dpy, c->win, dc.norm[ColBorder]);
1342 updatetitle(c);
1343 settags(c, getclient(trans));
1344 if(!c->isfloat)
1345 c->isfloat = trans || c->isfixed;
1346 if(clients)
1347 clients->prev = c;
1348 c->next = clients;
1349 c->snext = stack;
1350 stack = clients = c;
1351 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
1352 XMapWindow(dpy, c->win);
1353 setclientstate(c, NormalState);
1354 if(isvisible(c))
1355 focus(c);
1356 arrange();
1359 void
1360 resize(Client *c, Bool sizehints) {
1361 float actual, dx, dy, max, min;
1362 XWindowChanges wc;
1364 if(c->w <= 0 || c->h <= 0)
1365 return;
1366 if(sizehints) {
1367 if(c->minw && c->w < c->minw)
1368 c->w = c->minw;
1369 if(c->minh && c->h < c->minh)
1370 c->h = c->minh;
1371 if(c->maxw && c->w > c->maxw)
1372 c->w = c->maxw;
1373 if(c->maxh && c->h > c->maxh)
1374 c->h = c->maxh;
1375 /* inspired by algorithm from fluxbox */
1376 if(c->minay > 0 && c->maxay && (c->h - c->baseh) > 0) {
1377 dx = (float)(c->w - c->basew);
1378 dy = (float)(c->h - c->baseh);
1379 min = (float)(c->minax) / (float)(c->minay);
1380 max = (float)(c->maxax) / (float)(c->maxay);
1381 actual = dx / dy;
1382 if(max > 0 && min > 0 && actual > 0) {
1383 if(actual < min) {
1384 dy = (dx * min + dy) / (min * min + 1);
1385 dx = dy * min;
1386 c->w = (int)dx + c->basew;
1387 c->h = (int)dy + c->baseh;
1389 else if(actual > max) {
1390 dy = (dx * min + dy) / (max * max + 1);
1391 dx = dy * min;
1392 c->w = (int)dx + c->basew;
1393 c->h = (int)dy + c->baseh;
1397 if(c->incw)
1398 c->w -= (c->w - c->basew) % c->incw;
1399 if(c->inch)
1400 c->h -= (c->h - c->baseh) % c->inch;
1402 if(c->w == sw && c->h == sh)
1403 c->border = 0;
1404 else
1405 c->border = BORDERPX;
1406 /* offscreen appearance fixes */
1407 if(c->x > sw)
1408 c->x = sw - c->w - 2 * c->border;
1409 if(c->y > sh)
1410 c->y = sh - c->h - 2 * c->border;
1411 if(c->x + c->w + 2 * c->border < sx)
1412 c->x = sx;
1413 if(c->y + c->h + 2 * c->border < sy)
1414 c->y = sy;
1415 wc.x = c->x;
1416 wc.y = c->y;
1417 wc.width = c->w;
1418 wc.height = c->h;
1419 wc.border_width = c->border;
1420 XConfigureWindow(dpy, c->win, CWX | CWY | CWWidth | CWHeight | CWBorderWidth, &wc);
1421 configure(c);
1422 XSync(dpy, False);
1425 void
1426 updatesizehints(Client *c) {
1427 long msize;
1428 XSizeHints size;
1430 if(!XGetWMNormalHints(dpy, c->win, &size, &msize) || !size.flags)
1431 size.flags = PSize;
1432 c->flags = size.flags;
1433 if(c->flags & PBaseSize) {
1434 c->basew = size.base_width;
1435 c->baseh = size.base_height;
1436 } else {
1437 c->basew = c->baseh = 0;
1439 if(c->flags & PResizeInc) {
1440 c->incw = size.width_inc;
1441 c->inch = size.height_inc;
1442 } else {
1443 c->incw = c->inch = 0;
1445 if(c->flags & PMaxSize) {
1446 c->maxw = size.max_width;
1447 c->maxh = size.max_height;
1448 } else {
1449 c->maxw = c->maxh = 0;
1451 if(c->flags & PMinSize) {
1452 c->minw = size.min_width;
1453 c->minh = size.min_height;
1454 } else {
1455 c->minw = c->minh = 0;
1457 if(c->flags & PAspect) {
1458 c->minax = size.min_aspect.x;
1459 c->minay = size.min_aspect.y;
1460 c->maxax = size.max_aspect.x;
1461 c->maxay = size.max_aspect.y;
1462 } else {
1463 c->minax = c->minay = c->maxax = c->maxay = 0;
1465 c->isfixed = (c->maxw && c->minw && c->maxh && c->minh &&
1466 c->maxw == c->minw && c->maxh == c->minh);
1469 void
1470 updatetitle(Client *c) {
1471 char **list = NULL;
1472 int n;
1473 XTextProperty name;
1475 name.nitems = 0;
1476 c->name[0] = 0;
1477 XGetTextProperty(dpy, c->win, &name, netatom[NetWMName]);
1478 if(!name.nitems)
1479 XGetWMName(dpy, c->win, &name);
1480 if(!name.nitems)
1481 return;
1482 if(name.encoding == XA_STRING)
1483 strncpy(c->name, (char *)name.value, sizeof c->name);
1484 else {
1485 if(XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success && n > 0 && *list) {
1486 strncpy(c->name, *list, sizeof c->name);
1487 XFreeStringList(list);
1490 XFree(name.value);
1493 void
1494 unmanage(Client *c) {
1495 Client *nc;
1497 /* The server grab construct avoids race conditions. */
1498 XGrabServer(dpy);
1499 XSetErrorHandler(xerrordummy);
1500 detach(c);
1501 detachstack(c);
1502 if(sel == c) {
1503 for(nc = stack; nc && !isvisible(nc); nc = nc->snext);
1504 focus(nc);
1506 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1507 setclientstate(c, WithdrawnState);
1508 free(c);
1509 XSync(dpy, False);
1510 XSetErrorHandler(xerror);
1511 XUngrabServer(dpy);
1512 arrange();
1533 /* static */
1536 static void
1537 cleanup(void) {
1538 close(STDIN_FILENO);
1539 while(stack) {
1540 resize(stack, True);
1541 unmanage(stack);
1543 if(dc.font.set)
1544 XFreeFontSet(dpy, dc.font.set);
1545 else
1546 XFreeFont(dpy, dc.font.xfont);
1547 XUngrabKey(dpy, AnyKey, AnyModifier, root);
1548 XFreePixmap(dpy, dc.drawable);
1549 XFreeGC(dpy, dc.gc);
1550 XDestroyWindow(dpy, barwin);
1551 XFreeCursor(dpy, cursor[CurNormal]);
1552 XFreeCursor(dpy, cursor[CurResize]);
1553 XFreeCursor(dpy, cursor[CurMove]);
1554 XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime);
1555 XSync(dpy, False);
1558 static void
1559 scan(void) {
1560 unsigned int i, num;
1561 Window *wins, d1, d2;
1562 XWindowAttributes wa;
1564 wins = NULL;
1565 if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1566 for(i = 0; i < num; i++) {
1567 if(!XGetWindowAttributes(dpy, wins[i], &wa))
1568 continue;
1569 if(wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1570 continue;
1571 if(wa.map_state == IsViewable)
1572 manage(wins[i], &wa);
1575 if(wins)
1576 XFree(wins);
1579 static void
1580 setup(void) {
1581 int i, j;
1582 unsigned int mask;
1583 Window w;
1584 XModifierKeymap *modmap;
1585 XSetWindowAttributes wa;
1587 /* init atoms */
1588 wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1589 wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1590 wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1591 netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1592 netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1593 XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1594 PropModeReplace, (unsigned char *) netatom, NetLast);
1595 /* init cursors */
1596 cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1597 cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1598 cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1599 /* init modifier map */
1600 numlockmask = 0;
1601 modmap = XGetModifierMapping(dpy);
1602 for (i = 0; i < 8; i++) {
1603 for (j = 0; j < modmap->max_keypermod; j++) {
1604 if(modmap->modifiermap[i * modmap->max_keypermod + j] == XKeysymToKeycode(dpy, XK_Num_Lock))
1605 numlockmask = (1 << i);
1608 XFreeModifiermap(modmap);
1609 /* select for events */
1610 wa.event_mask = SubstructureRedirectMask | SubstructureNotifyMask
1611 | EnterWindowMask | LeaveWindowMask;
1612 wa.cursor = cursor[CurNormal];
1613 XChangeWindowAttributes(dpy, root, CWEventMask | CWCursor, &wa);
1614 grabkeys();
1615 initrregs();
1616 ntags = 2;
1617 seltag = True;
1618 /* style */
1619 dc.norm[ColBorder] = getcolor(NORMBORDERCOLOR);
1620 dc.norm[ColBG] = getcolor(NORMBGCOLOR);
1621 dc.norm[ColFG] = getcolor(NORMFGCOLOR);
1622 dc.sel[ColBorder] = getcolor(SELBORDERCOLOR);
1623 dc.sel[ColBG] = getcolor(SELBGCOLOR);
1624 dc.sel[ColFG] = getcolor(SELFGCOLOR);
1625 setfont(FONT);
1626 /* geometry */
1627 sx = sy = 0;
1628 sw = DisplayWidth(dpy, screen);
1629 sh = DisplayHeight(dpy, screen);
1630 nmaster = NMASTER;
1631 bmw = 1;
1632 /* bar */
1633 dc.h = bh = dc.font.height + 2;
1634 wa.override_redirect = 1;
1635 wa.background_pixmap = ParentRelative;
1636 wa.event_mask = ButtonPressMask | ExposureMask;
1637 barwin = XCreateWindow(dpy, root, sx, sy, sw, bh, 0,
1638 DefaultDepth(dpy, screen), CopyFromParent, DefaultVisual(dpy, screen),
1639 CWOverrideRedirect | CWBackPixmap | CWEventMask, &wa);
1640 XDefineCursor(dpy, barwin, cursor[CurNormal]);
1641 XMapRaised(dpy, barwin);
1642 strcpy(stext, "dwm-"VERSION);
1643 /* windowarea */
1644 wax = sx;
1645 way = sy + bh;
1646 wah = sh - bh;
1647 waw = sw;
1648 /* pixmap for everything */
1649 dc.drawable = XCreatePixmap(dpy, root, sw, bh, DefaultDepth(dpy, screen));
1650 dc.gc = XCreateGC(dpy, root, 0, 0);
1651 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
1652 /* multihead support */
1653 selscreen = XQueryPointer(dpy, root, &w, &w, &i, &i, &i, &i, &mask);
1656 /*
1657 * Startup Error handler to check if another window manager
1658 * is already running.
1659 */
1660 static int
1661 xerrorstart(Display *dsply, XErrorEvent *ee) {
1662 otherwm = True;
1663 return -1;
1668 void
1669 sendevent(Window w, Atom a, long value) {
1670 XEvent e;
1672 e.type = ClientMessage;
1673 e.xclient.window = w;
1674 e.xclient.message_type = a;
1675 e.xclient.format = 32;
1676 e.xclient.data.l[0] = value;
1677 e.xclient.data.l[1] = CurrentTime;
1678 XSendEvent(dpy, w, False, NoEventMask, &e);
1679 XSync(dpy, False);
1682 void
1683 quit() {
1684 readin = running = False;
1687 /* There's no way to check accesses to destroyed windows, thus those cases are
1688 * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
1689 * default error handler, which may call exit.
1690 */
1691 int
1692 xerror(Display *dpy, XErrorEvent *ee) {
1693 if(ee->error_code == BadWindow
1694 || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1695 || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1696 || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1697 || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1698 || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1699 || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1700 || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1701 return 0;
1702 fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1703 ee->request_code, ee->error_code);
1704 return xerrorxlib(dpy, ee); /* may call exit */
1707 int
1708 main(int argc, char *argv[]) {
1709 char *p;
1710 int r, xfd;
1711 fd_set rd;
1713 if(argc == 2 && !strncmp("-v", argv[1], 3)) {
1714 fputs("dwm-"VERSION", (C)opyright MMVI-MMVII Anselm R. Garbe\n", stdout);
1715 exit(EXIT_SUCCESS);
1716 } else if(argc != 1) {
1717 eprint("usage: dwm [-v]\n");
1719 setlocale(LC_CTYPE, "");
1720 dpy = XOpenDisplay(0);
1721 if(!dpy) {
1722 eprint("dwm: cannot open display\n");
1724 xfd = ConnectionNumber(dpy);
1725 screen = DefaultScreen(dpy);
1726 root = RootWindow(dpy, screen);
1727 otherwm = False;
1728 XSetErrorHandler(xerrorstart);
1729 /* this causes an error if some other window manager is running */
1730 XSelectInput(dpy, root, SubstructureRedirectMask);
1731 XSync(dpy, False);
1732 if(otherwm) {
1733 eprint("dwm: another window manager is already running\n");
1736 XSync(dpy, False);
1737 XSetErrorHandler(NULL);
1738 xerrorxlib = XSetErrorHandler(xerror);
1739 XSync(dpy, False);
1740 setup();
1741 drawstatus();
1742 scan();
1744 /* main event loop, also reads status text from stdin */
1745 XSync(dpy, False);
1746 procevent();
1747 readin = True;
1748 while(running) {
1749 FD_ZERO(&rd);
1750 if(readin)
1751 FD_SET(STDIN_FILENO, &rd);
1752 FD_SET(xfd, &rd);
1753 if(select(xfd + 1, &rd, NULL, NULL, NULL) == -1) {
1754 if(errno == EINTR)
1755 continue;
1756 eprint("select failed\n");
1758 if(FD_ISSET(STDIN_FILENO, &rd)) {
1759 switch(r = read(STDIN_FILENO, stext, sizeof stext - 1)) {
1760 case -1:
1761 strncpy(stext, strerror(errno), sizeof stext - 1);
1762 stext[sizeof stext - 1] = '\0';
1763 readin = False;
1764 break;
1765 case 0:
1766 strncpy(stext, "EOF", 4);
1767 readin = False;
1768 break;
1769 default:
1770 for(stext[r] = '\0', p = stext + strlen(stext) - 1; p >= stext && *p == '\n'; *p-- = '\0');
1771 for(; p >= stext && *p != '\n'; --p);
1772 if(p > stext)
1773 strncpy(stext, p + 1, sizeof stext);
1775 drawstatus();
1777 if(FD_ISSET(xfd, &rd))
1778 procevent();
1780 cleanup();
1781 XCloseDisplay(dpy);
1782 return 0;