aewl

view aewl.c @ 762:3f0b245732fc

changed terminology: "tag" is now "group"
author meillo@marmaro.de
date Fri, 05 Dec 2008 16:03:45 +0100
parents 59ce221b9a37
children 17428bca4a12
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 * domax() 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 group;
90 Client *next;
91 Client *prev;
92 Client *snext;
93 Window win;
94 };
96 typedef struct {
97 const char *clpattern;
98 int group;
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 char stext[256]; /* status text */
121 int bh, bmw; /* bar height, bar mode label width */
122 int screen, sx, sy, sw, sh; /* screen geometry */
123 int wax, way, wah, waw; /* windowarea geometry */
124 unsigned int nmaster; /* number of master clients */
125 unsigned int numlockmask; /* dynamic lock mask */
126 void (*handler[LASTEvent])(XEvent *); /* event handler */
127 void (*arrange)(void); /* arrange function, indicates mode */
128 Atom wmatom[WMLast], netatom[NetLast];
129 Bool running, selscreen, selgroup;
130 Client *clients, *sel, *stack; /* global client list and stack */
131 Cursor cursor[CurLast];
132 DC dc; /* global draw context */
133 Display *dpy;
134 Window root, barwin;
136 Bool running = True;
137 Bool selscreen = True;
138 Client *clients = NULL;
139 Client *sel = NULL;
140 Client *stack = NULL;
141 DC dc = {0};
143 static int (*xerrorxlib)(Display *, XErrorEvent *);
144 static Bool otherwm, readin;
145 static RReg *rreg = NULL;
146 static unsigned int len = 0;
149 RULES
152 /* client.c */
153 void configure(Client *c); /* send synthetic configure event */
154 void focus(Client *c); /* focus c, c may be NULL */
155 Client *getclient(Window w); /* return client of w */
156 Bool isprotodel(Client *c); /* returns True if c->win supports wmatom[WMDelete] */
157 void manage(Window w, XWindowAttributes *wa); /* manage new client */
158 void resize(Client *c, Bool sizehints); /* resize c*/
159 void updatesizehints(Client *c); /* update the size hint variables of c */
160 void updatetitle(Client *c); /* update the name of c */
161 void unmanage(Client *c); /* destroy c */
163 /* draw.c */
164 void drawstatus(void); /* draw the bar */
165 unsigned long getcolor(const char *colstr); /* return color of colstr */
166 void setfont(const char *fontstr); /* set the font for DC */
167 unsigned int textw(const char *text); /* return the width of text in px*/
169 /* event.c */
170 void grabkeys(void); /* grab all keys defined in config.h */
171 void procevent(void); /* process pending X events */
173 /* main.c */
174 void sendevent(Window w, Atom a, long value); /* send synthetic event to w */
175 int xerror(Display *dsply, XErrorEvent *ee); /* dwm's X error handler */
177 /* tag.c */
178 void initrregs(void); /* initialize regexps of rules defined in config.h */
179 Client *getnext(Client *c); /* returns next visible client */
180 void setgroup(Client *c, Client *trans); /* sets group of c */
182 /* util.c */
183 void *emallocz(unsigned int size); /* allocates zero-initialized memory, exits on error */
184 void eprint(const char *errstr, ...); /* prints errstr and exits with 1 */
186 /* view.c */
187 void detach(Client *c); /* detaches c from global client list */
188 void dotile(void); /* arranges all windows tiled */
189 void domax(void); /* arranges all windows fullscreen */
190 Bool isvisible(Client *c); /* returns True if client is visible */
191 void restack(void); /* restores z layers of all clients */
194 void toggleview(void); /* toggle the viewed group */
195 void focusnext(void); /* focuses next visible client */
196 void zoom(void); /* zooms the focused client to master area */
197 void killclient(void); /* kill c nicely */
198 void quit(void); /* quit dwm nicely */
199 void togglemode(void); /* toggles global arrange function (dotile/domax) */
200 void togglefloat(void); /* toggles focusesd client between floating/non-floating state */
201 void incnmaster(void); /* increments nmaster */
202 void decnmaster(void); /* decrements nmaster */
203 void togglegroup(void); /* toggles c group */
204 void spawn(const char* cmd); /* forks a new subprocess with cmd */
215 /* from view.c */
216 /* static */
218 static Client *
219 nexttiled(Client *c) {
220 for(c = getnext(c); c && c->isfloat; c = getnext(c->next));
221 return c;
222 }
224 static void
225 togglemax(Client *c) {
226 XEvent ev;
228 if(c->isfixed)
229 return;
231 if((c->ismax = !c->ismax)) {
232 c->rx = c->x; c->x = wax;
233 c->ry = c->y; c->y = way;
234 c->rw = c->w; c->w = waw - 2 * BORDERPX;
235 c->rh = c->h; c->h = wah - 2 * BORDERPX;
236 }
237 else {
238 c->x = c->rx;
239 c->y = c->ry;
240 c->w = c->rw;
241 c->h = c->rh;
242 }
243 resize(c, True);
244 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
245 }
249 void (*arrange)(void) = DEFMODE;
251 void
252 detach(Client *c) {
253 if(c->prev)
254 c->prev->next = c->next;
255 if(c->next)
256 c->next->prev = c->prev;
257 if(c == clients)
258 clients = c->next;
259 c->next = c->prev = NULL;
260 }
262 void
263 dotile(void) {
264 unsigned int i, n, mw, mh, tw, th;
265 Client *c;
267 for(n = 0, c = nexttiled(clients); c; c = nexttiled(c->next))
268 n++;
269 /* window geoms */
270 mh = (n > nmaster) ? wah / nmaster : wah / (n > 0 ? n : 1);
271 mw = (n > nmaster) ? waw / 2 : waw;
272 th = (n > nmaster) ? wah / (n - nmaster) : 0;
273 tw = waw - mw;
275 for(i = 0, c = clients; c; c = c->next)
276 if(isvisible(c)) {
277 if(c->isfloat) {
278 resize(c, True);
279 continue;
280 }
281 c->ismax = False;
282 c->x = wax;
283 c->y = way;
284 if(i < nmaster) {
285 c->y += i * mh;
286 c->w = mw - 2 * BORDERPX;
287 c->h = mh - 2 * BORDERPX;
288 }
289 else { /* tile window */
290 c->x += mw;
291 c->w = tw - 2 * BORDERPX;
292 if(th > 2 * BORDERPX) {
293 c->y += (i - nmaster) * th;
294 c->h = th - 2 * BORDERPX;
295 }
296 else /* fallback if th <= 2 * BORDERPX */
297 c->h = wah - 2 * BORDERPX;
298 }
299 resize(c, False);
300 i++;
301 }
302 else
303 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
304 if(!sel || !isvisible(sel)) {
305 for(c = stack; c && !isvisible(c); c = c->snext);
306 focus(c);
307 }
308 restack();
309 }
311 /* begin code by mitch */
312 void
313 arrangemax(Client *c) {
314 if(c == sel) {
315 c->ismax = True;
316 c->x = sx;
317 c->y = bh;
318 c->w = sw - 2 * BORDERPX;
319 c->h = sh - bh - 2 * BORDERPX;
320 XRaiseWindow(dpy, c->win);
321 } else {
322 c->ismax = False;
323 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
324 XLowerWindow(dpy, c->win);
325 }
326 }
328 void
329 domax(void) {
330 Client *c;
332 for(c = clients; c; c = c->next) {
333 if(isvisible(c)) {
334 if(c->isfloat) {
335 resize(c, True);
336 continue;
337 }
338 arrangemax(c);
339 resize(c, False);
340 } else {
341 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
342 }
344 }
345 if(!sel || !isvisible(sel)) {
346 for(c = stack; c && !isvisible(c); c = c->snext);
347 focus(c);
348 }
349 restack();
350 }
351 /* end code by mitch */
353 void
354 focusnext() {
355 Client *c;
357 if(!sel)
358 return;
359 if(!(c = getnext(sel->next)))
360 c = getnext(clients);
361 if(c) {
362 focus(c);
363 restack();
364 }
365 }
367 void
368 incnmaster() {
369 if(wah / (nmaster + 1) <= 2 * BORDERPX)
370 return;
371 nmaster++;
372 if(sel)
373 arrange();
374 else
375 drawstatus();
376 }
378 void
379 decnmaster() {
380 if(nmaster <= 1)
381 return;
382 nmaster--;
383 if(sel)
384 arrange();
385 else
386 drawstatus();
387 }
389 Bool
390 isvisible(Client *c) {
391 return (c->group == selgroup);
392 }
394 void
395 restack(void) {
396 Client *c;
397 XEvent ev;
399 drawstatus();
400 if(!sel)
401 return;
402 if(sel->isfloat)
403 XRaiseWindow(dpy, sel->win);
405 /* begin code by mitch */
406 if(arrange == domax) {
407 for(c = nexttiled(clients); c; c = nexttiled(c->next)) {
408 arrangemax(c);
409 resize(c, False);
410 }
412 } else if (arrange == dotile) {
413 /* end code by mitch */
415 if(!sel->isfloat)
416 XLowerWindow(dpy, sel->win);
417 for(c = nexttiled(clients); c; c = nexttiled(c->next)) {
418 if(c == sel)
419 continue;
420 XLowerWindow(dpy, c->win);
421 }
422 }
423 XSync(dpy, False);
424 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
425 }
427 void
428 togglefloat() {
429 if (!sel)
430 return;
431 sel->isfloat = !sel->isfloat;
432 arrange();
433 }
435 void
436 togglemode() {
437 /* only toggle between tile and max - float is just available through togglefloat */
438 arrange = (arrange == dotile) ? domax : dotile;
439 if(sel)
440 arrange();
441 else
442 drawstatus();
443 }
445 void
446 toggleview() {
447 selgroup = !selgroup;
448 arrange();
449 }
451 void
452 zoom() {
453 unsigned int n;
454 Client *c;
456 if(!sel)
457 return;
458 if(sel->isfloat) {
459 togglemax(sel);
460 return;
461 }
462 for(n = 0, c = nexttiled(clients); c; c = nexttiled(c->next))
463 n++;
465 if((c = sel) == nexttiled(clients))
466 if(!(c = nexttiled(c->next)))
467 return;
468 detach(c);
469 if(clients)
470 clients->prev = c;
471 c->next = clients;
472 clients = c;
473 focus(c);
474 arrange();
475 }
492 /* from util.c */
495 void *
496 emallocz(unsigned int size) {
497 void *res = calloc(1, size);
499 if(!res)
500 eprint("fatal: could not malloc() %u bytes\n", size);
501 return res;
502 }
504 void
505 eprint(const char *errstr, ...) {
506 va_list ap;
508 va_start(ap, errstr);
509 vfprintf(stderr, errstr, ap);
510 va_end(ap);
511 exit(EXIT_FAILURE);
512 }
514 void
515 spawn(const char* cmd) {
516 static char *shell = NULL;
518 if(!shell && !(shell = getenv("SHELL")))
519 shell = "/bin/sh";
520 if(!cmd)
521 return;
522 /* The double-fork construct avoids zombie processes and keeps the code
523 * clean from stupid signal handlers. */
524 if(fork() == 0) {
525 if(fork() == 0) {
526 if(dpy)
527 close(ConnectionNumber(dpy));
528 setsid();
529 execl(shell, shell, "-c", cmd, (char *)NULL);
530 fprintf(stderr, "dwm: execl '%s -c %s'", shell, cmd);
531 perror(" failed");
532 }
533 exit(0);
534 }
535 wait(0);
536 }
550 /* from tag.c */
552 /* static */
554 Client *
555 getnext(Client *c) {
556 for(; c && !isvisible(c); c = c->next);
557 return c;
558 }
560 void
561 initrregs(void) {
562 unsigned int i;
563 regex_t *reg;
565 if(rreg)
566 return;
567 len = sizeof rule / sizeof rule[0];
568 rreg = emallocz(len * sizeof(RReg));
569 for(i = 0; i < len; i++) {
570 if(rule[i].clpattern) {
571 reg = emallocz(sizeof(regex_t));
572 if(regcomp(reg, rule[i].clpattern, REG_EXTENDED))
573 free(reg);
574 else
575 rreg[i].clregex = reg;
576 }
577 }
578 }
580 void
581 setgroup(Client *c, Client *trans) {
582 char prop[512];
583 unsigned int i;
584 regmatch_t tmp;
585 Bool matched = (trans != NULL);
586 XClassHint ch = { 0 };
588 if(matched) {
589 c->group = trans->group;
590 } else {
591 XGetClassHint(dpy, c->win, &ch);
592 snprintf(prop, sizeof prop, "%s:%s:%s",
593 ch.res_class ? ch.res_class : "",
594 ch.res_name ? ch.res_name : "", c->name);
595 for(i = 0; i < len; i++)
596 if(rreg[i].clregex && !regexec(rreg[i].clregex, prop, 1, &tmp, 0)) {
597 c->isfloat = rule[i].isfloat;
598 if (rule[i].group < 0) {
599 c->group = selgroup;
600 } else if (rule[i].group == 0) {
601 c->group = True;
602 } else {
603 c->group = False;
604 }
605 matched = True;
606 break; /* perform only the first rule matching */
607 }
608 if(ch.res_class)
609 XFree(ch.res_class);
610 if(ch.res_name)
611 XFree(ch.res_name);
612 }
613 if(!matched) {
614 c->group = selgroup;
615 }
616 }
618 void
619 togglegroup() {
620 if(!sel)
621 return;
622 sel->group = !sel->group;
623 toggleview();
624 }
642 /* from event.c */
643 /* static */
645 KEYS
649 static void
650 movemouse(Client *c) {
651 int x1, y1, ocx, ocy, di;
652 unsigned int dui;
653 Window dummy;
654 XEvent ev;
656 ocx = c->x;
657 ocy = c->y;
658 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
659 None, cursor[CurMove], CurrentTime) != GrabSuccess)
660 return;
661 c->ismax = False;
662 XQueryPointer(dpy, root, &dummy, &dummy, &x1, &y1, &di, &di, &dui);
663 for(;;) {
664 XMaskEvent(dpy, MOUSEMASK | ExposureMask | SubstructureRedirectMask, &ev);
665 switch (ev.type) {
666 case ButtonRelease:
667 resize(c, True);
668 XUngrabPointer(dpy, CurrentTime);
669 return;
670 case ConfigureRequest:
671 case Expose:
672 case MapRequest:
673 handler[ev.type](&ev);
674 break;
675 case MotionNotify:
676 XSync(dpy, False);
677 c->x = ocx + (ev.xmotion.x - x1);
678 c->y = ocy + (ev.xmotion.y - y1);
679 if(abs(wax + c->x) < SNAP)
680 c->x = wax;
681 else if(abs((wax + waw) - (c->x + c->w + 2 * c->border)) < SNAP)
682 c->x = wax + waw - c->w - 2 * c->border;
683 if(abs(way - c->y) < SNAP)
684 c->y = way;
685 else if(abs((way + wah) - (c->y + c->h + 2 * c->border)) < SNAP)
686 c->y = way + wah - c->h - 2 * c->border;
687 resize(c, False);
688 break;
689 }
690 }
691 }
693 static void
694 resizemouse(Client *c) {
695 int ocx, ocy;
696 int nw, nh;
697 XEvent ev;
699 ocx = c->x;
700 ocy = c->y;
701 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
702 None, cursor[CurResize], CurrentTime) != GrabSuccess)
703 return;
704 c->ismax = False;
705 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->border - 1, c->h + c->border - 1);
706 for(;;) {
707 XMaskEvent(dpy, MOUSEMASK | ExposureMask | SubstructureRedirectMask , &ev);
708 switch(ev.type) {
709 case ButtonRelease:
710 resize(c, True);
711 XUngrabPointer(dpy, CurrentTime);
712 return;
713 case ConfigureRequest:
714 case Expose:
715 case MapRequest:
716 handler[ev.type](&ev);
717 break;
718 case MotionNotify:
719 XSync(dpy, False);
720 nw = ev.xmotion.x - ocx - 2 * c->border + 1;
721 c->w = nw > 0 ? nw : 1;
722 nh = ev.xmotion.y - ocy - 2 * c->border + 1;
723 c->h = nh > 0 ? nh : 1;
724 resize(c, True);
725 break;
726 }
727 }
728 }
730 static void
731 buttonpress(XEvent *e) {
732 Client *c;
733 XButtonPressedEvent *ev = &e->xbutton;
735 if(barwin == ev->window) {
736 if(ev->button == Button1) {
737 toggleview();
738 }
739 return;
740 } else if((c = getclient(ev->window))) {
741 focus(c);
742 if(CLEANMASK(ev->state) != MODKEY)
743 return;
744 if(ev->button == Button1 && c->isfloat) {
745 restack();
746 movemouse(c);
747 } else if(ev->button == Button3 && c->isfloat && !c->isfixed) {
748 restack();
749 resizemouse(c);
750 }
751 }
752 }
754 static void
755 configurerequest(XEvent *e) {
756 unsigned long newmask;
757 Client *c;
758 XConfigureRequestEvent *ev = &e->xconfigurerequest;
759 XWindowChanges wc;
761 if((c = getclient(ev->window))) {
762 c->ismax = False;
763 if(ev->value_mask & CWX)
764 c->x = ev->x;
765 if(ev->value_mask & CWY)
766 c->y = ev->y;
767 if(ev->value_mask & CWWidth)
768 c->w = ev->width;
769 if(ev->value_mask & CWHeight)
770 c->h = ev->height;
771 if(ev->value_mask & CWBorderWidth)
772 c->border = ev->border_width;
773 wc.x = c->x;
774 wc.y = c->y;
775 wc.width = c->w;
776 wc.height = c->h;
777 newmask = ev->value_mask & (~(CWSibling | CWStackMode | CWBorderWidth));
778 if(newmask)
779 XConfigureWindow(dpy, c->win, newmask, &wc);
780 else
781 configure(c);
782 XSync(dpy, False);
783 if(c->isfloat) {
784 resize(c, False);
785 if(!isvisible(c))
786 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
787 }
788 else
789 arrange();
790 } else {
791 wc.x = ev->x;
792 wc.y = ev->y;
793 wc.width = ev->width;
794 wc.height = ev->height;
795 wc.border_width = ev->border_width;
796 wc.sibling = ev->above;
797 wc.stack_mode = ev->detail;
798 XConfigureWindow(dpy, ev->window, ev->value_mask, &wc);
799 XSync(dpy, False);
800 }
801 }
803 static void
804 destroynotify(XEvent *e) {
805 Client *c;
806 XDestroyWindowEvent *ev = &e->xdestroywindow;
808 if((c = getclient(ev->window)))
809 unmanage(c);
810 }
812 static void
813 enternotify(XEvent *e) {
814 Client *c;
815 XCrossingEvent *ev = &e->xcrossing;
817 if(ev->mode != NotifyNormal || ev->detail == NotifyInferior)
818 return;
819 if((c = getclient(ev->window)) && isvisible(c))
820 focus(c);
821 else if(ev->window == root) {
822 selscreen = True;
823 for(c = stack; c && !isvisible(c); c = c->snext);
824 focus(c);
825 }
826 }
828 static void
829 expose(XEvent *e) {
830 XExposeEvent *ev = &e->xexpose;
832 if(ev->count == 0) {
833 if(barwin == ev->window)
834 drawstatus();
835 }
836 }
838 static void
839 keypress(XEvent *e) {
840 static unsigned int len = sizeof key / sizeof key[0];
841 unsigned int i;
842 KeySym keysym;
843 XKeyEvent *ev = &e->xkey;
845 keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
846 for(i = 0; i < len; i++) {
847 if(keysym == key[i].keysym && CLEANMASK(key[i].mod) == CLEANMASK(ev->state)) {
848 if(key[i].func)
849 key[i].func(key[i].cmd);
850 }
851 }
852 }
854 static void
855 leavenotify(XEvent *e) {
856 XCrossingEvent *ev = &e->xcrossing;
858 if((ev->window == root) && !ev->same_screen) {
859 selscreen = False;
860 focus(NULL);
861 }
862 }
864 static void
865 mappingnotify(XEvent *e) {
866 XMappingEvent *ev = &e->xmapping;
868 XRefreshKeyboardMapping(ev);
869 if(ev->request == MappingKeyboard)
870 grabkeys();
871 }
873 static void
874 maprequest(XEvent *e) {
875 static XWindowAttributes wa;
876 XMapRequestEvent *ev = &e->xmaprequest;
878 if(!XGetWindowAttributes(dpy, ev->window, &wa))
879 return;
880 if(wa.override_redirect) {
881 XSelectInput(dpy, ev->window,
882 (StructureNotifyMask | PropertyChangeMask));
883 return;
884 }
885 if(!getclient(ev->window))
886 manage(ev->window, &wa);
887 }
889 static void
890 propertynotify(XEvent *e) {
891 Client *c;
892 Window trans;
893 XPropertyEvent *ev = &e->xproperty;
895 if(ev->state == PropertyDelete)
896 return; /* ignore */
897 if((c = getclient(ev->window))) {
898 switch (ev->atom) {
899 default: break;
900 case XA_WM_TRANSIENT_FOR:
901 XGetTransientForHint(dpy, c->win, &trans);
902 if(!c->isfloat && (c->isfloat = (trans != 0)))
903 arrange();
904 break;
905 case XA_WM_NORMAL_HINTS:
906 updatesizehints(c);
907 break;
908 }
909 if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
910 updatetitle(c);
911 if(c == sel)
912 drawstatus();
913 }
914 }
915 }
917 static void
918 unmapnotify(XEvent *e) {
919 Client *c;
920 XUnmapEvent *ev = &e->xunmap;
922 if((c = getclient(ev->window)))
923 unmanage(c);
924 }
928 void (*handler[LASTEvent]) (XEvent *) = {
929 [ButtonPress] = buttonpress,
930 [ConfigureRequest] = configurerequest,
931 [DestroyNotify] = destroynotify,
932 [EnterNotify] = enternotify,
933 [LeaveNotify] = leavenotify,
934 [Expose] = expose,
935 [KeyPress] = keypress,
936 [MappingNotify] = mappingnotify,
937 [MapRequest] = maprequest,
938 [PropertyNotify] = propertynotify,
939 [UnmapNotify] = unmapnotify
940 };
942 void
943 grabkeys(void) {
944 static unsigned int len = sizeof key / sizeof key[0];
945 unsigned int i;
946 KeyCode code;
948 XUngrabKey(dpy, AnyKey, AnyModifier, root);
949 for(i = 0; i < len; i++) {
950 code = XKeysymToKeycode(dpy, key[i].keysym);
951 XGrabKey(dpy, code, key[i].mod, root, True,
952 GrabModeAsync, GrabModeAsync);
953 XGrabKey(dpy, code, key[i].mod | LockMask, root, True,
954 GrabModeAsync, GrabModeAsync);
955 XGrabKey(dpy, code, key[i].mod | numlockmask, root, True,
956 GrabModeAsync, GrabModeAsync);
957 XGrabKey(dpy, code, key[i].mod | numlockmask | LockMask, root, True,
958 GrabModeAsync, GrabModeAsync);
959 }
960 }
962 void
963 procevent(void) {
964 XEvent ev;
966 while(XPending(dpy)) {
967 XNextEvent(dpy, &ev);
968 if(handler[ev.type])
969 (handler[ev.type])(&ev); /* call handler */
970 }
971 }
987 /* from draw.c */
988 /* static */
990 static unsigned int
991 textnw(const char *text, unsigned int len) {
992 XRectangle r;
994 if(dc.font.set) {
995 XmbTextExtents(dc.font.set, text, len, NULL, &r);
996 return r.width;
997 }
998 return XTextWidth(dc.font.xfont, text, len);
999 }
1001 static void
1002 drawtext(const char *text, unsigned long col[ColLast]) {
1003 int x, y, w, h;
1004 static char buf[256];
1005 unsigned int len, olen;
1006 XGCValues gcv;
1007 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
1009 XSetForeground(dpy, dc.gc, col[ColBG]);
1010 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
1011 if(!text)
1012 return;
1013 w = 0;
1014 olen = len = strlen(text);
1015 if(len >= sizeof buf)
1016 len = sizeof buf - 1;
1017 memcpy(buf, text, len);
1018 buf[len] = 0;
1019 h = dc.font.ascent + dc.font.descent;
1020 y = dc.y + (dc.h / 2) - (h / 2) + dc.font.ascent;
1021 x = dc.x + (h / 2);
1022 /* shorten text if necessary */
1023 while(len && (w = textnw(buf, len)) > dc.w - h)
1024 buf[--len] = 0;
1025 if(len < olen) {
1026 if(len > 1)
1027 buf[len - 1] = '.';
1028 if(len > 2)
1029 buf[len - 2] = '.';
1030 if(len > 3)
1031 buf[len - 3] = '.';
1033 if(w > dc.w)
1034 return; /* too long */
1035 gcv.foreground = col[ColFG];
1036 if(dc.font.set) {
1037 XChangeGC(dpy, dc.gc, GCForeground, &gcv);
1038 XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
1039 } else {
1040 gcv.font = dc.font.xfont->fid;
1041 XChangeGC(dpy, dc.gc, GCForeground | GCFont, &gcv);
1042 XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
1048 void
1049 drawstatus(void) {
1050 int x;
1052 dc.x = dc.y = 0;
1053 dc.w = textw(NAMESEL);
1054 drawtext(NAMESEL, ( selgroup ? dc.sel : dc.norm ));
1055 dc.x += dc.w + 1;
1056 dc.w = textw(NAMENSEL);
1057 drawtext(NAMENSEL, ( selgroup ? dc.norm : dc.sel ));
1058 dc.x += dc.w + 1;
1059 dc.w = bmw;
1060 drawtext("", dc.norm);
1061 x = dc.x + dc.w;
1062 dc.w = textw(stext);
1063 dc.x = sw - dc.w;
1064 if(dc.x < x) {
1065 dc.x = x;
1066 dc.w = sw - x;
1068 drawtext(stext, dc.norm);
1069 if((dc.w = dc.x - x) > bh) {
1070 dc.x = x;
1071 drawtext(sel ? sel->name : NULL, dc.norm);
1073 XCopyArea(dpy, dc.drawable, barwin, dc.gc, 0, 0, sw, bh, 0, 0);
1074 XSync(dpy, False);
1077 unsigned long
1078 getcolor(const char *colstr) {
1079 Colormap cmap = DefaultColormap(dpy, screen);
1080 XColor color;
1082 if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
1083 eprint("error, cannot allocate color '%s'\n", colstr);
1084 return color.pixel;
1087 void
1088 setfont(const char *fontstr) {
1089 char *def, **missing;
1090 int i, n;
1092 missing = NULL;
1093 if(dc.font.set)
1094 XFreeFontSet(dpy, dc.font.set);
1095 dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
1096 if(missing) {
1097 while(n--)
1098 fprintf(stderr, "missing fontset: %s\n", missing[n]);
1099 XFreeStringList(missing);
1101 if(dc.font.set) {
1102 XFontSetExtents *font_extents;
1103 XFontStruct **xfonts;
1104 char **font_names;
1105 dc.font.ascent = dc.font.descent = 0;
1106 font_extents = XExtentsOfFontSet(dc.font.set);
1107 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
1108 for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
1109 if(dc.font.ascent < (*xfonts)->ascent)
1110 dc.font.ascent = (*xfonts)->ascent;
1111 if(dc.font.descent < (*xfonts)->descent)
1112 dc.font.descent = (*xfonts)->descent;
1113 xfonts++;
1115 } else {
1116 if(dc.font.xfont)
1117 XFreeFont(dpy, dc.font.xfont);
1118 dc.font.xfont = NULL;
1119 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr)))
1120 eprint("error, cannot load font: '%s'\n", fontstr);
1121 dc.font.ascent = dc.font.xfont->ascent;
1122 dc.font.descent = dc.font.xfont->descent;
1124 dc.font.height = dc.font.ascent + dc.font.descent;
1127 unsigned int
1128 textw(const char *text) {
1129 return textnw(text, strlen(text)) + dc.font.height;
1142 /* from client.c */
1143 /* static */
1145 static void
1146 detachstack(Client *c) {
1147 Client **tc;
1148 for(tc=&stack; *tc && *tc != c; tc=&(*tc)->snext);
1149 *tc = c->snext;
1152 static void
1153 grabbuttons(Client *c, Bool focused) {
1154 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1156 if(focused) {
1157 XGrabButton(dpy, Button1, MODKEY, c->win, False, BUTTONMASK,
1158 GrabModeAsync, GrabModeSync, None, None);
1159 XGrabButton(dpy, Button1, MODKEY | LockMask, c->win, False, BUTTONMASK,
1160 GrabModeAsync, GrabModeSync, None, None);
1161 XGrabButton(dpy, Button1, MODKEY | numlockmask, c->win, False, BUTTONMASK,
1162 GrabModeAsync, GrabModeSync, None, None);
1163 XGrabButton(dpy, Button1, MODKEY | numlockmask | LockMask, c->win, False, BUTTONMASK,
1164 GrabModeAsync, GrabModeSync, None, None);
1166 XGrabButton(dpy, Button2, MODKEY, c->win, False, BUTTONMASK,
1167 GrabModeAsync, GrabModeSync, None, None);
1168 XGrabButton(dpy, Button2, MODKEY | LockMask, c->win, False, BUTTONMASK,
1169 GrabModeAsync, GrabModeSync, None, None);
1170 XGrabButton(dpy, Button2, MODKEY | numlockmask, c->win, False, BUTTONMASK,
1171 GrabModeAsync, GrabModeSync, None, None);
1172 XGrabButton(dpy, Button2, MODKEY | numlockmask | LockMask, c->win, False, BUTTONMASK,
1173 GrabModeAsync, GrabModeSync, None, None);
1175 XGrabButton(dpy, Button3, MODKEY, c->win, False, BUTTONMASK,
1176 GrabModeAsync, GrabModeSync, None, None);
1177 XGrabButton(dpy, Button3, MODKEY | LockMask, c->win, False, BUTTONMASK,
1178 GrabModeAsync, GrabModeSync, None, None);
1179 XGrabButton(dpy, Button3, MODKEY | numlockmask, c->win, False, BUTTONMASK,
1180 GrabModeAsync, GrabModeSync, None, None);
1181 XGrabButton(dpy, Button3, MODKEY | numlockmask | LockMask, c->win, False, BUTTONMASK,
1182 GrabModeAsync, GrabModeSync, None, None);
1183 } else {
1184 XGrabButton(dpy, AnyButton, AnyModifier, c->win, False, BUTTONMASK,
1185 GrabModeAsync, GrabModeSync, None, None);
1189 static void
1190 setclientstate(Client *c, long state) {
1191 long data[] = {state, None};
1192 XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1193 PropModeReplace, (unsigned char *)data, 2);
1196 static int
1197 xerrordummy(Display *dsply, XErrorEvent *ee) {
1198 return 0;
1203 void
1204 configure(Client *c) {
1205 XEvent synev;
1207 synev.type = ConfigureNotify;
1208 synev.xconfigure.display = dpy;
1209 synev.xconfigure.event = c->win;
1210 synev.xconfigure.window = c->win;
1211 synev.xconfigure.x = c->x;
1212 synev.xconfigure.y = c->y;
1213 synev.xconfigure.width = c->w;
1214 synev.xconfigure.height = c->h;
1215 synev.xconfigure.border_width = c->border;
1216 synev.xconfigure.above = None;
1217 XSendEvent(dpy, c->win, True, NoEventMask, &synev);
1220 void
1221 focus(Client *c) {
1222 if(c && !isvisible(c))
1223 return;
1224 if(sel && sel != c) {
1225 grabbuttons(sel, False);
1226 XSetWindowBorder(dpy, sel->win, dc.norm[ColBorder]);
1228 if(c) {
1229 detachstack(c);
1230 c->snext = stack;
1231 stack = c;
1232 grabbuttons(c, True);
1234 sel = c;
1235 drawstatus();
1236 if(!selscreen)
1237 return;
1238 if(c) {
1239 XSetWindowBorder(dpy, c->win, dc.sel[ColBorder]);
1240 XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
1241 } else {
1242 XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
1246 Client *
1247 getclient(Window w) {
1248 Client *c;
1250 for(c = clients; c; c = c->next) {
1251 if(c->win == w) {
1252 return c;
1255 return NULL;
1258 Bool
1259 isprotodel(Client *c) {
1260 int i, n;
1261 Atom *protocols;
1262 Bool ret = False;
1264 if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
1265 for(i = 0; !ret && i < n; i++)
1266 if(protocols[i] == wmatom[WMDelete])
1267 ret = True;
1268 XFree(protocols);
1270 return ret;
1273 void
1274 killclient() {
1275 if(!sel)
1276 return;
1277 if(isprotodel(sel))
1278 sendevent(sel->win, wmatom[WMProtocols], wmatom[WMDelete]);
1279 else
1280 XKillClient(dpy, sel->win);
1283 void
1284 manage(Window w, XWindowAttributes *wa) {
1285 Client *c;
1286 Window trans;
1288 c = emallocz(sizeof(Client));
1289 c->group = True;
1290 c->win = w;
1291 c->x = wa->x;
1292 c->y = wa->y;
1293 c->w = wa->width;
1294 c->h = wa->height;
1295 if(c->w == sw && c->h == sh) {
1296 c->border = 0;
1297 c->x = sx;
1298 c->y = sy;
1299 } else {
1300 c->border = BORDERPX;
1301 if(c->x + c->w + 2 * c->border > wax + waw)
1302 c->x = wax + waw - c->w - 2 * c->border;
1303 if(c->y + c->h + 2 * c->border > way + wah)
1304 c->y = way + wah - c->h - 2 * c->border;
1305 if(c->x < wax)
1306 c->x = wax;
1307 if(c->y < way)
1308 c->y = way;
1310 updatesizehints(c);
1311 XSelectInput(dpy, c->win,
1312 StructureNotifyMask | PropertyChangeMask | EnterWindowMask);
1313 XGetTransientForHint(dpy, c->win, &trans);
1314 grabbuttons(c, False);
1315 XSetWindowBorder(dpy, c->win, dc.norm[ColBorder]);
1316 updatetitle(c);
1317 setgroup(c, getclient(trans));
1318 if(!c->isfloat)
1319 c->isfloat = trans || c->isfixed;
1320 if(clients)
1321 clients->prev = c;
1322 c->next = clients;
1323 c->snext = stack;
1324 stack = clients = c;
1325 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
1326 XMapWindow(dpy, c->win);
1327 setclientstate(c, NormalState);
1328 if(isvisible(c))
1329 focus(c);
1330 arrange();
1333 void
1334 resize(Client *c, Bool sizehints) {
1335 float actual, dx, dy, max, min;
1336 XWindowChanges wc;
1338 if(c->w <= 0 || c->h <= 0)
1339 return;
1340 if(sizehints) {
1341 if(c->minw && c->w < c->minw)
1342 c->w = c->minw;
1343 if(c->minh && c->h < c->minh)
1344 c->h = c->minh;
1345 if(c->maxw && c->w > c->maxw)
1346 c->w = c->maxw;
1347 if(c->maxh && c->h > c->maxh)
1348 c->h = c->maxh;
1349 /* inspired by algorithm from fluxbox */
1350 if(c->minay > 0 && c->maxay && (c->h - c->baseh) > 0) {
1351 dx = (float)(c->w - c->basew);
1352 dy = (float)(c->h - c->baseh);
1353 min = (float)(c->minax) / (float)(c->minay);
1354 max = (float)(c->maxax) / (float)(c->maxay);
1355 actual = dx / dy;
1356 if(max > 0 && min > 0 && actual > 0) {
1357 if(actual < min) {
1358 dy = (dx * min + dy) / (min * min + 1);
1359 dx = dy * min;
1360 c->w = (int)dx + c->basew;
1361 c->h = (int)dy + c->baseh;
1363 else if(actual > max) {
1364 dy = (dx * min + dy) / (max * max + 1);
1365 dx = dy * min;
1366 c->w = (int)dx + c->basew;
1367 c->h = (int)dy + c->baseh;
1371 if(c->incw)
1372 c->w -= (c->w - c->basew) % c->incw;
1373 if(c->inch)
1374 c->h -= (c->h - c->baseh) % c->inch;
1376 if(c->w == sw && c->h == sh)
1377 c->border = 0;
1378 else
1379 c->border = BORDERPX;
1380 /* offscreen appearance fixes */
1381 if(c->x > sw)
1382 c->x = sw - c->w - 2 * c->border;
1383 if(c->y > sh)
1384 c->y = sh - c->h - 2 * c->border;
1385 if(c->x + c->w + 2 * c->border < sx)
1386 c->x = sx;
1387 if(c->y + c->h + 2 * c->border < sy)
1388 c->y = sy;
1389 wc.x = c->x;
1390 wc.y = c->y;
1391 wc.width = c->w;
1392 wc.height = c->h;
1393 wc.border_width = c->border;
1394 XConfigureWindow(dpy, c->win, CWX | CWY | CWWidth | CWHeight | CWBorderWidth, &wc);
1395 configure(c);
1396 XSync(dpy, False);
1399 void
1400 updatesizehints(Client *c) {
1401 long msize;
1402 XSizeHints size;
1404 if(!XGetWMNormalHints(dpy, c->win, &size, &msize) || !size.flags)
1405 size.flags = PSize;
1406 c->flags = size.flags;
1407 if(c->flags & PBaseSize) {
1408 c->basew = size.base_width;
1409 c->baseh = size.base_height;
1410 } else {
1411 c->basew = c->baseh = 0;
1413 if(c->flags & PResizeInc) {
1414 c->incw = size.width_inc;
1415 c->inch = size.height_inc;
1416 } else {
1417 c->incw = c->inch = 0;
1419 if(c->flags & PMaxSize) {
1420 c->maxw = size.max_width;
1421 c->maxh = size.max_height;
1422 } else {
1423 c->maxw = c->maxh = 0;
1425 if(c->flags & PMinSize) {
1426 c->minw = size.min_width;
1427 c->minh = size.min_height;
1428 } else {
1429 c->minw = c->minh = 0;
1431 if(c->flags & PAspect) {
1432 c->minax = size.min_aspect.x;
1433 c->minay = size.min_aspect.y;
1434 c->maxax = size.max_aspect.x;
1435 c->maxay = size.max_aspect.y;
1436 } else {
1437 c->minax = c->minay = c->maxax = c->maxay = 0;
1439 c->isfixed = (c->maxw && c->minw && c->maxh && c->minh &&
1440 c->maxw == c->minw && c->maxh == c->minh);
1443 void
1444 updatetitle(Client *c) {
1445 char **list = NULL;
1446 int n;
1447 XTextProperty name;
1449 name.nitems = 0;
1450 c->name[0] = 0;
1451 XGetTextProperty(dpy, c->win, &name, netatom[NetWMName]);
1452 if(!name.nitems)
1453 XGetWMName(dpy, c->win, &name);
1454 if(!name.nitems)
1455 return;
1456 if(name.encoding == XA_STRING)
1457 strncpy(c->name, (char *)name.value, sizeof c->name);
1458 else {
1459 if(XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success && n > 0 && *list) {
1460 strncpy(c->name, *list, sizeof c->name);
1461 XFreeStringList(list);
1464 XFree(name.value);
1467 void
1468 unmanage(Client *c) {
1469 Client *nc;
1471 /* The server grab construct avoids race conditions. */
1472 XGrabServer(dpy);
1473 XSetErrorHandler(xerrordummy);
1474 detach(c);
1475 detachstack(c);
1476 if(sel == c) {
1477 for(nc = stack; nc && !isvisible(nc); nc = nc->snext);
1478 focus(nc);
1480 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1481 setclientstate(c, WithdrawnState);
1482 free(c);
1483 XSync(dpy, False);
1484 XSetErrorHandler(xerror);
1485 XUngrabServer(dpy);
1486 arrange();
1507 /* static */
1510 static void
1511 cleanup(void) {
1512 close(STDIN_FILENO);
1513 while(stack) {
1514 resize(stack, True);
1515 unmanage(stack);
1517 if(dc.font.set)
1518 XFreeFontSet(dpy, dc.font.set);
1519 else
1520 XFreeFont(dpy, dc.font.xfont);
1521 XUngrabKey(dpy, AnyKey, AnyModifier, root);
1522 XFreePixmap(dpy, dc.drawable);
1523 XFreeGC(dpy, dc.gc);
1524 XDestroyWindow(dpy, barwin);
1525 XFreeCursor(dpy, cursor[CurNormal]);
1526 XFreeCursor(dpy, cursor[CurResize]);
1527 XFreeCursor(dpy, cursor[CurMove]);
1528 XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime);
1529 XSync(dpy, False);
1532 static void
1533 scan(void) {
1534 unsigned int i, num;
1535 Window *wins, d1, d2;
1536 XWindowAttributes wa;
1538 wins = NULL;
1539 if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1540 for(i = 0; i < num; i++) {
1541 if(!XGetWindowAttributes(dpy, wins[i], &wa))
1542 continue;
1543 if(wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1544 continue;
1545 if(wa.map_state == IsViewable)
1546 manage(wins[i], &wa);
1549 if(wins)
1550 XFree(wins);
1553 static void
1554 setup(void) {
1555 int i, j;
1556 unsigned int mask;
1557 Window w;
1558 XModifierKeymap *modmap;
1559 XSetWindowAttributes wa;
1561 /* init atoms */
1562 wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1563 wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1564 wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1565 netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1566 netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1567 XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1568 PropModeReplace, (unsigned char *) netatom, NetLast);
1569 /* init cursors */
1570 cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1571 cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1572 cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1573 /* init modifier map */
1574 numlockmask = 0;
1575 modmap = XGetModifierMapping(dpy);
1576 for (i = 0; i < 8; i++) {
1577 for (j = 0; j < modmap->max_keypermod; j++) {
1578 if(modmap->modifiermap[i * modmap->max_keypermod + j] == XKeysymToKeycode(dpy, XK_Num_Lock))
1579 numlockmask = (1 << i);
1582 XFreeModifiermap(modmap);
1583 /* select for events */
1584 wa.event_mask = SubstructureRedirectMask | SubstructureNotifyMask
1585 | EnterWindowMask | LeaveWindowMask;
1586 wa.cursor = cursor[CurNormal];
1587 XChangeWindowAttributes(dpy, root, CWEventMask | CWCursor, &wa);
1588 grabkeys();
1589 initrregs();
1590 selgroup = True;
1591 /* style */
1592 dc.norm[ColBorder] = getcolor(NORMBORDERCOLOR);
1593 dc.norm[ColBG] = getcolor(NORMBGCOLOR);
1594 dc.norm[ColFG] = getcolor(NORMFGCOLOR);
1595 dc.sel[ColBorder] = getcolor(SELBORDERCOLOR);
1596 dc.sel[ColBG] = getcolor(SELBGCOLOR);
1597 dc.sel[ColFG] = getcolor(SELFGCOLOR);
1598 setfont(FONT);
1599 /* geometry */
1600 sx = sy = 0;
1601 sw = DisplayWidth(dpy, screen);
1602 sh = DisplayHeight(dpy, screen);
1603 nmaster = NMASTER;
1604 bmw = 1;
1605 /* bar */
1606 dc.h = bh = dc.font.height + 2;
1607 wa.override_redirect = 1;
1608 wa.background_pixmap = ParentRelative;
1609 wa.event_mask = ButtonPressMask | ExposureMask;
1610 barwin = XCreateWindow(dpy, root, sx, sy, sw, bh, 0,
1611 DefaultDepth(dpy, screen), CopyFromParent, DefaultVisual(dpy, screen),
1612 CWOverrideRedirect | CWBackPixmap | CWEventMask, &wa);
1613 XDefineCursor(dpy, barwin, cursor[CurNormal]);
1614 XMapRaised(dpy, barwin);
1615 strcpy(stext, "dwm-"VERSION);
1616 /* windowarea */
1617 wax = sx;
1618 way = sy + bh;
1619 wah = sh - bh;
1620 waw = sw;
1621 /* pixmap for everything */
1622 dc.drawable = XCreatePixmap(dpy, root, sw, bh, DefaultDepth(dpy, screen));
1623 dc.gc = XCreateGC(dpy, root, 0, 0);
1624 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
1625 /* multihead support */
1626 selscreen = XQueryPointer(dpy, root, &w, &w, &i, &i, &i, &i, &mask);
1629 /*
1630 * Startup Error handler to check if another window manager
1631 * is already running.
1632 */
1633 static int
1634 xerrorstart(Display *dsply, XErrorEvent *ee) {
1635 otherwm = True;
1636 return -1;
1641 void
1642 sendevent(Window w, Atom a, long value) {
1643 XEvent e;
1645 e.type = ClientMessage;
1646 e.xclient.window = w;
1647 e.xclient.message_type = a;
1648 e.xclient.format = 32;
1649 e.xclient.data.l[0] = value;
1650 e.xclient.data.l[1] = CurrentTime;
1651 XSendEvent(dpy, w, False, NoEventMask, &e);
1652 XSync(dpy, False);
1655 void
1656 quit() {
1657 readin = running = False;
1660 /* There's no way to check accesses to destroyed windows, thus those cases are
1661 * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
1662 * default error handler, which may call exit.
1663 */
1664 int
1665 xerror(Display *dpy, XErrorEvent *ee) {
1666 if(ee->error_code == BadWindow
1667 || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1668 || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1669 || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1670 || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1671 || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1672 || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1673 || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1674 return 0;
1675 fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1676 ee->request_code, ee->error_code);
1677 return xerrorxlib(dpy, ee); /* may call exit */
1680 int
1681 main(int argc, char *argv[]) {
1682 char *p;
1683 int r, xfd;
1684 fd_set rd;
1686 if(argc == 2 && !strncmp("-v", argv[1], 3)) {
1687 fputs("dwm-"VERSION", (C)opyright MMVI-MMVII Anselm R. Garbe\n", stdout);
1688 exit(EXIT_SUCCESS);
1689 } else if(argc != 1) {
1690 eprint("usage: dwm [-v]\n");
1692 setlocale(LC_CTYPE, "");
1693 dpy = XOpenDisplay(0);
1694 if(!dpy) {
1695 eprint("dwm: cannot open display\n");
1697 xfd = ConnectionNumber(dpy);
1698 screen = DefaultScreen(dpy);
1699 root = RootWindow(dpy, screen);
1700 otherwm = False;
1701 XSetErrorHandler(xerrorstart);
1702 /* this causes an error if some other window manager is running */
1703 XSelectInput(dpy, root, SubstructureRedirectMask);
1704 XSync(dpy, False);
1705 if(otherwm) {
1706 eprint("dwm: another window manager is already running\n");
1709 XSync(dpy, False);
1710 XSetErrorHandler(NULL);
1711 xerrorxlib = XSetErrorHandler(xerror);
1712 XSync(dpy, False);
1713 setup();
1714 drawstatus();
1715 scan();
1717 /* main event loop, also reads status text from stdin */
1718 XSync(dpy, False);
1719 procevent();
1720 readin = True;
1721 while(running) {
1722 FD_ZERO(&rd);
1723 if(readin)
1724 FD_SET(STDIN_FILENO, &rd);
1725 FD_SET(xfd, &rd);
1726 if(select(xfd + 1, &rd, NULL, NULL, NULL) == -1) {
1727 if(errno == EINTR)
1728 continue;
1729 eprint("select failed\n");
1731 if(FD_ISSET(STDIN_FILENO, &rd)) {
1732 switch(r = read(STDIN_FILENO, stext, sizeof stext - 1)) {
1733 case -1:
1734 strncpy(stext, strerror(errno), sizeof stext - 1);
1735 stext[sizeof stext - 1] = '\0';
1736 readin = False;
1737 break;
1738 case 0:
1739 strncpy(stext, "EOF", 4);
1740 readin = False;
1741 break;
1742 default:
1743 for(stext[r] = '\0', p = stext + strlen(stext) - 1; p >= stext && *p == '\n'; *p-- = '\0');
1744 for(; p >= stext && *p != '\n'; --p);
1745 if(p > stext)
1746 strncpy(stext, p + 1, sizeof stext);
1748 drawstatus();
1750 if(FD_ISSET(xfd, &rd))
1751 procevent();
1753 cleanup();
1754 XCloseDisplay(dpy);
1755 return 0;