aewl

view aewl.c @ 761:59ce221b9a37

removed global float (dofloat); number of tags is fixed (2)
author meillo@marmaro.de
date Fri, 05 Dec 2008 15:44:43 +0100
parents 014c4cb1ae4a
children 3f0b245732fc
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 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 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, seltag;
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 settags(Client *c, Client *trans); /* sets tags 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 tag */
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 toggletag(void); /* toggles c tag */
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 if(c->tag == seltag) {
392 return True;
393 }
394 return False;
395 }
397 void
398 restack(void) {
399 Client *c;
400 XEvent ev;
402 drawstatus();
403 if(!sel)
404 return;
405 if(sel->isfloat)
406 XRaiseWindow(dpy, sel->win);
408 /* begin code by mitch */
409 if(arrange == domax) {
410 for(c = nexttiled(clients); c; c = nexttiled(c->next)) {
411 arrangemax(c);
412 resize(c, False);
413 }
415 } else if (arrange == dotile) {
416 /* end code by mitch */
418 if(!sel->isfloat)
419 XLowerWindow(dpy, sel->win);
420 for(c = nexttiled(clients); c; c = nexttiled(c->next)) {
421 if(c == sel)
422 continue;
423 XLowerWindow(dpy, c->win);
424 }
425 }
426 XSync(dpy, False);
427 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
428 }
430 void
431 togglefloat() {
432 if (!sel)
433 return;
434 sel->isfloat = !sel->isfloat;
435 arrange();
436 }
438 void
439 togglemode() {
440 /* only toggle between tile and max - float is just available through togglefloat */
441 arrange = (arrange == dotile) ? domax : dotile;
442 if(sel)
443 arrange();
444 else
445 drawstatus();
446 }
448 void
449 toggleview() {
450 seltag = !seltag;
451 arrange();
452 }
454 void
455 zoom() {
456 unsigned int n;
457 Client *c;
459 if(!sel)
460 return;
461 if(sel->isfloat) {
462 togglemax(sel);
463 return;
464 }
465 for(n = 0, c = nexttiled(clients); c; c = nexttiled(c->next))
466 n++;
468 if((c = sel) == nexttiled(clients))
469 if(!(c = nexttiled(c->next)))
470 return;
471 detach(c);
472 if(clients)
473 clients->prev = c;
474 c->next = clients;
475 clients = c;
476 focus(c);
477 arrange();
478 }
495 /* from util.c */
498 void *
499 emallocz(unsigned int size) {
500 void *res = calloc(1, size);
502 if(!res)
503 eprint("fatal: could not malloc() %u bytes\n", size);
504 return res;
505 }
507 void
508 eprint(const char *errstr, ...) {
509 va_list ap;
511 va_start(ap, errstr);
512 vfprintf(stderr, errstr, ap);
513 va_end(ap);
514 exit(EXIT_FAILURE);
515 }
517 void
518 spawn(const char* cmd) {
519 static char *shell = NULL;
521 if(!shell && !(shell = getenv("SHELL")))
522 shell = "/bin/sh";
523 if(!cmd)
524 return;
525 /* The double-fork construct avoids zombie processes and keeps the code
526 * clean from stupid signal handlers. */
527 if(fork() == 0) {
528 if(fork() == 0) {
529 if(dpy)
530 close(ConnectionNumber(dpy));
531 setsid();
532 execl(shell, shell, "-c", cmd, (char *)NULL);
533 fprintf(stderr, "dwm: execl '%s -c %s'", shell, cmd);
534 perror(" failed");
535 }
536 exit(0);
537 }
538 wait(0);
539 }
553 /* from tag.c */
555 /* static */
557 Client *
558 getnext(Client *c) {
559 for(; c && !isvisible(c); c = c->next);
560 return c;
561 }
563 void
564 initrregs(void) {
565 unsigned int i;
566 regex_t *reg;
568 if(rreg)
569 return;
570 len = sizeof rule / sizeof rule[0];
571 rreg = emallocz(len * sizeof(RReg));
572 for(i = 0; i < len; i++) {
573 if(rule[i].clpattern) {
574 reg = emallocz(sizeof(regex_t));
575 if(regcomp(reg, rule[i].clpattern, REG_EXTENDED))
576 free(reg);
577 else
578 rreg[i].clregex = reg;
579 }
580 }
581 }
583 void
584 settags(Client *c, Client *trans) {
585 char prop[512];
586 unsigned int i;
587 regmatch_t tmp;
588 Bool matched = trans != NULL;
589 XClassHint ch = { 0 };
591 if(matched) {
592 c->tag = trans->tag;
593 } else {
594 XGetClassHint(dpy, c->win, &ch);
595 snprintf(prop, sizeof prop, "%s:%s:%s",
596 ch.res_class ? ch.res_class : "",
597 ch.res_name ? ch.res_name : "", c->name);
598 for(i = 0; i < len; i++)
599 if(rreg[i].clregex && !regexec(rreg[i].clregex, prop, 1, &tmp, 0)) {
600 c->isfloat = rule[i].isfloat;
601 if (rule[i].tag < 0) {
602 c->tag = seltag;
603 } else if (rule[i].tag == 0) {
604 c->tag = True;
605 } else {
606 c->tag = False;
607 }
608 matched = True;
609 break; /* perform only the first rule matching */
610 }
611 if(ch.res_class)
612 XFree(ch.res_class);
613 if(ch.res_name)
614 XFree(ch.res_name);
615 }
616 if(!matched) {
617 c->tag = seltag;
618 }
619 }
621 void
622 toggletag() {
623 if(!sel)
624 return;
625 sel->tag = !sel->tag;
626 toggleview();
627 }
645 /* from event.c */
646 /* static */
648 KEYS
652 static void
653 movemouse(Client *c) {
654 int x1, y1, ocx, ocy, di;
655 unsigned int dui;
656 Window dummy;
657 XEvent ev;
659 ocx = c->x;
660 ocy = c->y;
661 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
662 None, cursor[CurMove], CurrentTime) != GrabSuccess)
663 return;
664 c->ismax = False;
665 XQueryPointer(dpy, root, &dummy, &dummy, &x1, &y1, &di, &di, &dui);
666 for(;;) {
667 XMaskEvent(dpy, MOUSEMASK | ExposureMask | SubstructureRedirectMask, &ev);
668 switch (ev.type) {
669 case ButtonRelease:
670 resize(c, True);
671 XUngrabPointer(dpy, CurrentTime);
672 return;
673 case ConfigureRequest:
674 case Expose:
675 case MapRequest:
676 handler[ev.type](&ev);
677 break;
678 case MotionNotify:
679 XSync(dpy, False);
680 c->x = ocx + (ev.xmotion.x - x1);
681 c->y = ocy + (ev.xmotion.y - y1);
682 if(abs(wax + c->x) < SNAP)
683 c->x = wax;
684 else if(abs((wax + waw) - (c->x + c->w + 2 * c->border)) < SNAP)
685 c->x = wax + waw - c->w - 2 * c->border;
686 if(abs(way - c->y) < SNAP)
687 c->y = way;
688 else if(abs((way + wah) - (c->y + c->h + 2 * c->border)) < SNAP)
689 c->y = way + wah - c->h - 2 * c->border;
690 resize(c, False);
691 break;
692 }
693 }
694 }
696 static void
697 resizemouse(Client *c) {
698 int ocx, ocy;
699 int nw, nh;
700 XEvent ev;
702 ocx = c->x;
703 ocy = c->y;
704 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
705 None, cursor[CurResize], CurrentTime) != GrabSuccess)
706 return;
707 c->ismax = False;
708 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->border - 1, c->h + c->border - 1);
709 for(;;) {
710 XMaskEvent(dpy, MOUSEMASK | ExposureMask | SubstructureRedirectMask , &ev);
711 switch(ev.type) {
712 case ButtonRelease:
713 resize(c, True);
714 XUngrabPointer(dpy, CurrentTime);
715 return;
716 case ConfigureRequest:
717 case Expose:
718 case MapRequest:
719 handler[ev.type](&ev);
720 break;
721 case MotionNotify:
722 XSync(dpy, False);
723 nw = ev.xmotion.x - ocx - 2 * c->border + 1;
724 c->w = nw > 0 ? nw : 1;
725 nh = ev.xmotion.y - ocy - 2 * c->border + 1;
726 c->h = nh > 0 ? nh : 1;
727 resize(c, True);
728 break;
729 }
730 }
731 }
733 static void
734 buttonpress(XEvent *e) {
735 Client *c;
736 XButtonPressedEvent *ev = &e->xbutton;
738 if(barwin == ev->window) {
739 if(ev->button == Button1) {
740 toggleview();
741 }
742 return;
743 } else if((c = getclient(ev->window))) {
744 focus(c);
745 if(CLEANMASK(ev->state) != MODKEY)
746 return;
747 if(ev->button == Button1 && c->isfloat) {
748 restack();
749 movemouse(c);
750 } else if(ev->button == Button3 && c->isfloat && !c->isfixed) {
751 restack();
752 resizemouse(c);
753 }
754 }
755 }
757 static void
758 configurerequest(XEvent *e) {
759 unsigned long newmask;
760 Client *c;
761 XConfigureRequestEvent *ev = &e->xconfigurerequest;
762 XWindowChanges wc;
764 if((c = getclient(ev->window))) {
765 c->ismax = False;
766 if(ev->value_mask & CWX)
767 c->x = ev->x;
768 if(ev->value_mask & CWY)
769 c->y = ev->y;
770 if(ev->value_mask & CWWidth)
771 c->w = ev->width;
772 if(ev->value_mask & CWHeight)
773 c->h = ev->height;
774 if(ev->value_mask & CWBorderWidth)
775 c->border = ev->border_width;
776 wc.x = c->x;
777 wc.y = c->y;
778 wc.width = c->w;
779 wc.height = c->h;
780 newmask = ev->value_mask & (~(CWSibling | CWStackMode | CWBorderWidth));
781 if(newmask)
782 XConfigureWindow(dpy, c->win, newmask, &wc);
783 else
784 configure(c);
785 XSync(dpy, False);
786 if(c->isfloat) {
787 resize(c, False);
788 if(!isvisible(c))
789 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
790 }
791 else
792 arrange();
793 } else {
794 wc.x = ev->x;
795 wc.y = ev->y;
796 wc.width = ev->width;
797 wc.height = ev->height;
798 wc.border_width = ev->border_width;
799 wc.sibling = ev->above;
800 wc.stack_mode = ev->detail;
801 XConfigureWindow(dpy, ev->window, ev->value_mask, &wc);
802 XSync(dpy, False);
803 }
804 }
806 static void
807 destroynotify(XEvent *e) {
808 Client *c;
809 XDestroyWindowEvent *ev = &e->xdestroywindow;
811 if((c = getclient(ev->window)))
812 unmanage(c);
813 }
815 static void
816 enternotify(XEvent *e) {
817 Client *c;
818 XCrossingEvent *ev = &e->xcrossing;
820 if(ev->mode != NotifyNormal || ev->detail == NotifyInferior)
821 return;
822 if((c = getclient(ev->window)) && isvisible(c))
823 focus(c);
824 else if(ev->window == root) {
825 selscreen = True;
826 for(c = stack; c && !isvisible(c); c = c->snext);
827 focus(c);
828 }
829 }
831 static void
832 expose(XEvent *e) {
833 XExposeEvent *ev = &e->xexpose;
835 if(ev->count == 0) {
836 if(barwin == ev->window)
837 drawstatus();
838 }
839 }
841 static void
842 keypress(XEvent *e) {
843 static unsigned int len = sizeof key / sizeof key[0];
844 unsigned int i;
845 KeySym keysym;
846 XKeyEvent *ev = &e->xkey;
848 keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
849 for(i = 0; i < len; i++) {
850 if(keysym == key[i].keysym && CLEANMASK(key[i].mod) == CLEANMASK(ev->state)) {
851 if(key[i].func)
852 key[i].func(key[i].cmd);
853 }
854 }
855 }
857 static void
858 leavenotify(XEvent *e) {
859 XCrossingEvent *ev = &e->xcrossing;
861 if((ev->window == root) && !ev->same_screen) {
862 selscreen = False;
863 focus(NULL);
864 }
865 }
867 static void
868 mappingnotify(XEvent *e) {
869 XMappingEvent *ev = &e->xmapping;
871 XRefreshKeyboardMapping(ev);
872 if(ev->request == MappingKeyboard)
873 grabkeys();
874 }
876 static void
877 maprequest(XEvent *e) {
878 static XWindowAttributes wa;
879 XMapRequestEvent *ev = &e->xmaprequest;
881 if(!XGetWindowAttributes(dpy, ev->window, &wa))
882 return;
883 if(wa.override_redirect) {
884 XSelectInput(dpy, ev->window,
885 (StructureNotifyMask | PropertyChangeMask));
886 return;
887 }
888 if(!getclient(ev->window))
889 manage(ev->window, &wa);
890 }
892 static void
893 propertynotify(XEvent *e) {
894 Client *c;
895 Window trans;
896 XPropertyEvent *ev = &e->xproperty;
898 if(ev->state == PropertyDelete)
899 return; /* ignore */
900 if((c = getclient(ev->window))) {
901 switch (ev->atom) {
902 default: break;
903 case XA_WM_TRANSIENT_FOR:
904 XGetTransientForHint(dpy, c->win, &trans);
905 if(!c->isfloat && (c->isfloat = (trans != 0)))
906 arrange();
907 break;
908 case XA_WM_NORMAL_HINTS:
909 updatesizehints(c);
910 break;
911 }
912 if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
913 updatetitle(c);
914 if(c == sel)
915 drawstatus();
916 }
917 }
918 }
920 static void
921 unmapnotify(XEvent *e) {
922 Client *c;
923 XUnmapEvent *ev = &e->xunmap;
925 if((c = getclient(ev->window)))
926 unmanage(c);
927 }
931 void (*handler[LASTEvent]) (XEvent *) = {
932 [ButtonPress] = buttonpress,
933 [ConfigureRequest] = configurerequest,
934 [DestroyNotify] = destroynotify,
935 [EnterNotify] = enternotify,
936 [LeaveNotify] = leavenotify,
937 [Expose] = expose,
938 [KeyPress] = keypress,
939 [MappingNotify] = mappingnotify,
940 [MapRequest] = maprequest,
941 [PropertyNotify] = propertynotify,
942 [UnmapNotify] = unmapnotify
943 };
945 void
946 grabkeys(void) {
947 static unsigned int len = sizeof key / sizeof key[0];
948 unsigned int i;
949 KeyCode code;
951 XUngrabKey(dpy, AnyKey, AnyModifier, root);
952 for(i = 0; i < len; i++) {
953 code = XKeysymToKeycode(dpy, key[i].keysym);
954 XGrabKey(dpy, code, key[i].mod, root, True,
955 GrabModeAsync, GrabModeAsync);
956 XGrabKey(dpy, code, key[i].mod | LockMask, root, True,
957 GrabModeAsync, GrabModeAsync);
958 XGrabKey(dpy, code, key[i].mod | numlockmask, root, True,
959 GrabModeAsync, GrabModeAsync);
960 XGrabKey(dpy, code, key[i].mod | numlockmask | LockMask, root, True,
961 GrabModeAsync, GrabModeAsync);
962 }
963 }
965 void
966 procevent(void) {
967 XEvent ev;
969 while(XPending(dpy)) {
970 XNextEvent(dpy, &ev);
971 if(handler[ev.type])
972 (handler[ev.type])(&ev); /* call handler */
973 }
974 }
990 /* from draw.c */
991 /* static */
993 static unsigned int
994 textnw(const char *text, unsigned int len) {
995 XRectangle r;
997 if(dc.font.set) {
998 XmbTextExtents(dc.font.set, text, len, NULL, &r);
999 return r.width;
1001 return XTextWidth(dc.font.xfont, text, len);
1004 static void
1005 drawtext(const char *text, unsigned long col[ColLast]) {
1006 int x, y, w, h;
1007 static char buf[256];
1008 unsigned int len, olen;
1009 XGCValues gcv;
1010 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
1012 XSetForeground(dpy, dc.gc, col[ColBG]);
1013 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
1014 if(!text)
1015 return;
1016 w = 0;
1017 olen = len = strlen(text);
1018 if(len >= sizeof buf)
1019 len = sizeof buf - 1;
1020 memcpy(buf, text, len);
1021 buf[len] = 0;
1022 h = dc.font.ascent + dc.font.descent;
1023 y = dc.y + (dc.h / 2) - (h / 2) + dc.font.ascent;
1024 x = dc.x + (h / 2);
1025 /* shorten text if necessary */
1026 while(len && (w = textnw(buf, len)) > dc.w - h)
1027 buf[--len] = 0;
1028 if(len < olen) {
1029 if(len > 1)
1030 buf[len - 1] = '.';
1031 if(len > 2)
1032 buf[len - 2] = '.';
1033 if(len > 3)
1034 buf[len - 3] = '.';
1036 if(w > dc.w)
1037 return; /* too long */
1038 gcv.foreground = col[ColFG];
1039 if(dc.font.set) {
1040 XChangeGC(dpy, dc.gc, GCForeground, &gcv);
1041 XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
1042 } else {
1043 gcv.font = dc.font.xfont->fid;
1044 XChangeGC(dpy, dc.gc, GCForeground | GCFont, &gcv);
1045 XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
1051 void
1052 drawstatus(void) {
1053 int x;
1055 dc.x = dc.y = 0;
1056 dc.w = textw(NAMESEL);
1057 drawtext(NAMESEL, ( seltag ? dc.sel : dc.norm ));
1058 dc.x += dc.w + 1;
1059 dc.w = textw(NAMENSEL);
1060 drawtext(NAMENSEL, ( seltag ? dc.norm : dc.sel ));
1061 dc.x += dc.w + 1;
1062 dc.w = bmw;
1063 drawtext("", dc.norm);
1064 x = dc.x + dc.w;
1065 dc.w = textw(stext);
1066 dc.x = sw - dc.w;
1067 if(dc.x < x) {
1068 dc.x = x;
1069 dc.w = sw - x;
1071 drawtext(stext, dc.norm);
1072 if((dc.w = dc.x - x) > bh) {
1073 dc.x = x;
1074 drawtext(sel ? sel->name : NULL, dc.norm);
1076 XCopyArea(dpy, dc.drawable, barwin, dc.gc, 0, 0, sw, bh, 0, 0);
1077 XSync(dpy, False);
1080 unsigned long
1081 getcolor(const char *colstr) {
1082 Colormap cmap = DefaultColormap(dpy, screen);
1083 XColor color;
1085 if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
1086 eprint("error, cannot allocate color '%s'\n", colstr);
1087 return color.pixel;
1090 void
1091 setfont(const char *fontstr) {
1092 char *def, **missing;
1093 int i, n;
1095 missing = NULL;
1096 if(dc.font.set)
1097 XFreeFontSet(dpy, dc.font.set);
1098 dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
1099 if(missing) {
1100 while(n--)
1101 fprintf(stderr, "missing fontset: %s\n", missing[n]);
1102 XFreeStringList(missing);
1104 if(dc.font.set) {
1105 XFontSetExtents *font_extents;
1106 XFontStruct **xfonts;
1107 char **font_names;
1108 dc.font.ascent = dc.font.descent = 0;
1109 font_extents = XExtentsOfFontSet(dc.font.set);
1110 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
1111 for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
1112 if(dc.font.ascent < (*xfonts)->ascent)
1113 dc.font.ascent = (*xfonts)->ascent;
1114 if(dc.font.descent < (*xfonts)->descent)
1115 dc.font.descent = (*xfonts)->descent;
1116 xfonts++;
1118 } else {
1119 if(dc.font.xfont)
1120 XFreeFont(dpy, dc.font.xfont);
1121 dc.font.xfont = NULL;
1122 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr)))
1123 eprint("error, cannot load font: '%s'\n", fontstr);
1124 dc.font.ascent = dc.font.xfont->ascent;
1125 dc.font.descent = dc.font.xfont->descent;
1127 dc.font.height = dc.font.ascent + dc.font.descent;
1130 unsigned int
1131 textw(const char *text) {
1132 return textnw(text, strlen(text)) + dc.font.height;
1145 /* from client.c */
1146 /* static */
1148 static void
1149 detachstack(Client *c) {
1150 Client **tc;
1151 for(tc=&stack; *tc && *tc != c; tc=&(*tc)->snext);
1152 *tc = c->snext;
1155 static void
1156 grabbuttons(Client *c, Bool focused) {
1157 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1159 if(focused) {
1160 XGrabButton(dpy, Button1, MODKEY, c->win, False, BUTTONMASK,
1161 GrabModeAsync, GrabModeSync, None, None);
1162 XGrabButton(dpy, Button1, MODKEY | LockMask, c->win, False, BUTTONMASK,
1163 GrabModeAsync, GrabModeSync, None, None);
1164 XGrabButton(dpy, Button1, MODKEY | numlockmask, c->win, False, BUTTONMASK,
1165 GrabModeAsync, GrabModeSync, None, None);
1166 XGrabButton(dpy, Button1, MODKEY | numlockmask | LockMask, c->win, False, BUTTONMASK,
1167 GrabModeAsync, GrabModeSync, None, None);
1169 XGrabButton(dpy, Button2, MODKEY, c->win, False, BUTTONMASK,
1170 GrabModeAsync, GrabModeSync, None, None);
1171 XGrabButton(dpy, Button2, MODKEY | LockMask, c->win, False, BUTTONMASK,
1172 GrabModeAsync, GrabModeSync, None, None);
1173 XGrabButton(dpy, Button2, MODKEY | numlockmask, c->win, False, BUTTONMASK,
1174 GrabModeAsync, GrabModeSync, None, None);
1175 XGrabButton(dpy, Button2, MODKEY | numlockmask | LockMask, c->win, False, BUTTONMASK,
1176 GrabModeAsync, GrabModeSync, None, None);
1178 XGrabButton(dpy, Button3, MODKEY, c->win, False, BUTTONMASK,
1179 GrabModeAsync, GrabModeSync, None, None);
1180 XGrabButton(dpy, Button3, MODKEY | LockMask, c->win, False, BUTTONMASK,
1181 GrabModeAsync, GrabModeSync, None, None);
1182 XGrabButton(dpy, Button3, MODKEY | numlockmask, c->win, False, BUTTONMASK,
1183 GrabModeAsync, GrabModeSync, None, None);
1184 XGrabButton(dpy, Button3, MODKEY | numlockmask | LockMask, c->win, False, BUTTONMASK,
1185 GrabModeAsync, GrabModeSync, None, None);
1186 } else {
1187 XGrabButton(dpy, AnyButton, AnyModifier, c->win, False, BUTTONMASK,
1188 GrabModeAsync, GrabModeSync, None, None);
1192 static void
1193 setclientstate(Client *c, long state) {
1194 long data[] = {state, None};
1195 XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1196 PropModeReplace, (unsigned char *)data, 2);
1199 static int
1200 xerrordummy(Display *dsply, XErrorEvent *ee) {
1201 return 0;
1206 void
1207 configure(Client *c) {
1208 XEvent synev;
1210 synev.type = ConfigureNotify;
1211 synev.xconfigure.display = dpy;
1212 synev.xconfigure.event = c->win;
1213 synev.xconfigure.window = c->win;
1214 synev.xconfigure.x = c->x;
1215 synev.xconfigure.y = c->y;
1216 synev.xconfigure.width = c->w;
1217 synev.xconfigure.height = c->h;
1218 synev.xconfigure.border_width = c->border;
1219 synev.xconfigure.above = None;
1220 XSendEvent(dpy, c->win, True, NoEventMask, &synev);
1223 void
1224 focus(Client *c) {
1225 if(c && !isvisible(c))
1226 return;
1227 if(sel && sel != c) {
1228 grabbuttons(sel, False);
1229 XSetWindowBorder(dpy, sel->win, dc.norm[ColBorder]);
1231 if(c) {
1232 detachstack(c);
1233 c->snext = stack;
1234 stack = c;
1235 grabbuttons(c, True);
1237 sel = c;
1238 drawstatus();
1239 if(!selscreen)
1240 return;
1241 if(c) {
1242 XSetWindowBorder(dpy, c->win, dc.sel[ColBorder]);
1243 XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
1244 } else {
1245 XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
1249 Client *
1250 getclient(Window w) {
1251 Client *c;
1253 for(c = clients; c; c = c->next) {
1254 if(c->win == w) {
1255 return c;
1258 return NULL;
1261 Bool
1262 isprotodel(Client *c) {
1263 int i, n;
1264 Atom *protocols;
1265 Bool ret = False;
1267 if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
1268 for(i = 0; !ret && i < n; i++)
1269 if(protocols[i] == wmatom[WMDelete])
1270 ret = True;
1271 XFree(protocols);
1273 return ret;
1276 void
1277 killclient() {
1278 if(!sel)
1279 return;
1280 if(isprotodel(sel))
1281 sendevent(sel->win, wmatom[WMProtocols], wmatom[WMDelete]);
1282 else
1283 XKillClient(dpy, sel->win);
1286 void
1287 manage(Window w, XWindowAttributes *wa) {
1288 Client *c;
1289 Window trans;
1291 c = emallocz(sizeof(Client));
1292 c->tag = True;
1293 c->win = w;
1294 c->x = wa->x;
1295 c->y = wa->y;
1296 c->w = wa->width;
1297 c->h = wa->height;
1298 if(c->w == sw && c->h == sh) {
1299 c->border = 0;
1300 c->x = sx;
1301 c->y = sy;
1302 } else {
1303 c->border = BORDERPX;
1304 if(c->x + c->w + 2 * c->border > wax + waw)
1305 c->x = wax + waw - c->w - 2 * c->border;
1306 if(c->y + c->h + 2 * c->border > way + wah)
1307 c->y = way + wah - c->h - 2 * c->border;
1308 if(c->x < wax)
1309 c->x = wax;
1310 if(c->y < way)
1311 c->y = way;
1313 updatesizehints(c);
1314 XSelectInput(dpy, c->win,
1315 StructureNotifyMask | PropertyChangeMask | EnterWindowMask);
1316 XGetTransientForHint(dpy, c->win, &trans);
1317 grabbuttons(c, False);
1318 XSetWindowBorder(dpy, c->win, dc.norm[ColBorder]);
1319 updatetitle(c);
1320 settags(c, getclient(trans));
1321 if(!c->isfloat)
1322 c->isfloat = trans || c->isfixed;
1323 if(clients)
1324 clients->prev = c;
1325 c->next = clients;
1326 c->snext = stack;
1327 stack = clients = c;
1328 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
1329 XMapWindow(dpy, c->win);
1330 setclientstate(c, NormalState);
1331 if(isvisible(c))
1332 focus(c);
1333 arrange();
1336 void
1337 resize(Client *c, Bool sizehints) {
1338 float actual, dx, dy, max, min;
1339 XWindowChanges wc;
1341 if(c->w <= 0 || c->h <= 0)
1342 return;
1343 if(sizehints) {
1344 if(c->minw && c->w < c->minw)
1345 c->w = c->minw;
1346 if(c->minh && c->h < c->minh)
1347 c->h = c->minh;
1348 if(c->maxw && c->w > c->maxw)
1349 c->w = c->maxw;
1350 if(c->maxh && c->h > c->maxh)
1351 c->h = c->maxh;
1352 /* inspired by algorithm from fluxbox */
1353 if(c->minay > 0 && c->maxay && (c->h - c->baseh) > 0) {
1354 dx = (float)(c->w - c->basew);
1355 dy = (float)(c->h - c->baseh);
1356 min = (float)(c->minax) / (float)(c->minay);
1357 max = (float)(c->maxax) / (float)(c->maxay);
1358 actual = dx / dy;
1359 if(max > 0 && min > 0 && actual > 0) {
1360 if(actual < min) {
1361 dy = (dx * min + dy) / (min * min + 1);
1362 dx = dy * min;
1363 c->w = (int)dx + c->basew;
1364 c->h = (int)dy + c->baseh;
1366 else if(actual > max) {
1367 dy = (dx * min + dy) / (max * max + 1);
1368 dx = dy * min;
1369 c->w = (int)dx + c->basew;
1370 c->h = (int)dy + c->baseh;
1374 if(c->incw)
1375 c->w -= (c->w - c->basew) % c->incw;
1376 if(c->inch)
1377 c->h -= (c->h - c->baseh) % c->inch;
1379 if(c->w == sw && c->h == sh)
1380 c->border = 0;
1381 else
1382 c->border = BORDERPX;
1383 /* offscreen appearance fixes */
1384 if(c->x > sw)
1385 c->x = sw - c->w - 2 * c->border;
1386 if(c->y > sh)
1387 c->y = sh - c->h - 2 * c->border;
1388 if(c->x + c->w + 2 * c->border < sx)
1389 c->x = sx;
1390 if(c->y + c->h + 2 * c->border < sy)
1391 c->y = sy;
1392 wc.x = c->x;
1393 wc.y = c->y;
1394 wc.width = c->w;
1395 wc.height = c->h;
1396 wc.border_width = c->border;
1397 XConfigureWindow(dpy, c->win, CWX | CWY | CWWidth | CWHeight | CWBorderWidth, &wc);
1398 configure(c);
1399 XSync(dpy, False);
1402 void
1403 updatesizehints(Client *c) {
1404 long msize;
1405 XSizeHints size;
1407 if(!XGetWMNormalHints(dpy, c->win, &size, &msize) || !size.flags)
1408 size.flags = PSize;
1409 c->flags = size.flags;
1410 if(c->flags & PBaseSize) {
1411 c->basew = size.base_width;
1412 c->baseh = size.base_height;
1413 } else {
1414 c->basew = c->baseh = 0;
1416 if(c->flags & PResizeInc) {
1417 c->incw = size.width_inc;
1418 c->inch = size.height_inc;
1419 } else {
1420 c->incw = c->inch = 0;
1422 if(c->flags & PMaxSize) {
1423 c->maxw = size.max_width;
1424 c->maxh = size.max_height;
1425 } else {
1426 c->maxw = c->maxh = 0;
1428 if(c->flags & PMinSize) {
1429 c->minw = size.min_width;
1430 c->minh = size.min_height;
1431 } else {
1432 c->minw = c->minh = 0;
1434 if(c->flags & PAspect) {
1435 c->minax = size.min_aspect.x;
1436 c->minay = size.min_aspect.y;
1437 c->maxax = size.max_aspect.x;
1438 c->maxay = size.max_aspect.y;
1439 } else {
1440 c->minax = c->minay = c->maxax = c->maxay = 0;
1442 c->isfixed = (c->maxw && c->minw && c->maxh && c->minh &&
1443 c->maxw == c->minw && c->maxh == c->minh);
1446 void
1447 updatetitle(Client *c) {
1448 char **list = NULL;
1449 int n;
1450 XTextProperty name;
1452 name.nitems = 0;
1453 c->name[0] = 0;
1454 XGetTextProperty(dpy, c->win, &name, netatom[NetWMName]);
1455 if(!name.nitems)
1456 XGetWMName(dpy, c->win, &name);
1457 if(!name.nitems)
1458 return;
1459 if(name.encoding == XA_STRING)
1460 strncpy(c->name, (char *)name.value, sizeof c->name);
1461 else {
1462 if(XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success && n > 0 && *list) {
1463 strncpy(c->name, *list, sizeof c->name);
1464 XFreeStringList(list);
1467 XFree(name.value);
1470 void
1471 unmanage(Client *c) {
1472 Client *nc;
1474 /* The server grab construct avoids race conditions. */
1475 XGrabServer(dpy);
1476 XSetErrorHandler(xerrordummy);
1477 detach(c);
1478 detachstack(c);
1479 if(sel == c) {
1480 for(nc = stack; nc && !isvisible(nc); nc = nc->snext);
1481 focus(nc);
1483 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1484 setclientstate(c, WithdrawnState);
1485 free(c);
1486 XSync(dpy, False);
1487 XSetErrorHandler(xerror);
1488 XUngrabServer(dpy);
1489 arrange();
1510 /* static */
1513 static void
1514 cleanup(void) {
1515 close(STDIN_FILENO);
1516 while(stack) {
1517 resize(stack, True);
1518 unmanage(stack);
1520 if(dc.font.set)
1521 XFreeFontSet(dpy, dc.font.set);
1522 else
1523 XFreeFont(dpy, dc.font.xfont);
1524 XUngrabKey(dpy, AnyKey, AnyModifier, root);
1525 XFreePixmap(dpy, dc.drawable);
1526 XFreeGC(dpy, dc.gc);
1527 XDestroyWindow(dpy, barwin);
1528 XFreeCursor(dpy, cursor[CurNormal]);
1529 XFreeCursor(dpy, cursor[CurResize]);
1530 XFreeCursor(dpy, cursor[CurMove]);
1531 XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime);
1532 XSync(dpy, False);
1535 static void
1536 scan(void) {
1537 unsigned int i, num;
1538 Window *wins, d1, d2;
1539 XWindowAttributes wa;
1541 wins = NULL;
1542 if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1543 for(i = 0; i < num; i++) {
1544 if(!XGetWindowAttributes(dpy, wins[i], &wa))
1545 continue;
1546 if(wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1547 continue;
1548 if(wa.map_state == IsViewable)
1549 manage(wins[i], &wa);
1552 if(wins)
1553 XFree(wins);
1556 static void
1557 setup(void) {
1558 int i, j;
1559 unsigned int mask;
1560 Window w;
1561 XModifierKeymap *modmap;
1562 XSetWindowAttributes wa;
1564 /* init atoms */
1565 wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1566 wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1567 wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1568 netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1569 netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1570 XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1571 PropModeReplace, (unsigned char *) netatom, NetLast);
1572 /* init cursors */
1573 cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1574 cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1575 cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1576 /* init modifier map */
1577 numlockmask = 0;
1578 modmap = XGetModifierMapping(dpy);
1579 for (i = 0; i < 8; i++) {
1580 for (j = 0; j < modmap->max_keypermod; j++) {
1581 if(modmap->modifiermap[i * modmap->max_keypermod + j] == XKeysymToKeycode(dpy, XK_Num_Lock))
1582 numlockmask = (1 << i);
1585 XFreeModifiermap(modmap);
1586 /* select for events */
1587 wa.event_mask = SubstructureRedirectMask | SubstructureNotifyMask
1588 | EnterWindowMask | LeaveWindowMask;
1589 wa.cursor = cursor[CurNormal];
1590 XChangeWindowAttributes(dpy, root, CWEventMask | CWCursor, &wa);
1591 grabkeys();
1592 initrregs();
1593 seltag = True;
1594 /* style */
1595 dc.norm[ColBorder] = getcolor(NORMBORDERCOLOR);
1596 dc.norm[ColBG] = getcolor(NORMBGCOLOR);
1597 dc.norm[ColFG] = getcolor(NORMFGCOLOR);
1598 dc.sel[ColBorder] = getcolor(SELBORDERCOLOR);
1599 dc.sel[ColBG] = getcolor(SELBGCOLOR);
1600 dc.sel[ColFG] = getcolor(SELFGCOLOR);
1601 setfont(FONT);
1602 /* geometry */
1603 sx = sy = 0;
1604 sw = DisplayWidth(dpy, screen);
1605 sh = DisplayHeight(dpy, screen);
1606 nmaster = NMASTER;
1607 bmw = 1;
1608 /* bar */
1609 dc.h = bh = dc.font.height + 2;
1610 wa.override_redirect = 1;
1611 wa.background_pixmap = ParentRelative;
1612 wa.event_mask = ButtonPressMask | ExposureMask;
1613 barwin = XCreateWindow(dpy, root, sx, sy, sw, bh, 0,
1614 DefaultDepth(dpy, screen), CopyFromParent, DefaultVisual(dpy, screen),
1615 CWOverrideRedirect | CWBackPixmap | CWEventMask, &wa);
1616 XDefineCursor(dpy, barwin, cursor[CurNormal]);
1617 XMapRaised(dpy, barwin);
1618 strcpy(stext, "dwm-"VERSION);
1619 /* windowarea */
1620 wax = sx;
1621 way = sy + bh;
1622 wah = sh - bh;
1623 waw = sw;
1624 /* pixmap for everything */
1625 dc.drawable = XCreatePixmap(dpy, root, sw, bh, DefaultDepth(dpy, screen));
1626 dc.gc = XCreateGC(dpy, root, 0, 0);
1627 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
1628 /* multihead support */
1629 selscreen = XQueryPointer(dpy, root, &w, &w, &i, &i, &i, &i, &mask);
1632 /*
1633 * Startup Error handler to check if another window manager
1634 * is already running.
1635 */
1636 static int
1637 xerrorstart(Display *dsply, XErrorEvent *ee) {
1638 otherwm = True;
1639 return -1;
1644 void
1645 sendevent(Window w, Atom a, long value) {
1646 XEvent e;
1648 e.type = ClientMessage;
1649 e.xclient.window = w;
1650 e.xclient.message_type = a;
1651 e.xclient.format = 32;
1652 e.xclient.data.l[0] = value;
1653 e.xclient.data.l[1] = CurrentTime;
1654 XSendEvent(dpy, w, False, NoEventMask, &e);
1655 XSync(dpy, False);
1658 void
1659 quit() {
1660 readin = running = False;
1663 /* There's no way to check accesses to destroyed windows, thus those cases are
1664 * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
1665 * default error handler, which may call exit.
1666 */
1667 int
1668 xerror(Display *dpy, XErrorEvent *ee) {
1669 if(ee->error_code == BadWindow
1670 || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1671 || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1672 || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1673 || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1674 || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1675 || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1676 || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1677 return 0;
1678 fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1679 ee->request_code, ee->error_code);
1680 return xerrorxlib(dpy, ee); /* may call exit */
1683 int
1684 main(int argc, char *argv[]) {
1685 char *p;
1686 int r, xfd;
1687 fd_set rd;
1689 if(argc == 2 && !strncmp("-v", argv[1], 3)) {
1690 fputs("dwm-"VERSION", (C)opyright MMVI-MMVII Anselm R. Garbe\n", stdout);
1691 exit(EXIT_SUCCESS);
1692 } else if(argc != 1) {
1693 eprint("usage: dwm [-v]\n");
1695 setlocale(LC_CTYPE, "");
1696 dpy = XOpenDisplay(0);
1697 if(!dpy) {
1698 eprint("dwm: cannot open display\n");
1700 xfd = ConnectionNumber(dpy);
1701 screen = DefaultScreen(dpy);
1702 root = RootWindow(dpy, screen);
1703 otherwm = False;
1704 XSetErrorHandler(xerrorstart);
1705 /* this causes an error if some other window manager is running */
1706 XSelectInput(dpy, root, SubstructureRedirectMask);
1707 XSync(dpy, False);
1708 if(otherwm) {
1709 eprint("dwm: another window manager is already running\n");
1712 XSync(dpy, False);
1713 XSetErrorHandler(NULL);
1714 xerrorxlib = XSetErrorHandler(xerror);
1715 XSync(dpy, False);
1716 setup();
1717 drawstatus();
1718 scan();
1720 /* main event loop, also reads status text from stdin */
1721 XSync(dpy, False);
1722 procevent();
1723 readin = True;
1724 while(running) {
1725 FD_ZERO(&rd);
1726 if(readin)
1727 FD_SET(STDIN_FILENO, &rd);
1728 FD_SET(xfd, &rd);
1729 if(select(xfd + 1, &rd, NULL, NULL, NULL) == -1) {
1730 if(errno == EINTR)
1731 continue;
1732 eprint("select failed\n");
1734 if(FD_ISSET(STDIN_FILENO, &rd)) {
1735 switch(r = read(STDIN_FILENO, stext, sizeof stext - 1)) {
1736 case -1:
1737 strncpy(stext, strerror(errno), sizeof stext - 1);
1738 stext[sizeof stext - 1] = '\0';
1739 readin = False;
1740 break;
1741 case 0:
1742 strncpy(stext, "EOF", 4);
1743 readin = False;
1744 break;
1745 default:
1746 for(stext[r] = '\0', p = stext + strlen(stext) - 1; p >= stext && *p == '\n'; *p-- = '\0');
1747 for(; p >= stext && *p != '\n'; --p);
1748 if(p > stext)
1749 strncpy(stext, p + 1, sizeof stext);
1751 drawstatus();
1753 if(FD_ISSET(xfd, &rd))
1754 procevent();
1756 cleanup();
1757 XCloseDisplay(dpy);
1758 return 0;