aewl
view aewl.c @ 764:15660880e23d
removed unnessasary color pair
author | meillo@marmaro.de |
---|---|
date | Fri, 05 Dec 2008 19:08:47 +0100 |
parents | 17428bca4a12 |
children | 3f7c68a720b5 |
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 { 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 && !matched; 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 }
607 if(ch.res_class)
608 XFree(ch.res_class);
609 if(ch.res_name)
610 XFree(ch.res_name);
611 }
612 if(!matched) {
613 c->group = selgroup;
614 }
615 }
617 void
618 togglegroup() {
619 if(!sel)
620 return;
621 sel->group = !sel->group;
622 toggleview();
623 }
641 /* from event.c */
642 /* static */
644 KEYS
648 static void
649 movemouse(Client *c) {
650 int x1, y1, ocx, ocy, di;
651 unsigned int dui;
652 Window dummy;
653 XEvent ev;
655 ocx = c->x;
656 ocy = c->y;
657 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
658 None, cursor[CurMove], CurrentTime) != GrabSuccess)
659 return;
660 c->ismax = False;
661 XQueryPointer(dpy, root, &dummy, &dummy, &x1, &y1, &di, &di, &dui);
662 for(;;) {
663 XMaskEvent(dpy, MOUSEMASK | ExposureMask | SubstructureRedirectMask, &ev);
664 switch (ev.type) {
665 case ButtonRelease:
666 resize(c, True);
667 XUngrabPointer(dpy, CurrentTime);
668 return;
669 case ConfigureRequest:
670 case Expose:
671 case MapRequest:
672 handler[ev.type](&ev);
673 break;
674 case MotionNotify:
675 XSync(dpy, False);
676 c->x = ocx + (ev.xmotion.x - x1);
677 c->y = ocy + (ev.xmotion.y - y1);
678 if(abs(wax + c->x) < SNAP)
679 c->x = wax;
680 else if(abs((wax + waw) - (c->x + c->w + 2 * c->border)) < SNAP)
681 c->x = wax + waw - c->w - 2 * c->border;
682 if(abs(way - c->y) < SNAP)
683 c->y = way;
684 else if(abs((way + wah) - (c->y + c->h + 2 * c->border)) < SNAP)
685 c->y = way + wah - c->h - 2 * c->border;
686 resize(c, False);
687 break;
688 }
689 }
690 }
692 static void
693 resizemouse(Client *c) {
694 int ocx, ocy;
695 int nw, nh;
696 XEvent ev;
698 ocx = c->x;
699 ocy = c->y;
700 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
701 None, cursor[CurResize], CurrentTime) != GrabSuccess)
702 return;
703 c->ismax = False;
704 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->border - 1, c->h + c->border - 1);
705 for(;;) {
706 XMaskEvent(dpy, MOUSEMASK | ExposureMask | SubstructureRedirectMask , &ev);
707 switch(ev.type) {
708 case ButtonRelease:
709 resize(c, True);
710 XUngrabPointer(dpy, CurrentTime);
711 return;
712 case ConfigureRequest:
713 case Expose:
714 case MapRequest:
715 handler[ev.type](&ev);
716 break;
717 case MotionNotify:
718 XSync(dpy, False);
719 nw = ev.xmotion.x - ocx - 2 * c->border + 1;
720 c->w = nw > 0 ? nw : 1;
721 nh = ev.xmotion.y - ocy - 2 * c->border + 1;
722 c->h = nh > 0 ? nh : 1;
723 resize(c, True);
724 break;
725 }
726 }
727 }
729 static void
730 buttonpress(XEvent *e) {
731 Client *c;
732 XButtonPressedEvent *ev = &e->xbutton;
734 if(barwin == ev->window) {
735 return;
736 }
737 if((c = getclient(ev->window))) {
738 focus(c);
739 if(CLEANMASK(ev->state) != MODKEY)
740 return;
741 if(ev->button == Button1 && c->isfloat) {
742 restack();
743 movemouse(c);
744 } else if(ev->button == Button3 && c->isfloat && !c->isfixed) {
745 restack();
746 resizemouse(c);
747 }
748 }
749 }
751 static void
752 configurerequest(XEvent *e) {
753 unsigned long newmask;
754 Client *c;
755 XConfigureRequestEvent *ev = &e->xconfigurerequest;
756 XWindowChanges wc;
758 if((c = getclient(ev->window))) {
759 c->ismax = False;
760 if(ev->value_mask & CWX)
761 c->x = ev->x;
762 if(ev->value_mask & CWY)
763 c->y = ev->y;
764 if(ev->value_mask & CWWidth)
765 c->w = ev->width;
766 if(ev->value_mask & CWHeight)
767 c->h = ev->height;
768 if(ev->value_mask & CWBorderWidth)
769 c->border = ev->border_width;
770 wc.x = c->x;
771 wc.y = c->y;
772 wc.width = c->w;
773 wc.height = c->h;
774 newmask = ev->value_mask & (~(CWSibling | CWStackMode | CWBorderWidth));
775 if(newmask)
776 XConfigureWindow(dpy, c->win, newmask, &wc);
777 else
778 configure(c);
779 XSync(dpy, False);
780 if(c->isfloat) {
781 resize(c, False);
782 if(!isvisible(c))
783 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
784 }
785 else
786 arrange();
787 } else {
788 wc.x = ev->x;
789 wc.y = ev->y;
790 wc.width = ev->width;
791 wc.height = ev->height;
792 wc.border_width = ev->border_width;
793 wc.sibling = ev->above;
794 wc.stack_mode = ev->detail;
795 XConfigureWindow(dpy, ev->window, ev->value_mask, &wc);
796 XSync(dpy, False);
797 }
798 }
800 static void
801 destroynotify(XEvent *e) {
802 Client *c;
803 XDestroyWindowEvent *ev = &e->xdestroywindow;
805 if((c = getclient(ev->window)))
806 unmanage(c);
807 }
809 static void
810 enternotify(XEvent *e) {
811 Client *c;
812 XCrossingEvent *ev = &e->xcrossing;
814 if(ev->mode != NotifyNormal || ev->detail == NotifyInferior)
815 return;
816 if((c = getclient(ev->window)) && isvisible(c))
817 focus(c);
818 else if(ev->window == root) {
819 selscreen = True;
820 for(c = stack; c && !isvisible(c); c = c->snext);
821 focus(c);
822 }
823 }
825 static void
826 expose(XEvent *e) {
827 XExposeEvent *ev = &e->xexpose;
829 if(ev->count == 0) {
830 if(barwin == ev->window)
831 drawstatus();
832 }
833 }
835 static void
836 keypress(XEvent *e) {
837 static unsigned int len = sizeof key / sizeof key[0];
838 unsigned int i;
839 KeySym keysym;
840 XKeyEvent *ev = &e->xkey;
842 keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
843 for(i = 0; i < len; i++) {
844 if(keysym == key[i].keysym && CLEANMASK(key[i].mod) == CLEANMASK(ev->state)) {
845 if(key[i].func)
846 key[i].func(key[i].cmd);
847 }
848 }
849 }
851 static void
852 leavenotify(XEvent *e) {
853 XCrossingEvent *ev = &e->xcrossing;
855 if((ev->window == root) && !ev->same_screen) {
856 selscreen = False;
857 focus(NULL);
858 }
859 }
861 static void
862 mappingnotify(XEvent *e) {
863 XMappingEvent *ev = &e->xmapping;
865 XRefreshKeyboardMapping(ev);
866 if(ev->request == MappingKeyboard)
867 grabkeys();
868 }
870 static void
871 maprequest(XEvent *e) {
872 static XWindowAttributes wa;
873 XMapRequestEvent *ev = &e->xmaprequest;
875 if(!XGetWindowAttributes(dpy, ev->window, &wa))
876 return;
877 if(wa.override_redirect) {
878 XSelectInput(dpy, ev->window,
879 (StructureNotifyMask | PropertyChangeMask));
880 return;
881 }
882 if(!getclient(ev->window))
883 manage(ev->window, &wa);
884 }
886 static void
887 propertynotify(XEvent *e) {
888 Client *c;
889 Window trans;
890 XPropertyEvent *ev = &e->xproperty;
892 if(ev->state == PropertyDelete)
893 return; /* ignore */
894 if((c = getclient(ev->window))) {
895 switch (ev->atom) {
896 default: break;
897 case XA_WM_TRANSIENT_FOR:
898 XGetTransientForHint(dpy, c->win, &trans);
899 if(!c->isfloat && (c->isfloat = (trans != 0)))
900 arrange();
901 break;
902 case XA_WM_NORMAL_HINTS:
903 updatesizehints(c);
904 break;
905 }
906 if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
907 updatetitle(c);
908 if(c == sel)
909 drawstatus();
910 }
911 }
912 }
914 static void
915 unmapnotify(XEvent *e) {
916 Client *c;
917 XUnmapEvent *ev = &e->xunmap;
919 if((c = getclient(ev->window)))
920 unmanage(c);
921 }
925 void (*handler[LASTEvent]) (XEvent *) = {
926 [ButtonPress] = buttonpress,
927 [ConfigureRequest] = configurerequest,
928 [DestroyNotify] = destroynotify,
929 [EnterNotify] = enternotify,
930 [LeaveNotify] = leavenotify,
931 [Expose] = expose,
932 [KeyPress] = keypress,
933 [MappingNotify] = mappingnotify,
934 [MapRequest] = maprequest,
935 [PropertyNotify] = propertynotify,
936 [UnmapNotify] = unmapnotify
937 };
939 void
940 grabkeys(void) {
941 static unsigned int len = sizeof key / sizeof key[0];
942 unsigned int i;
943 KeyCode code;
945 XUngrabKey(dpy, AnyKey, AnyModifier, root);
946 for(i = 0; i < len; i++) {
947 code = XKeysymToKeycode(dpy, key[i].keysym);
948 XGrabKey(dpy, code, key[i].mod, root, True,
949 GrabModeAsync, GrabModeAsync);
950 XGrabKey(dpy, code, key[i].mod | LockMask, root, True,
951 GrabModeAsync, GrabModeAsync);
952 XGrabKey(dpy, code, key[i].mod | numlockmask, root, True,
953 GrabModeAsync, GrabModeAsync);
954 XGrabKey(dpy, code, key[i].mod | numlockmask | LockMask, root, True,
955 GrabModeAsync, GrabModeAsync);
956 }
957 }
959 void
960 procevent(void) {
961 XEvent ev;
963 while(XPending(dpy)) {
964 XNextEvent(dpy, &ev);
965 if(handler[ev.type])
966 (handler[ev.type])(&ev); /* call handler */
967 }
968 }
984 /* from draw.c */
985 /* static */
987 static unsigned int
988 textnw(const char *text, unsigned int len) {
989 XRectangle r;
991 if(dc.font.set) {
992 XmbTextExtents(dc.font.set, text, len, NULL, &r);
993 return r.width;
994 }
995 return XTextWidth(dc.font.xfont, text, len);
996 }
998 static void
999 drawtext(const char *text, unsigned long col[ColLast]) {
1000 int x, y, w, h;
1001 static char buf[256];
1002 unsigned int len, olen;
1003 XGCValues gcv;
1004 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
1006 XSetForeground(dpy, dc.gc, col[ColBG]);
1007 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
1008 if(!text)
1009 return;
1010 w = 0;
1011 olen = len = strlen(text);
1012 if(len >= sizeof buf)
1013 len = sizeof buf - 1;
1014 memcpy(buf, text, len);
1015 buf[len] = 0;
1016 h = dc.font.ascent + dc.font.descent;
1017 y = dc.y + (dc.h / 2) - (h / 2) + dc.font.ascent;
1018 x = dc.x + (h / 2);
1019 /* shorten text if necessary */
1020 while(len && (w = textnw(buf, len)) > dc.w - h)
1021 buf[--len] = 0;
1022 if(len < olen) {
1023 if(len > 1)
1024 buf[len - 1] = '.';
1025 if(len > 2)
1026 buf[len - 2] = '.';
1027 if(len > 3)
1028 buf[len - 3] = '.';
1029 }
1030 if(w > dc.w)
1031 return; /* too long */
1032 gcv.foreground = col[ColFG];
1033 if(dc.font.set) {
1034 XChangeGC(dpy, dc.gc, GCForeground, &gcv);
1035 XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
1036 } else {
1037 gcv.font = dc.font.xfont->fid;
1038 XChangeGC(dpy, dc.gc, GCForeground | GCFont, &gcv);
1039 XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
1040 }
1041 }
1045 void
1046 drawstatus(void) {
1047 int x;
1049 dc.x = dc.y = 0;
1050 dc.w = textw(NAMESEL);
1051 drawtext(NAMESEL, ( selgroup ? dc.sel : dc.norm ));
1052 dc.x += dc.w + 1;
1053 dc.w = textw(NAMENSEL);
1054 drawtext(NAMENSEL, ( selgroup ? dc.norm : dc.sel ));
1055 dc.x += dc.w + 1;
1056 dc.w = bmw;
1057 drawtext("", dc.norm);
1058 x = dc.x + dc.w;
1059 dc.w = textw(stext);
1060 dc.x = sw - dc.w;
1061 if(dc.x < x) {
1062 dc.x = x;
1063 dc.w = sw - x;
1064 }
1065 drawtext(stext, dc.norm);
1066 if((dc.w = dc.x - x) > bh) {
1067 dc.x = x;
1068 drawtext(sel ? sel->name : NULL, dc.norm);
1069 }
1070 XCopyArea(dpy, dc.drawable, barwin, dc.gc, 0, 0, sw, bh, 0, 0);
1071 XSync(dpy, False);
1072 }
1074 unsigned long
1075 getcolor(const char *colstr) {
1076 Colormap cmap = DefaultColormap(dpy, screen);
1077 XColor color;
1079 if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
1080 eprint("error, cannot allocate color '%s'\n", colstr);
1081 return color.pixel;
1082 }
1084 void
1085 setfont(const char *fontstr) {
1086 char *def, **missing;
1087 int i, n;
1089 missing = NULL;
1090 if(dc.font.set)
1091 XFreeFontSet(dpy, dc.font.set);
1092 dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
1093 if(missing) {
1094 while(n--)
1095 fprintf(stderr, "missing fontset: %s\n", missing[n]);
1096 XFreeStringList(missing);
1097 }
1098 if(dc.font.set) {
1099 XFontSetExtents *font_extents;
1100 XFontStruct **xfonts;
1101 char **font_names;
1102 dc.font.ascent = dc.font.descent = 0;
1103 font_extents = XExtentsOfFontSet(dc.font.set);
1104 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
1105 for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
1106 if(dc.font.ascent < (*xfonts)->ascent)
1107 dc.font.ascent = (*xfonts)->ascent;
1108 if(dc.font.descent < (*xfonts)->descent)
1109 dc.font.descent = (*xfonts)->descent;
1110 xfonts++;
1111 }
1112 } else {
1113 if(dc.font.xfont)
1114 XFreeFont(dpy, dc.font.xfont);
1115 dc.font.xfont = NULL;
1116 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr)))
1117 eprint("error, cannot load font: '%s'\n", fontstr);
1118 dc.font.ascent = dc.font.xfont->ascent;
1119 dc.font.descent = dc.font.xfont->descent;
1120 }
1121 dc.font.height = dc.font.ascent + dc.font.descent;
1122 }
1124 unsigned int
1125 textw(const char *text) {
1126 return textnw(text, strlen(text)) + dc.font.height;
1127 }
1139 /* from client.c */
1140 /* static */
1142 static void
1143 detachstack(Client *c) {
1144 Client **tc;
1145 for(tc=&stack; *tc && *tc != c; tc=&(*tc)->snext);
1146 *tc = c->snext;
1147 }
1149 static void
1150 grabbuttons(Client *c, Bool focused) {
1151 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1153 if(focused) {
1154 XGrabButton(dpy, Button1, MODKEY, c->win, False, BUTTONMASK,
1155 GrabModeAsync, GrabModeSync, None, None);
1156 XGrabButton(dpy, Button1, MODKEY | LockMask, c->win, False, BUTTONMASK,
1157 GrabModeAsync, GrabModeSync, None, None);
1158 XGrabButton(dpy, Button1, MODKEY | numlockmask, c->win, False, BUTTONMASK,
1159 GrabModeAsync, GrabModeSync, None, None);
1160 XGrabButton(dpy, Button1, MODKEY | numlockmask | LockMask, c->win, False, BUTTONMASK,
1161 GrabModeAsync, GrabModeSync, None, None);
1163 XGrabButton(dpy, Button2, MODKEY, c->win, False, BUTTONMASK,
1164 GrabModeAsync, GrabModeSync, None, None);
1165 XGrabButton(dpy, Button2, MODKEY | LockMask, c->win, False, BUTTONMASK,
1166 GrabModeAsync, GrabModeSync, None, None);
1167 XGrabButton(dpy, Button2, MODKEY | numlockmask, c->win, False, BUTTONMASK,
1168 GrabModeAsync, GrabModeSync, None, None);
1169 XGrabButton(dpy, Button2, MODKEY | numlockmask | LockMask, c->win, False, BUTTONMASK,
1170 GrabModeAsync, GrabModeSync, None, None);
1172 XGrabButton(dpy, Button3, MODKEY, c->win, False, BUTTONMASK,
1173 GrabModeAsync, GrabModeSync, None, None);
1174 XGrabButton(dpy, Button3, MODKEY | LockMask, c->win, False, BUTTONMASK,
1175 GrabModeAsync, GrabModeSync, None, None);
1176 XGrabButton(dpy, Button3, MODKEY | numlockmask, c->win, False, BUTTONMASK,
1177 GrabModeAsync, GrabModeSync, None, None);
1178 XGrabButton(dpy, Button3, MODKEY | numlockmask | LockMask, c->win, False, BUTTONMASK,
1179 GrabModeAsync, GrabModeSync, None, None);
1180 } else {
1181 XGrabButton(dpy, AnyButton, AnyModifier, c->win, False, BUTTONMASK,
1182 GrabModeAsync, GrabModeSync, None, None);
1183 }
1184 }
1186 static void
1187 setclientstate(Client *c, long state) {
1188 long data[] = {state, None};
1189 XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1190 PropModeReplace, (unsigned char *)data, 2);
1191 }
1193 static int
1194 xerrordummy(Display *dsply, XErrorEvent *ee) {
1195 return 0;
1196 }
1200 void
1201 configure(Client *c) {
1202 XEvent synev;
1204 synev.type = ConfigureNotify;
1205 synev.xconfigure.display = dpy;
1206 synev.xconfigure.event = c->win;
1207 synev.xconfigure.window = c->win;
1208 synev.xconfigure.x = c->x;
1209 synev.xconfigure.y = c->y;
1210 synev.xconfigure.width = c->w;
1211 synev.xconfigure.height = c->h;
1212 synev.xconfigure.border_width = c->border;
1213 synev.xconfigure.above = None;
1214 XSendEvent(dpy, c->win, True, NoEventMask, &synev);
1215 }
1217 void
1218 focus(Client *c) {
1219 if(c && !isvisible(c))
1220 return;
1221 if(sel && sel != c) {
1222 grabbuttons(sel, False);
1223 XSetWindowBorder(dpy, sel->win, dc.norm[ColBG]);
1224 }
1225 if(c) {
1226 detachstack(c);
1227 c->snext = stack;
1228 stack = c;
1229 grabbuttons(c, True);
1230 }
1231 sel = c;
1232 drawstatus();
1233 if(!selscreen)
1234 return;
1235 if(c) {
1236 XSetWindowBorder(dpy, c->win, dc.sel[ColBG]);
1237 XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
1238 } else {
1239 XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
1240 }
1241 }
1243 Client *
1244 getclient(Window w) {
1245 Client *c;
1247 for(c = clients; c; c = c->next) {
1248 if(c->win == w) {
1249 return c;
1250 }
1251 }
1252 return NULL;
1253 }
1255 Bool
1256 isprotodel(Client *c) {
1257 int i, n;
1258 Atom *protocols;
1259 Bool ret = False;
1261 if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
1262 for(i = 0; !ret && i < n; i++)
1263 if(protocols[i] == wmatom[WMDelete])
1264 ret = True;
1265 XFree(protocols);
1266 }
1267 return ret;
1268 }
1270 void
1271 killclient() {
1272 if(!sel)
1273 return;
1274 if(isprotodel(sel))
1275 sendevent(sel->win, wmatom[WMProtocols], wmatom[WMDelete]);
1276 else
1277 XKillClient(dpy, sel->win);
1278 }
1280 void
1281 manage(Window w, XWindowAttributes *wa) {
1282 Client *c;
1283 Window trans;
1285 c = emallocz(sizeof(Client));
1286 c->group = True;
1287 c->win = w;
1288 c->x = wa->x;
1289 c->y = wa->y;
1290 c->w = wa->width;
1291 c->h = wa->height;
1292 if(c->w == sw && c->h == sh) {
1293 c->border = 0;
1294 c->x = sx;
1295 c->y = sy;
1296 } else {
1297 c->border = BORDERPX;
1298 if(c->x + c->w + 2 * c->border > wax + waw)
1299 c->x = wax + waw - c->w - 2 * c->border;
1300 if(c->y + c->h + 2 * c->border > way + wah)
1301 c->y = way + wah - c->h - 2 * c->border;
1302 if(c->x < wax)
1303 c->x = wax;
1304 if(c->y < way)
1305 c->y = way;
1306 }
1307 updatesizehints(c);
1308 XSelectInput(dpy, c->win,
1309 StructureNotifyMask | PropertyChangeMask | EnterWindowMask);
1310 XGetTransientForHint(dpy, c->win, &trans);
1311 grabbuttons(c, False);
1312 XSetWindowBorder(dpy, c->win, dc.norm[ColBG]);
1313 updatetitle(c);
1314 setgroup(c, getclient(trans));
1315 if(!c->isfloat)
1316 c->isfloat = trans || c->isfixed;
1317 if(clients)
1318 clients->prev = c;
1319 c->next = clients;
1320 c->snext = stack;
1321 stack = clients = c;
1322 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
1323 XMapWindow(dpy, c->win);
1324 setclientstate(c, NormalState);
1325 if(isvisible(c))
1326 focus(c);
1327 arrange();
1328 }
1330 void
1331 resize(Client *c, Bool sizehints) {
1332 float actual, dx, dy, max, min;
1333 XWindowChanges wc;
1335 if(c->w <= 0 || c->h <= 0)
1336 return;
1337 if(sizehints) {
1338 if(c->minw && c->w < c->minw)
1339 c->w = c->minw;
1340 if(c->minh && c->h < c->minh)
1341 c->h = c->minh;
1342 if(c->maxw && c->w > c->maxw)
1343 c->w = c->maxw;
1344 if(c->maxh && c->h > c->maxh)
1345 c->h = c->maxh;
1346 /* inspired by algorithm from fluxbox */
1347 if(c->minay > 0 && c->maxay && (c->h - c->baseh) > 0) {
1348 dx = (float)(c->w - c->basew);
1349 dy = (float)(c->h - c->baseh);
1350 min = (float)(c->minax) / (float)(c->minay);
1351 max = (float)(c->maxax) / (float)(c->maxay);
1352 actual = dx / dy;
1353 if(max > 0 && min > 0 && actual > 0) {
1354 if(actual < min) {
1355 dy = (dx * min + dy) / (min * min + 1);
1356 dx = dy * min;
1357 c->w = (int)dx + c->basew;
1358 c->h = (int)dy + c->baseh;
1359 }
1360 else if(actual > max) {
1361 dy = (dx * min + dy) / (max * max + 1);
1362 dx = dy * min;
1363 c->w = (int)dx + c->basew;
1364 c->h = (int)dy + c->baseh;
1365 }
1366 }
1367 }
1368 if(c->incw)
1369 c->w -= (c->w - c->basew) % c->incw;
1370 if(c->inch)
1371 c->h -= (c->h - c->baseh) % c->inch;
1372 }
1373 if(c->w == sw && c->h == sh)
1374 c->border = 0;
1375 else
1376 c->border = BORDERPX;
1377 /* offscreen appearance fixes */
1378 if(c->x > sw)
1379 c->x = sw - c->w - 2 * c->border;
1380 if(c->y > sh)
1381 c->y = sh - c->h - 2 * c->border;
1382 if(c->x + c->w + 2 * c->border < sx)
1383 c->x = sx;
1384 if(c->y + c->h + 2 * c->border < sy)
1385 c->y = sy;
1386 wc.x = c->x;
1387 wc.y = c->y;
1388 wc.width = c->w;
1389 wc.height = c->h;
1390 wc.border_width = c->border;
1391 XConfigureWindow(dpy, c->win, CWX | CWY | CWWidth | CWHeight | CWBorderWidth, &wc);
1392 configure(c);
1393 XSync(dpy, False);
1394 }
1396 void
1397 updatesizehints(Client *c) {
1398 long msize;
1399 XSizeHints size;
1401 if(!XGetWMNormalHints(dpy, c->win, &size, &msize) || !size.flags)
1402 size.flags = PSize;
1403 c->flags = size.flags;
1404 if(c->flags & PBaseSize) {
1405 c->basew = size.base_width;
1406 c->baseh = size.base_height;
1407 } else {
1408 c->basew = c->baseh = 0;
1409 }
1410 if(c->flags & PResizeInc) {
1411 c->incw = size.width_inc;
1412 c->inch = size.height_inc;
1413 } else {
1414 c->incw = c->inch = 0;
1415 }
1416 if(c->flags & PMaxSize) {
1417 c->maxw = size.max_width;
1418 c->maxh = size.max_height;
1419 } else {
1420 c->maxw = c->maxh = 0;
1421 }
1422 if(c->flags & PMinSize) {
1423 c->minw = size.min_width;
1424 c->minh = size.min_height;
1425 } else {
1426 c->minw = c->minh = 0;
1427 }
1428 if(c->flags & PAspect) {
1429 c->minax = size.min_aspect.x;
1430 c->minay = size.min_aspect.y;
1431 c->maxax = size.max_aspect.x;
1432 c->maxay = size.max_aspect.y;
1433 } else {
1434 c->minax = c->minay = c->maxax = c->maxay = 0;
1435 }
1436 c->isfixed = (c->maxw && c->minw && c->maxh && c->minh &&
1437 c->maxw == c->minw && c->maxh == c->minh);
1438 }
1440 void
1441 updatetitle(Client *c) {
1442 char **list = NULL;
1443 int n;
1444 XTextProperty name;
1446 name.nitems = 0;
1447 c->name[0] = 0;
1448 XGetTextProperty(dpy, c->win, &name, netatom[NetWMName]);
1449 if(!name.nitems)
1450 XGetWMName(dpy, c->win, &name);
1451 if(!name.nitems)
1452 return;
1453 if(name.encoding == XA_STRING)
1454 strncpy(c->name, (char *)name.value, sizeof c->name);
1455 else {
1456 if(XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success && n > 0 && *list) {
1457 strncpy(c->name, *list, sizeof c->name);
1458 XFreeStringList(list);
1459 }
1460 }
1461 XFree(name.value);
1462 }
1464 void
1465 unmanage(Client *c) {
1466 Client *nc;
1468 /* The server grab construct avoids race conditions. */
1469 XGrabServer(dpy);
1470 XSetErrorHandler(xerrordummy);
1471 detach(c);
1472 detachstack(c);
1473 if(sel == c) {
1474 for(nc = stack; nc && !isvisible(nc); nc = nc->snext);
1475 focus(nc);
1476 }
1477 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1478 setclientstate(c, WithdrawnState);
1479 free(c);
1480 XSync(dpy, False);
1481 XSetErrorHandler(xerror);
1482 XUngrabServer(dpy);
1483 arrange();
1484 }
1504 /* static */
1507 static void
1508 cleanup(void) {
1509 close(STDIN_FILENO);
1510 while(stack) {
1511 resize(stack, True);
1512 unmanage(stack);
1513 }
1514 if(dc.font.set)
1515 XFreeFontSet(dpy, dc.font.set);
1516 else
1517 XFreeFont(dpy, dc.font.xfont);
1518 XUngrabKey(dpy, AnyKey, AnyModifier, root);
1519 XFreePixmap(dpy, dc.drawable);
1520 XFreeGC(dpy, dc.gc);
1521 XDestroyWindow(dpy, barwin);
1522 XFreeCursor(dpy, cursor[CurNormal]);
1523 XFreeCursor(dpy, cursor[CurResize]);
1524 XFreeCursor(dpy, cursor[CurMove]);
1525 XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime);
1526 XSync(dpy, False);
1527 }
1529 static void
1530 scan(void) {
1531 unsigned int i, num;
1532 Window *wins, d1, d2;
1533 XWindowAttributes wa;
1535 wins = NULL;
1536 if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1537 for(i = 0; i < num; i++) {
1538 if(!XGetWindowAttributes(dpy, wins[i], &wa))
1539 continue;
1540 if(wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1541 continue;
1542 if(wa.map_state == IsViewable)
1543 manage(wins[i], &wa);
1544 }
1545 }
1546 if(wins)
1547 XFree(wins);
1548 }
1550 static void
1551 setup(void) {
1552 int i, j;
1553 unsigned int mask;
1554 Window w;
1555 XModifierKeymap *modmap;
1556 XSetWindowAttributes wa;
1558 /* init atoms */
1559 wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1560 wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1561 wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1562 netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1563 netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1564 XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1565 PropModeReplace, (unsigned char *) netatom, NetLast);
1566 /* init cursors */
1567 cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1568 cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1569 cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1570 /* init modifier map */
1571 numlockmask = 0;
1572 modmap = XGetModifierMapping(dpy);
1573 for (i = 0; i < 8; i++) {
1574 for (j = 0; j < modmap->max_keypermod; j++) {
1575 if(modmap->modifiermap[i * modmap->max_keypermod + j] == XKeysymToKeycode(dpy, XK_Num_Lock))
1576 numlockmask = (1 << i);
1577 }
1578 }
1579 XFreeModifiermap(modmap);
1580 /* select for events */
1581 wa.event_mask = SubstructureRedirectMask | SubstructureNotifyMask
1582 | EnterWindowMask | LeaveWindowMask;
1583 wa.cursor = cursor[CurNormal];
1584 XChangeWindowAttributes(dpy, root, CWEventMask | CWCursor, &wa);
1585 grabkeys();
1586 initrregs();
1587 selgroup = True;
1588 /* style */
1589 dc.norm[ColBG] = getcolor(NORMBGCOLOR);
1590 dc.norm[ColFG] = getcolor(NORMFGCOLOR);
1591 dc.sel[ColBG] = getcolor(SELBGCOLOR);
1592 dc.sel[ColFG] = getcolor(SELFGCOLOR);
1593 setfont(FONT);
1594 /* geometry */
1595 sx = sy = 0;
1596 sw = DisplayWidth(dpy, screen);
1597 sh = DisplayHeight(dpy, screen);
1598 nmaster = NMASTER;
1599 bmw = 1;
1600 /* bar */
1601 dc.h = bh = dc.font.height + 2;
1602 wa.override_redirect = 1;
1603 wa.background_pixmap = ParentRelative;
1604 wa.event_mask = ButtonPressMask | ExposureMask;
1605 barwin = XCreateWindow(dpy, root, sx, sy, sw, bh, 0,
1606 DefaultDepth(dpy, screen), CopyFromParent, DefaultVisual(dpy, screen),
1607 CWOverrideRedirect | CWBackPixmap | CWEventMask, &wa);
1608 XDefineCursor(dpy, barwin, cursor[CurNormal]);
1609 XMapRaised(dpy, barwin);
1610 strcpy(stext, "dwm-"VERSION);
1611 /* windowarea */
1612 wax = sx;
1613 way = sy + bh;
1614 wah = sh - bh;
1615 waw = sw;
1616 /* pixmap for everything */
1617 dc.drawable = XCreatePixmap(dpy, root, sw, bh, DefaultDepth(dpy, screen));
1618 dc.gc = XCreateGC(dpy, root, 0, 0);
1619 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
1620 /* multihead support */
1621 selscreen = XQueryPointer(dpy, root, &w, &w, &i, &i, &i, &i, &mask);
1622 }
1624 /*
1625 * Startup Error handler to check if another window manager
1626 * is already running.
1627 */
1628 static int
1629 xerrorstart(Display *dsply, XErrorEvent *ee) {
1630 otherwm = True;
1631 return -1;
1632 }
1636 void
1637 sendevent(Window w, Atom a, long value) {
1638 XEvent e;
1640 e.type = ClientMessage;
1641 e.xclient.window = w;
1642 e.xclient.message_type = a;
1643 e.xclient.format = 32;
1644 e.xclient.data.l[0] = value;
1645 e.xclient.data.l[1] = CurrentTime;
1646 XSendEvent(dpy, w, False, NoEventMask, &e);
1647 XSync(dpy, False);
1648 }
1650 void
1651 quit() {
1652 readin = running = False;
1653 }
1655 /* There's no way to check accesses to destroyed windows, thus those cases are
1656 * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
1657 * default error handler, which may call exit.
1658 */
1659 int
1660 xerror(Display *dpy, XErrorEvent *ee) {
1661 if(ee->error_code == BadWindow
1662 || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1663 || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1664 || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1665 || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1666 || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1667 || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1668 || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1669 return 0;
1670 fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1671 ee->request_code, ee->error_code);
1672 return xerrorxlib(dpy, ee); /* may call exit */
1673 }
1675 int
1676 main(int argc, char *argv[]) {
1677 char *p;
1678 int r, xfd;
1679 fd_set rd;
1681 if(argc == 2 && !strncmp("-v", argv[1], 3)) {
1682 fputs("dwm-"VERSION", (C)opyright MMVI-MMVII Anselm R. Garbe\n", stdout);
1683 exit(EXIT_SUCCESS);
1684 } else if(argc != 1) {
1685 eprint("usage: dwm [-v]\n");
1686 }
1687 setlocale(LC_CTYPE, "");
1688 dpy = XOpenDisplay(0);
1689 if(!dpy) {
1690 eprint("dwm: cannot open display\n");
1691 }
1692 xfd = ConnectionNumber(dpy);
1693 screen = DefaultScreen(dpy);
1694 root = RootWindow(dpy, screen);
1695 otherwm = False;
1696 XSetErrorHandler(xerrorstart);
1697 /* this causes an error if some other window manager is running */
1698 XSelectInput(dpy, root, SubstructureRedirectMask);
1699 XSync(dpy, False);
1700 if(otherwm) {
1701 eprint("dwm: another window manager is already running\n");
1702 }
1704 XSync(dpy, False);
1705 XSetErrorHandler(NULL);
1706 xerrorxlib = XSetErrorHandler(xerror);
1707 XSync(dpy, False);
1708 setup();
1709 drawstatus();
1710 scan();
1712 /* main event loop, also reads status text from stdin */
1713 XSync(dpy, False);
1714 procevent();
1715 readin = True;
1716 while(running) {
1717 FD_ZERO(&rd);
1718 if(readin)
1719 FD_SET(STDIN_FILENO, &rd);
1720 FD_SET(xfd, &rd);
1721 if(select(xfd + 1, &rd, NULL, NULL, NULL) == -1) {
1722 if(errno == EINTR)
1723 continue;
1724 eprint("select failed\n");
1725 }
1726 if(FD_ISSET(STDIN_FILENO, &rd)) {
1727 switch(r = read(STDIN_FILENO, stext, sizeof stext - 1)) {
1728 case -1:
1729 strncpy(stext, strerror(errno), sizeof stext - 1);
1730 stext[sizeof stext - 1] = '\0';
1731 readin = False;
1732 break;
1733 case 0:
1734 strncpy(stext, "EOF", 4);
1735 readin = False;
1736 break;
1737 default:
1738 for(stext[r] = '\0', p = stext + strlen(stext) - 1; p >= stext && *p == '\n'; *p-- = '\0');
1739 for(; p >= stext && *p != '\n'; --p);
1740 if(p > stext)
1741 strncpy(stext, p + 1, sizeof stext);
1742 }
1743 drawstatus();
1744 }
1745 if(FD_ISSET(xfd, &rd))
1746 procevent();
1747 }
1748 cleanup();
1749 XCloseDisplay(dpy);
1750 return 0;
1751 }