aewl
view dwm.c @ 757:427608ef0687
modified makefile
author | meillo@marmaro.de |
---|---|
date | Fri, 30 May 2008 00:34:38 +0200 |
parents | cdd895c163bd |
children | bc512840e5a5 |
line source
1 /* (C)opyright MMVI-MMVII Anselm R. Garbe <garbeam at gmail dot com>
2 * See LICENSE file for license details.
3 *
4 * dynamic window manager is designed like any other X client as well. It is
5 * driven through handling X events. In contrast to other X clients, a window
6 * manager selects for SubstructureRedirectMask on the root window, to receive
7 * events about window (dis-)appearance. Only one X connection at a time is
8 * allowed to select for this event mask.
9 *
10 * Calls to fetch an X event from the event queue are blocking. Due reading
11 * status text from standard input, a select()-driven main loop has been
12 * implemented which selects for reads on the X connection and STDIN_FILENO to
13 * handle all data smoothly. The event handlers of dwm are organized in an
14 * array which is accessed whenever a new event has been fetched. This allows
15 * event dispatching in O(1) time.
16 *
17 * Each child of the root window is called a client, except windows which have
18 * set the override_redirect flag. Clients are organized in a global
19 * doubly-linked client list, the focus history is remembered through a global
20 * stack list. Each client contains an array of Bools of the same size as the
21 * global tags array to indicate the tags of a client. For each client dwm
22 * creates a small title window, which is resized whenever the (_NET_)WM_NAME
23 * properties are updated or the client is moved/resized.
24 *
25 * Keys and tagging rules are organized as arrays and defined in the config.h
26 * file. These arrays are kept static in event.o and tag.o respectively,
27 * because no other part of dwm needs access to them. The current mode is
28 * represented by the arrange() function pointer, which wether points to
29 * dofloat() or dotile().
30 *
31 * To understand everything else, start reading main.c:main().
32 */
34 #include "config.h"
35 #include <errno.h>
36 #include <locale.h>
37 #include <regex.h>
38 #include <stdio.h>
39 #include <stdarg.h>
40 #include <stdlib.h>
41 #include <string.h>
42 #include <unistd.h>
43 #include <sys/select.h>
44 #include <sys/types.h>
45 #include <sys/wait.h>
46 #include <X11/cursorfont.h>
47 #include <X11/keysym.h>
48 #include <X11/Xatom.h>
49 #include <X11/Xlib.h>
50 #include <X11/Xproto.h>
51 #include <X11/Xutil.h>
53 /* mask shorthands, used in event.c and client.c */
54 #define BUTTONMASK (ButtonPressMask | ButtonReleaseMask)
56 enum { NetSupported, NetWMName, NetLast }; /* EWMH atoms */
57 enum { WMProtocols, WMDelete, WMState, WMLast }; /* default atoms */
58 enum { CurNormal, CurResize, CurMove, CurLast }; /* cursor */
59 enum { ColBorder, ColFG, ColBG, ColLast }; /* color */
61 typedef union {
62 const char *cmd;
63 int i;
64 } Arg; /* argument type */
66 typedef struct {
67 int ascent;
68 int descent;
69 int height;
70 XFontSet set;
71 XFontStruct *xfont;
72 } Fnt;
74 typedef struct {
75 int x, y, w, h;
76 unsigned long norm[ColLast];
77 unsigned long sel[ColLast];
78 Drawable drawable;
79 Fnt font;
80 GC gc;
81 } DC; /* draw context */
83 typedef struct Client Client;
84 struct Client {
85 char name[256];
86 int x, y, w, h;
87 int rx, ry, rw, rh; /* revert geometry */
88 int basew, baseh, incw, inch, maxw, maxh, minw, minh;
89 int minax, minay, maxax, maxay;
90 long flags;
91 unsigned int border;
92 Bool isfixed, isfloat, ismax;
93 Bool tag;
94 Client *next;
95 Client *prev;
96 Client *snext;
97 Window win;
98 };
100 typedef struct {
101 const char *clpattern;
102 int tag;
103 Bool isfloat;
104 } Rule;
106 typedef struct {
107 regex_t *clregex;
108 } RReg;
111 typedef struct {
112 unsigned long mod;
113 KeySym keysym;
114 void (*func)(Arg *arg);
115 Arg arg;
116 } Key;
119 #define CLEANMASK(mask) (mask & ~(numlockmask | LockMask))
120 #define MOUSEMASK (BUTTONMASK | PointerMotionMask)
124 const char *tags[]; /* all tags */
125 char stext[256]; /* status text */
126 int bh, bmw; /* bar height, bar mode label width */
127 int screen, sx, sy, sw, sh; /* screen geometry */
128 int wax, way, wah, waw; /* windowarea geometry */
129 unsigned int nmaster; /* number of master clients */
130 unsigned int ntags, numlockmask; /* number of tags, dynamic lock mask */
131 void (*handler[LASTEvent])(XEvent *); /* event handler */
132 void (*arrange)(void); /* arrange function, indicates mode */
133 Atom wmatom[WMLast], netatom[NetLast];
134 Bool running, selscreen, seltag; /* seltag is array of Bool */
135 Client *clients, *sel, *stack; /* global client list and stack */
136 Cursor cursor[CurLast];
137 DC dc; /* global draw context */
138 Display *dpy;
139 Window root, barwin;
141 Bool running = True;
142 Bool selscreen = True;
143 Client *clients = NULL;
144 Client *sel = NULL;
145 Client *stack = NULL;
146 DC dc = {0};
148 static int (*xerrorxlib)(Display *, XErrorEvent *);
149 static Bool otherwm, readin;
150 static RReg *rreg = NULL;
151 static unsigned int len = 0;
154 TAGS
155 RULES
158 /* client.c */
159 void configure(Client *c); /* send synthetic configure event */
160 void focus(Client *c); /* focus c, c may be NULL */
161 Client *getclient(Window w); /* return client of w */
162 Bool isprotodel(Client *c); /* returns True if c->win supports wmatom[WMDelete] */
163 void killclient(); /* kill c nicely */
164 void manage(Window w, XWindowAttributes *wa); /* manage new client */
165 void resize(Client *c, Bool sizehints); /* resize c*/
166 void updatesizehints(Client *c); /* update the size hint variables of c */
167 void updatetitle(Client *c); /* update the name of c */
168 void unmanage(Client *c); /* destroy c */
170 /* draw.c */
171 void drawstatus(void); /* draw the bar */
172 unsigned long getcolor(const char *colstr); /* return color of colstr */
173 void setfont(const char *fontstr); /* set the font for DC */
174 unsigned int textw(const char *text); /* return the width of text in px*/
176 /* event.c */
177 void grabkeys(void); /* grab all keys defined in config.h */
178 void procevent(void); /* process pending X events */
180 /* main.c */
181 void quit(); /* quit dwm nicely */
182 void sendevent(Window w, Atom a, long value); /* send synthetic event to w */
183 int xerror(Display *dsply, XErrorEvent *ee); /* dwm's X error handler */
185 /* tag.c */
186 void initrregs(void); /* initialize regexps of rules defined in config.h */
187 Client *getnext(Client *c); /* returns next visible client */
188 void settags(Client *c, Client *trans); /* sets tags of c */
189 void toggletag(); /* toggles c tags with arg's index */
191 /* util.c */
192 void *emallocz(unsigned int size); /* allocates zero-initialized memory, exits on error */
193 void eprint(const char *errstr, ...); /* prints errstr and exits with 1 */
194 void spawn(Arg *arg); /* forks a new subprocess with to arg's cmd */
196 /* view.c */
197 void detach(Client *c); /* detaches c from global client list */
198 void dofloat(void); /* arranges all windows floating */
199 void dotile(void); /* arranges all windows tiled */
200 void domax(void); /* arranges all windows fullscreen */
201 void focusnext(); /* focuses next visible client, arg is ignored */
202 void incnmaster(); /* increments nmaster */
203 void decnmaster(); /* decrements nmaster */
204 Bool isvisible(Client *c); /* returns True if client is visible */
205 void restack(void); /* restores z layers of all clients */
206 void togglefloat(); /* toggles focusesd client between floating/non-floating state */
207 void togglemode(); /* toggles global arrange function (dotile/dofloat) */
208 void toggleview(); /* views the tag with arg's index */
209 void zoom(); /* zooms the focused client to master area, arg is ignored */
220 /* from view.c */
221 /* static */
223 static Client *
224 nexttiled(Client *c) {
225 for(c = getnext(c); c && c->isfloat; c = getnext(c->next));
226 return c;
227 }
229 static void
230 togglemax(Client *c) {
231 XEvent ev;
233 if(c->isfixed)
234 return;
236 if((c->ismax = !c->ismax)) {
237 c->rx = c->x; c->x = wax;
238 c->ry = c->y; c->y = way;
239 c->rw = c->w; c->w = waw - 2 * BORDERPX;
240 c->rh = c->h; c->h = wah - 2 * BORDERPX;
241 }
242 else {
243 c->x = c->rx;
244 c->y = c->ry;
245 c->w = c->rw;
246 c->h = c->rh;
247 }
248 resize(c, True);
249 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
250 }
254 void (*arrange)(void) = DEFMODE;
256 void
257 detach(Client *c) {
258 if(c->prev)
259 c->prev->next = c->next;
260 if(c->next)
261 c->next->prev = c->prev;
262 if(c == clients)
263 clients = c->next;
264 c->next = c->prev = NULL;
265 }
267 void
268 dofloat(void) {
269 Client *c;
271 for(c = clients; c; c = c->next) {
272 if(isvisible(c)) {
273 resize(c, True);
274 }
275 else
276 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
277 }
278 if(!sel || !isvisible(sel)) {
279 for(c = stack; c && !isvisible(c); c = c->snext);
280 focus(c);
281 }
282 restack();
283 }
285 void
286 dotile(void) {
287 unsigned int i, n, mw, mh, tw, th;
288 Client *c;
290 for(n = 0, c = nexttiled(clients); c; c = nexttiled(c->next))
291 n++;
292 /* window geoms */
293 mh = (n > nmaster) ? wah / nmaster : wah / (n > 0 ? n : 1);
294 mw = (n > nmaster) ? waw / 2 : waw;
295 th = (n > nmaster) ? wah / (n - nmaster) : 0;
296 tw = waw - mw;
298 for(i = 0, c = clients; c; c = c->next)
299 if(isvisible(c)) {
300 if(c->isfloat) {
301 resize(c, True);
302 continue;
303 }
304 c->ismax = False;
305 c->x = wax;
306 c->y = way;
307 if(i < nmaster) {
308 c->y += i * mh;
309 c->w = mw - 2 * BORDERPX;
310 c->h = mh - 2 * BORDERPX;
311 }
312 else { /* tile window */
313 c->x += mw;
314 c->w = tw - 2 * BORDERPX;
315 if(th > 2 * BORDERPX) {
316 c->y += (i - nmaster) * th;
317 c->h = th - 2 * BORDERPX;
318 }
319 else /* fallback if th <= 2 * BORDERPX */
320 c->h = wah - 2 * BORDERPX;
321 }
322 resize(c, False);
323 i++;
324 }
325 else
326 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
327 if(!sel || !isvisible(sel)) {
328 for(c = stack; c && !isvisible(c); c = c->snext);
329 focus(c);
330 }
331 restack();
332 }
334 /* begin code by mitch */
335 void
336 arrangemax(Client *c) {
337 if(c == sel) {
338 c->ismax = True;
339 c->x = sx;
340 c->y = bh;
341 c->w = sw - 2 * BORDERPX;
342 c->h = sh - bh - 2 * BORDERPX;
343 XRaiseWindow(dpy, c->win);
344 } else {
345 c->ismax = False;
346 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
347 XLowerWindow(dpy, c->win);
348 }
349 }
351 void
352 domax(void) {
353 Client *c;
355 for(c = clients; c; c = c->next) {
356 if(isvisible(c)) {
357 if(c->isfloat) {
358 resize(c, True);
359 continue;
360 }
361 arrangemax(c);
362 resize(c, False);
363 } else {
364 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
365 }
367 }
368 if(!sel || !isvisible(sel)) {
369 for(c = stack; c && !isvisible(c); c = c->snext);
370 focus(c);
371 }
372 restack();
373 }
374 /* end code by mitch */
376 void
377 focusnext() {
378 Client *c;
380 if(!sel)
381 return;
382 if(!(c = getnext(sel->next)))
383 c = getnext(clients);
384 if(c) {
385 focus(c);
386 restack();
387 }
388 }
390 void
391 incnmaster() {
392 if((arrange == dofloat) || (wah / (nmaster + 1) <= 2 * BORDERPX))
393 return;
394 nmaster++;
395 if(sel)
396 arrange();
397 else
398 drawstatus();
399 }
401 void
402 decnmaster() {
403 if((arrange == dofloat) || (nmaster <= 1))
404 return;
405 nmaster--;
406 if(sel)
407 arrange();
408 else
409 drawstatus();
410 }
412 Bool
413 isvisible(Client *c) {
414 if((c->tag && seltag) || (!c->tag && !seltag)) {
415 return True;
416 }
417 return False;
418 }
420 void
421 restack(void) {
422 Client *c;
423 XEvent ev;
425 drawstatus();
426 if(!sel)
427 return;
428 if(sel->isfloat || arrange == dofloat)
429 XRaiseWindow(dpy, sel->win);
431 /* begin code by mitch */
432 if(arrange == domax) {
433 for(c = nexttiled(clients); c; c = nexttiled(c->next)) {
434 arrangemax(c);
435 resize(c, False);
436 }
438 } else if (arrange == dotile) {
439 /* end code by mitch */
441 if(!sel->isfloat)
442 XLowerWindow(dpy, sel->win);
443 for(c = nexttiled(clients); c; c = nexttiled(c->next)) {
444 if(c == sel)
445 continue;
446 XLowerWindow(dpy, c->win);
447 }
448 }
449 XSync(dpy, False);
450 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
451 }
453 void
454 togglefloat() {
455 if (!sel || arrange == dofloat)
456 return;
457 sel->isfloat = !sel->isfloat;
458 arrange();
459 }
461 void
462 togglemode() {
463 /* only toggle between tile and max - float is just available through togglefloat */
464 arrange = (arrange == dotile) ? domax : dotile;
465 if(sel)
466 arrange();
467 else
468 drawstatus();
469 }
471 void
472 toggleview() {
473 seltag = !seltag;
474 arrange();
475 }
477 void
478 zoom() {
479 unsigned int n;
480 Client *c;
482 if(!sel)
483 return;
484 if(sel->isfloat || (arrange == dofloat)) {
485 togglemax(sel);
486 return;
487 }
488 for(n = 0, c = nexttiled(clients); c; c = nexttiled(c->next))
489 n++;
491 if((c = sel) == nexttiled(clients))
492 if(!(c = nexttiled(c->next)))
493 return;
494 detach(c);
495 if(clients)
496 clients->prev = c;
497 c->next = clients;
498 clients = c;
499 focus(c);
500 arrange();
501 }
518 /* from util.c */
521 void *
522 emallocz(unsigned int size) {
523 void *res = calloc(1, size);
525 if(!res)
526 eprint("fatal: could not malloc() %u bytes\n", size);
527 return res;
528 }
530 void
531 eprint(const char *errstr, ...) {
532 va_list ap;
534 va_start(ap, errstr);
535 vfprintf(stderr, errstr, ap);
536 va_end(ap);
537 exit(EXIT_FAILURE);
538 }
540 void
541 spawn(Arg *arg) {
542 static char *shell = NULL;
544 if(!shell && !(shell = getenv("SHELL")))
545 shell = "/bin/sh";
546 if(!arg->cmd)
547 return;
548 /* The double-fork construct avoids zombie processes and keeps the code
549 * clean from stupid signal handlers. */
550 if(fork() == 0) {
551 if(fork() == 0) {
552 if(dpy)
553 close(ConnectionNumber(dpy));
554 setsid();
555 execl(shell, shell, "-c", arg->cmd, (char *)NULL);
556 fprintf(stderr, "dwm: execl '%s -c %s'", shell, arg->cmd);
557 perror(" failed");
558 }
559 exit(0);
560 }
561 wait(0);
562 }
576 /* from tag.c */
578 /* static */
580 Client *
581 getnext(Client *c) {
582 for(; c && !isvisible(c); c = c->next);
583 return c;
584 }
586 void
587 initrregs(void) {
588 unsigned int i;
589 regex_t *reg;
591 if(rreg)
592 return;
593 len = sizeof rule / sizeof rule[0];
594 rreg = emallocz(len * sizeof(RReg));
595 for(i = 0; i < len; i++) {
596 if(rule[i].clpattern) {
597 reg = emallocz(sizeof(regex_t));
598 if(regcomp(reg, rule[i].clpattern, REG_EXTENDED))
599 free(reg);
600 else
601 rreg[i].clregex = reg;
602 }
603 }
604 }
606 void
607 settags(Client *c, Client *trans) {
608 char prop[512];
609 unsigned int i;
610 regmatch_t tmp;
611 Bool matched = trans != NULL;
612 XClassHint ch = { 0 };
614 if(matched) {
615 c->tag = trans->tag;
616 } else {
617 XGetClassHint(dpy, c->win, &ch);
618 snprintf(prop, sizeof prop, "%s:%s:%s",
619 ch.res_class ? ch.res_class : "",
620 ch.res_name ? ch.res_name : "", c->name);
621 for(i = 0; i < len; i++)
622 if(rreg[i].clregex && !regexec(rreg[i].clregex, prop, 1, &tmp, 0)) {
623 c->isfloat = rule[i].isfloat;
624 if (rule[i].tag < 0) {
625 c->tag = seltag;
626 } else if (rule[i].tag == 0) {
627 c->tag = True;
628 } else {
629 c->tag = False;
630 }
631 matched = True;
632 break; /* perform only the first rule matching */
633 }
634 if(ch.res_class)
635 XFree(ch.res_class);
636 if(ch.res_name)
637 XFree(ch.res_name);
638 }
639 if(!matched) {
640 c->tag = seltag;
641 }
642 }
644 void
645 toggletag() {
646 if(!sel)
647 return;
648 sel->tag = !sel->tag;
649 toggleview();
650 }
668 /* from event.c */
669 /* static */
671 KEYS
675 static void
676 movemouse(Client *c) {
677 int x1, y1, ocx, ocy, di;
678 unsigned int dui;
679 Window dummy;
680 XEvent ev;
682 ocx = c->x;
683 ocy = c->y;
684 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
685 None, cursor[CurMove], CurrentTime) != GrabSuccess)
686 return;
687 c->ismax = False;
688 XQueryPointer(dpy, root, &dummy, &dummy, &x1, &y1, &di, &di, &dui);
689 for(;;) {
690 XMaskEvent(dpy, MOUSEMASK | ExposureMask | SubstructureRedirectMask, &ev);
691 switch (ev.type) {
692 case ButtonRelease:
693 resize(c, True);
694 XUngrabPointer(dpy, CurrentTime);
695 return;
696 case ConfigureRequest:
697 case Expose:
698 case MapRequest:
699 handler[ev.type](&ev);
700 break;
701 case MotionNotify:
702 XSync(dpy, False);
703 c->x = ocx + (ev.xmotion.x - x1);
704 c->y = ocy + (ev.xmotion.y - y1);
705 if(abs(wax + c->x) < SNAP)
706 c->x = wax;
707 else if(abs((wax + waw) - (c->x + c->w + 2 * c->border)) < SNAP)
708 c->x = wax + waw - c->w - 2 * c->border;
709 if(abs(way - c->y) < SNAP)
710 c->y = way;
711 else if(abs((way + wah) - (c->y + c->h + 2 * c->border)) < SNAP)
712 c->y = way + wah - c->h - 2 * c->border;
713 resize(c, False);
714 break;
715 }
716 }
717 }
719 static void
720 resizemouse(Client *c) {
721 int ocx, ocy;
722 int nw, nh;
723 XEvent ev;
725 ocx = c->x;
726 ocy = c->y;
727 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
728 None, cursor[CurResize], CurrentTime) != GrabSuccess)
729 return;
730 c->ismax = False;
731 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->border - 1, c->h + c->border - 1);
732 for(;;) {
733 XMaskEvent(dpy, MOUSEMASK | ExposureMask | SubstructureRedirectMask , &ev);
734 switch(ev.type) {
735 case ButtonRelease:
736 resize(c, True);
737 XUngrabPointer(dpy, CurrentTime);
738 return;
739 case ConfigureRequest:
740 case Expose:
741 case MapRequest:
742 handler[ev.type](&ev);
743 break;
744 case MotionNotify:
745 XSync(dpy, False);
746 nw = ev.xmotion.x - ocx - 2 * c->border + 1;
747 c->w = nw > 0 ? nw : 1;
748 nh = ev.xmotion.y - ocy - 2 * c->border + 1;
749 c->h = nh > 0 ? nh : 1;
750 resize(c, True);
751 break;
752 }
753 }
754 }
756 static void
757 buttonpress(XEvent *e) {
758 int x;
759 Arg a;
760 Client *c;
761 XButtonPressedEvent *ev = &e->xbutton;
763 if(barwin == ev->window) {
764 x = 0;
765 for(a.i = 0; a.i < ntags; a.i++) {
766 x += textw(tags[a.i]);
767 if(ev->x < x) {
768 if(ev->button == Button1) {
769 toggleview();
770 }
771 return;
772 }
773 }
774 if(ev->x < x + bmw)
775 if (ev->button == Button1) {
776 togglemode(NULL);
777 }
778 }
779 else if((c = getclient(ev->window))) {
780 focus(c);
781 if(CLEANMASK(ev->state) != MODKEY)
782 return;
783 if(ev->button == Button1 && (arrange == dofloat || c->isfloat)) {
784 restack();
785 movemouse(c);
786 }
787 else if(ev->button == Button2)
788 zoom(NULL);
789 else if(ev->button == Button3 && (arrange == dofloat || c->isfloat) &&
790 !c->isfixed) {
791 restack();
792 resizemouse(c);
793 }
794 }
795 }
797 static void
798 configurerequest(XEvent *e) {
799 unsigned long newmask;
800 Client *c;
801 XConfigureRequestEvent *ev = &e->xconfigurerequest;
802 XWindowChanges wc;
804 if((c = getclient(ev->window))) {
805 c->ismax = False;
806 if(ev->value_mask & CWX)
807 c->x = ev->x;
808 if(ev->value_mask & CWY)
809 c->y = ev->y;
810 if(ev->value_mask & CWWidth)
811 c->w = ev->width;
812 if(ev->value_mask & CWHeight)
813 c->h = ev->height;
814 if(ev->value_mask & CWBorderWidth)
815 c->border = ev->border_width;
816 wc.x = c->x;
817 wc.y = c->y;
818 wc.width = c->w;
819 wc.height = c->h;
820 newmask = ev->value_mask & (~(CWSibling | CWStackMode | CWBorderWidth));
821 if(newmask)
822 XConfigureWindow(dpy, c->win, newmask, &wc);
823 else
824 configure(c);
825 XSync(dpy, False);
826 if(c->isfloat) {
827 resize(c, False);
828 if(!isvisible(c))
829 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
830 }
831 else
832 arrange();
833 }
834 else {
835 wc.x = ev->x;
836 wc.y = ev->y;
837 wc.width = ev->width;
838 wc.height = ev->height;
839 wc.border_width = ev->border_width;
840 wc.sibling = ev->above;
841 wc.stack_mode = ev->detail;
842 XConfigureWindow(dpy, ev->window, ev->value_mask, &wc);
843 XSync(dpy, False);
844 }
845 }
847 static void
848 destroynotify(XEvent *e) {
849 Client *c;
850 XDestroyWindowEvent *ev = &e->xdestroywindow;
852 if((c = getclient(ev->window)))
853 unmanage(c);
854 }
856 static void
857 enternotify(XEvent *e) {
858 Client *c;
859 XCrossingEvent *ev = &e->xcrossing;
861 if(ev->mode != NotifyNormal || ev->detail == NotifyInferior)
862 return;
863 if((c = getclient(ev->window)) && isvisible(c))
864 focus(c);
865 else if(ev->window == root) {
866 selscreen = True;
867 for(c = stack; c && !isvisible(c); c = c->snext);
868 focus(c);
869 }
870 }
872 static void
873 expose(XEvent *e) {
874 XExposeEvent *ev = &e->xexpose;
876 if(ev->count == 0) {
877 if(barwin == ev->window)
878 drawstatus();
879 }
880 }
882 static void
883 keypress(XEvent *e) {
884 static unsigned int len = sizeof key / sizeof key[0];
885 unsigned int i;
886 KeySym keysym;
887 XKeyEvent *ev = &e->xkey;
889 keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
890 for(i = 0; i < len; i++) {
891 if(keysym == key[i].keysym && CLEANMASK(key[i].mod) == CLEANMASK(ev->state)) {
892 if(key[i].func)
893 key[i].func(&key[i].arg);
894 }
895 }
896 }
898 static void
899 leavenotify(XEvent *e) {
900 XCrossingEvent *ev = &e->xcrossing;
902 if((ev->window == root) && !ev->same_screen) {
903 selscreen = False;
904 focus(NULL);
905 }
906 }
908 static void
909 mappingnotify(XEvent *e) {
910 XMappingEvent *ev = &e->xmapping;
912 XRefreshKeyboardMapping(ev);
913 if(ev->request == MappingKeyboard)
914 grabkeys();
915 }
917 static void
918 maprequest(XEvent *e) {
919 static XWindowAttributes wa;
920 XMapRequestEvent *ev = &e->xmaprequest;
922 if(!XGetWindowAttributes(dpy, ev->window, &wa))
923 return;
924 if(wa.override_redirect) {
925 XSelectInput(dpy, ev->window,
926 (StructureNotifyMask | PropertyChangeMask));
927 return;
928 }
929 if(!getclient(ev->window))
930 manage(ev->window, &wa);
931 }
933 static void
934 propertynotify(XEvent *e) {
935 Client *c;
936 Window trans;
937 XPropertyEvent *ev = &e->xproperty;
939 if(ev->state == PropertyDelete)
940 return; /* ignore */
941 if((c = getclient(ev->window))) {
942 switch (ev->atom) {
943 default: break;
944 case XA_WM_TRANSIENT_FOR:
945 XGetTransientForHint(dpy, c->win, &trans);
946 if(!c->isfloat && (c->isfloat = (trans != 0)))
947 arrange();
948 break;
949 case XA_WM_NORMAL_HINTS:
950 updatesizehints(c);
951 break;
952 }
953 if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
954 updatetitle(c);
955 if(c == sel)
956 drawstatus();
957 }
958 }
959 }
961 static void
962 unmapnotify(XEvent *e) {
963 Client *c;
964 XUnmapEvent *ev = &e->xunmap;
966 if((c = getclient(ev->window)))
967 unmanage(c);
968 }
972 void (*handler[LASTEvent]) (XEvent *) = {
973 [ButtonPress] = buttonpress,
974 [ConfigureRequest] = configurerequest,
975 [DestroyNotify] = destroynotify,
976 [EnterNotify] = enternotify,
977 [LeaveNotify] = leavenotify,
978 [Expose] = expose,
979 [KeyPress] = keypress,
980 [MappingNotify] = mappingnotify,
981 [MapRequest] = maprequest,
982 [PropertyNotify] = propertynotify,
983 [UnmapNotify] = unmapnotify
984 };
986 void
987 grabkeys(void) {
988 static unsigned int len = sizeof key / sizeof key[0];
989 unsigned int i;
990 KeyCode code;
992 XUngrabKey(dpy, AnyKey, AnyModifier, root);
993 for(i = 0; i < len; i++) {
994 code = XKeysymToKeycode(dpy, key[i].keysym);
995 XGrabKey(dpy, code, key[i].mod, root, True,
996 GrabModeAsync, GrabModeAsync);
997 XGrabKey(dpy, code, key[i].mod | LockMask, root, True,
998 GrabModeAsync, GrabModeAsync);
999 XGrabKey(dpy, code, key[i].mod | numlockmask, root, True,
1000 GrabModeAsync, GrabModeAsync);
1001 XGrabKey(dpy, code, key[i].mod | numlockmask | LockMask, root, True,
1002 GrabModeAsync, GrabModeAsync);
1003 }
1004 }
1006 void
1007 procevent(void) {
1008 XEvent ev;
1010 while(XPending(dpy)) {
1011 XNextEvent(dpy, &ev);
1012 if(handler[ev.type])
1013 (handler[ev.type])(&ev); /* call handler */
1014 }
1015 }
1031 /* from draw.c */
1032 /* static */
1034 static unsigned int
1035 textnw(const char *text, unsigned int len) {
1036 XRectangle r;
1038 if(dc.font.set) {
1039 XmbTextExtents(dc.font.set, text, len, NULL, &r);
1040 return r.width;
1041 }
1042 return XTextWidth(dc.font.xfont, text, len);
1043 }
1045 static void
1046 drawtext(const char *text, unsigned long col[ColLast]) {
1047 int x, y, w, h;
1048 static char buf[256];
1049 unsigned int len, olen;
1050 XGCValues gcv;
1051 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
1053 XSetForeground(dpy, dc.gc, col[ColBG]);
1054 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
1055 if(!text)
1056 return;
1057 w = 0;
1058 olen = len = strlen(text);
1059 if(len >= sizeof buf)
1060 len = sizeof buf - 1;
1061 memcpy(buf, text, len);
1062 buf[len] = 0;
1063 h = dc.font.ascent + dc.font.descent;
1064 y = dc.y + (dc.h / 2) - (h / 2) + dc.font.ascent;
1065 x = dc.x + (h / 2);
1066 /* shorten text if necessary */
1067 while(len && (w = textnw(buf, len)) > dc.w - h)
1068 buf[--len] = 0;
1069 if(len < olen) {
1070 if(len > 1)
1071 buf[len - 1] = '.';
1072 if(len > 2)
1073 buf[len - 2] = '.';
1074 if(len > 3)
1075 buf[len - 3] = '.';
1076 }
1077 if(w > dc.w)
1078 return; /* too long */
1079 gcv.foreground = col[ColFG];
1080 if(dc.font.set) {
1081 XChangeGC(dpy, dc.gc, GCForeground, &gcv);
1082 XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
1083 } else {
1084 gcv.font = dc.font.xfont->fid;
1085 XChangeGC(dpy, dc.gc, GCForeground | GCFont, &gcv);
1086 XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
1087 }
1088 }
1092 void
1093 drawstatus(void) {
1094 int x;
1095 unsigned int i;
1097 dc.x = dc.y = 0;
1098 for(i = 0; i < ntags; i++) {
1099 dc.w = textw(tags[i]);
1100 drawtext(tags[i], ( ((i == 0 && seltag) || (i == 1 && !seltag)) ? dc.sel : dc.norm));
1101 dc.x += dc.w + 1;
1102 }
1103 dc.w = bmw;
1104 drawtext("", dc.norm);
1105 x = dc.x + dc.w;
1106 dc.w = textw(stext);
1107 dc.x = sw - dc.w;
1108 if(dc.x < x) {
1109 dc.x = x;
1110 dc.w = sw - x;
1111 }
1112 drawtext(stext, dc.norm);
1113 if((dc.w = dc.x - x) > bh) {
1114 dc.x = x;
1115 drawtext(sel ? sel->name : NULL, dc.norm);
1116 }
1117 XCopyArea(dpy, dc.drawable, barwin, dc.gc, 0, 0, sw, bh, 0, 0);
1118 XSync(dpy, False);
1119 }
1121 unsigned long
1122 getcolor(const char *colstr) {
1123 Colormap cmap = DefaultColormap(dpy, screen);
1124 XColor color;
1126 if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
1127 eprint("error, cannot allocate color '%s'\n", colstr);
1128 return color.pixel;
1129 }
1131 void
1132 setfont(const char *fontstr) {
1133 char *def, **missing;
1134 int i, n;
1136 missing = NULL;
1137 if(dc.font.set)
1138 XFreeFontSet(dpy, dc.font.set);
1139 dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
1140 if(missing) {
1141 while(n--)
1142 fprintf(stderr, "missing fontset: %s\n", missing[n]);
1143 XFreeStringList(missing);
1144 }
1145 if(dc.font.set) {
1146 XFontSetExtents *font_extents;
1147 XFontStruct **xfonts;
1148 char **font_names;
1149 dc.font.ascent = dc.font.descent = 0;
1150 font_extents = XExtentsOfFontSet(dc.font.set);
1151 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
1152 for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
1153 if(dc.font.ascent < (*xfonts)->ascent)
1154 dc.font.ascent = (*xfonts)->ascent;
1155 if(dc.font.descent < (*xfonts)->descent)
1156 dc.font.descent = (*xfonts)->descent;
1157 xfonts++;
1158 }
1159 } else {
1160 if(dc.font.xfont)
1161 XFreeFont(dpy, dc.font.xfont);
1162 dc.font.xfont = NULL;
1163 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr)))
1164 eprint("error, cannot load font: '%s'\n", fontstr);
1165 dc.font.ascent = dc.font.xfont->ascent;
1166 dc.font.descent = dc.font.xfont->descent;
1167 }
1168 dc.font.height = dc.font.ascent + dc.font.descent;
1169 }
1171 unsigned int
1172 textw(const char *text) {
1173 return textnw(text, strlen(text)) + dc.font.height;
1174 }
1186 /* from client.c */
1187 /* static */
1189 static void
1190 detachstack(Client *c) {
1191 Client **tc;
1192 for(tc=&stack; *tc && *tc != c; tc=&(*tc)->snext);
1193 *tc = c->snext;
1194 }
1196 static void
1197 grabbuttons(Client *c, Bool focused) {
1198 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1200 if(focused) {
1201 XGrabButton(dpy, Button1, MODKEY, c->win, False, BUTTONMASK,
1202 GrabModeAsync, GrabModeSync, None, None);
1203 XGrabButton(dpy, Button1, MODKEY | LockMask, c->win, False, BUTTONMASK,
1204 GrabModeAsync, GrabModeSync, None, None);
1205 XGrabButton(dpy, Button1, MODKEY | numlockmask, c->win, False, BUTTONMASK,
1206 GrabModeAsync, GrabModeSync, None, None);
1207 XGrabButton(dpy, Button1, MODKEY | numlockmask | LockMask, c->win, False, BUTTONMASK,
1208 GrabModeAsync, GrabModeSync, None, None);
1210 XGrabButton(dpy, Button2, MODKEY, c->win, False, BUTTONMASK,
1211 GrabModeAsync, GrabModeSync, None, None);
1212 XGrabButton(dpy, Button2, MODKEY | LockMask, c->win, False, BUTTONMASK,
1213 GrabModeAsync, GrabModeSync, None, None);
1214 XGrabButton(dpy, Button2, MODKEY | numlockmask, c->win, False, BUTTONMASK,
1215 GrabModeAsync, GrabModeSync, None, None);
1216 XGrabButton(dpy, Button2, MODKEY | numlockmask | LockMask, c->win, False, BUTTONMASK,
1217 GrabModeAsync, GrabModeSync, None, None);
1219 XGrabButton(dpy, Button3, MODKEY, c->win, False, BUTTONMASK,
1220 GrabModeAsync, GrabModeSync, None, None);
1221 XGrabButton(dpy, Button3, MODKEY | LockMask, c->win, False, BUTTONMASK,
1222 GrabModeAsync, GrabModeSync, None, None);
1223 XGrabButton(dpy, Button3, MODKEY | numlockmask, c->win, False, BUTTONMASK,
1224 GrabModeAsync, GrabModeSync, None, None);
1225 XGrabButton(dpy, Button3, MODKEY | numlockmask | LockMask, c->win, False, BUTTONMASK,
1226 GrabModeAsync, GrabModeSync, None, None);
1227 } else {
1228 XGrabButton(dpy, AnyButton, AnyModifier, c->win, False, BUTTONMASK,
1229 GrabModeAsync, GrabModeSync, None, None);
1230 }
1231 }
1233 static void
1234 setclientstate(Client *c, long state) {
1235 long data[] = {state, None};
1236 XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1237 PropModeReplace, (unsigned char *)data, 2);
1238 }
1240 static int
1241 xerrordummy(Display *dsply, XErrorEvent *ee) {
1242 return 0;
1243 }
1247 void
1248 configure(Client *c) {
1249 XEvent synev;
1251 synev.type = ConfigureNotify;
1252 synev.xconfigure.display = dpy;
1253 synev.xconfigure.event = c->win;
1254 synev.xconfigure.window = c->win;
1255 synev.xconfigure.x = c->x;
1256 synev.xconfigure.y = c->y;
1257 synev.xconfigure.width = c->w;
1258 synev.xconfigure.height = c->h;
1259 synev.xconfigure.border_width = c->border;
1260 synev.xconfigure.above = None;
1261 XSendEvent(dpy, c->win, True, NoEventMask, &synev);
1262 }
1264 void
1265 focus(Client *c) {
1266 if(c && !isvisible(c))
1267 return;
1268 if(sel && sel != c) {
1269 grabbuttons(sel, False);
1270 XSetWindowBorder(dpy, sel->win, dc.norm[ColBorder]);
1271 }
1272 if(c) {
1273 detachstack(c);
1274 c->snext = stack;
1275 stack = c;
1276 grabbuttons(c, True);
1277 }
1278 sel = c;
1279 drawstatus();
1280 if(!selscreen)
1281 return;
1282 if(c) {
1283 XSetWindowBorder(dpy, c->win, dc.sel[ColBorder]);
1284 XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
1285 } else {
1286 XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
1287 }
1288 }
1290 Client *
1291 getclient(Window w) {
1292 Client *c;
1294 for(c = clients; c; c = c->next) {
1295 if(c->win == w) {
1296 return c;
1297 }
1298 }
1299 return NULL;
1300 }
1302 Bool
1303 isprotodel(Client *c) {
1304 int i, n;
1305 Atom *protocols;
1306 Bool ret = False;
1308 if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
1309 for(i = 0; !ret && i < n; i++)
1310 if(protocols[i] == wmatom[WMDelete])
1311 ret = True;
1312 XFree(protocols);
1313 }
1314 return ret;
1315 }
1317 void
1318 killclient() {
1319 if(!sel)
1320 return;
1321 if(isprotodel(sel))
1322 sendevent(sel->win, wmatom[WMProtocols], wmatom[WMDelete]);
1323 else
1324 XKillClient(dpy, sel->win);
1325 }
1327 void
1328 manage(Window w, XWindowAttributes *wa) {
1329 Client *c;
1330 Window trans;
1332 c = emallocz(sizeof(Client));
1333 c->tag = True;
1334 c->win = w;
1335 c->x = wa->x;
1336 c->y = wa->y;
1337 c->w = wa->width;
1338 c->h = wa->height;
1339 if(c->w == sw && c->h == sh) {
1340 c->border = 0;
1341 c->x = sx;
1342 c->y = sy;
1343 } else {
1344 c->border = BORDERPX;
1345 if(c->x + c->w + 2 * c->border > wax + waw)
1346 c->x = wax + waw - c->w - 2 * c->border;
1347 if(c->y + c->h + 2 * c->border > way + wah)
1348 c->y = way + wah - c->h - 2 * c->border;
1349 if(c->x < wax)
1350 c->x = wax;
1351 if(c->y < way)
1352 c->y = way;
1353 }
1354 updatesizehints(c);
1355 XSelectInput(dpy, c->win,
1356 StructureNotifyMask | PropertyChangeMask | EnterWindowMask);
1357 XGetTransientForHint(dpy, c->win, &trans);
1358 grabbuttons(c, False);
1359 XSetWindowBorder(dpy, c->win, dc.norm[ColBorder]);
1360 updatetitle(c);
1361 settags(c, getclient(trans));
1362 if(!c->isfloat)
1363 c->isfloat = trans || c->isfixed;
1364 if(clients)
1365 clients->prev = c;
1366 c->next = clients;
1367 c->snext = stack;
1368 stack = clients = c;
1369 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
1370 XMapWindow(dpy, c->win);
1371 setclientstate(c, NormalState);
1372 if(isvisible(c))
1373 focus(c);
1374 arrange();
1375 }
1377 void
1378 resize(Client *c, Bool sizehints) {
1379 float actual, dx, dy, max, min;
1380 XWindowChanges wc;
1382 if(c->w <= 0 || c->h <= 0)
1383 return;
1384 if(sizehints) {
1385 if(c->minw && c->w < c->minw)
1386 c->w = c->minw;
1387 if(c->minh && c->h < c->minh)
1388 c->h = c->minh;
1389 if(c->maxw && c->w > c->maxw)
1390 c->w = c->maxw;
1391 if(c->maxh && c->h > c->maxh)
1392 c->h = c->maxh;
1393 /* inspired by algorithm from fluxbox */
1394 if(c->minay > 0 && c->maxay && (c->h - c->baseh) > 0) {
1395 dx = (float)(c->w - c->basew);
1396 dy = (float)(c->h - c->baseh);
1397 min = (float)(c->minax) / (float)(c->minay);
1398 max = (float)(c->maxax) / (float)(c->maxay);
1399 actual = dx / dy;
1400 if(max > 0 && min > 0 && actual > 0) {
1401 if(actual < min) {
1402 dy = (dx * min + dy) / (min * min + 1);
1403 dx = dy * min;
1404 c->w = (int)dx + c->basew;
1405 c->h = (int)dy + c->baseh;
1406 }
1407 else if(actual > max) {
1408 dy = (dx * min + dy) / (max * max + 1);
1409 dx = dy * min;
1410 c->w = (int)dx + c->basew;
1411 c->h = (int)dy + c->baseh;
1412 }
1413 }
1414 }
1415 if(c->incw)
1416 c->w -= (c->w - c->basew) % c->incw;
1417 if(c->inch)
1418 c->h -= (c->h - c->baseh) % c->inch;
1419 }
1420 if(c->w == sw && c->h == sh)
1421 c->border = 0;
1422 else
1423 c->border = BORDERPX;
1424 /* offscreen appearance fixes */
1425 if(c->x > sw)
1426 c->x = sw - c->w - 2 * c->border;
1427 if(c->y > sh)
1428 c->y = sh - c->h - 2 * c->border;
1429 if(c->x + c->w + 2 * c->border < sx)
1430 c->x = sx;
1431 if(c->y + c->h + 2 * c->border < sy)
1432 c->y = sy;
1433 wc.x = c->x;
1434 wc.y = c->y;
1435 wc.width = c->w;
1436 wc.height = c->h;
1437 wc.border_width = c->border;
1438 XConfigureWindow(dpy, c->win, CWX | CWY | CWWidth | CWHeight | CWBorderWidth, &wc);
1439 configure(c);
1440 XSync(dpy, False);
1441 }
1443 void
1444 updatesizehints(Client *c) {
1445 long msize;
1446 XSizeHints size;
1448 if(!XGetWMNormalHints(dpy, c->win, &size, &msize) || !size.flags)
1449 size.flags = PSize;
1450 c->flags = size.flags;
1451 if(c->flags & PBaseSize) {
1452 c->basew = size.base_width;
1453 c->baseh = size.base_height;
1454 } else {
1455 c->basew = c->baseh = 0;
1456 }
1457 if(c->flags & PResizeInc) {
1458 c->incw = size.width_inc;
1459 c->inch = size.height_inc;
1460 } else {
1461 c->incw = c->inch = 0;
1462 }
1463 if(c->flags & PMaxSize) {
1464 c->maxw = size.max_width;
1465 c->maxh = size.max_height;
1466 } else {
1467 c->maxw = c->maxh = 0;
1468 }
1469 if(c->flags & PMinSize) {
1470 c->minw = size.min_width;
1471 c->minh = size.min_height;
1472 } else {
1473 c->minw = c->minh = 0;
1474 }
1475 if(c->flags & PAspect) {
1476 c->minax = size.min_aspect.x;
1477 c->minay = size.min_aspect.y;
1478 c->maxax = size.max_aspect.x;
1479 c->maxay = size.max_aspect.y;
1480 } else {
1481 c->minax = c->minay = c->maxax = c->maxay = 0;
1482 }
1483 c->isfixed = (c->maxw && c->minw && c->maxh && c->minh &&
1484 c->maxw == c->minw && c->maxh == c->minh);
1485 }
1487 void
1488 updatetitle(Client *c) {
1489 char **list = NULL;
1490 int n;
1491 XTextProperty name;
1493 name.nitems = 0;
1494 c->name[0] = 0;
1495 XGetTextProperty(dpy, c->win, &name, netatom[NetWMName]);
1496 if(!name.nitems)
1497 XGetWMName(dpy, c->win, &name);
1498 if(!name.nitems)
1499 return;
1500 if(name.encoding == XA_STRING)
1501 strncpy(c->name, (char *)name.value, sizeof c->name);
1502 else {
1503 if(XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success && n > 0 && *list) {
1504 strncpy(c->name, *list, sizeof c->name);
1505 XFreeStringList(list);
1506 }
1507 }
1508 XFree(name.value);
1509 }
1511 void
1512 unmanage(Client *c) {
1513 Client *nc;
1515 /* The server grab construct avoids race conditions. */
1516 XGrabServer(dpy);
1517 XSetErrorHandler(xerrordummy);
1518 detach(c);
1519 detachstack(c);
1520 if(sel == c) {
1521 for(nc = stack; nc && !isvisible(nc); nc = nc->snext);
1522 focus(nc);
1523 }
1524 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1525 setclientstate(c, WithdrawnState);
1526 free(c);
1527 XSync(dpy, False);
1528 XSetErrorHandler(xerror);
1529 XUngrabServer(dpy);
1530 arrange();
1531 }
1551 /* static */
1554 static void
1555 cleanup(void) {
1556 close(STDIN_FILENO);
1557 while(stack) {
1558 resize(stack, True);
1559 unmanage(stack);
1560 }
1561 if(dc.font.set)
1562 XFreeFontSet(dpy, dc.font.set);
1563 else
1564 XFreeFont(dpy, dc.font.xfont);
1565 XUngrabKey(dpy, AnyKey, AnyModifier, root);
1566 XFreePixmap(dpy, dc.drawable);
1567 XFreeGC(dpy, dc.gc);
1568 XDestroyWindow(dpy, barwin);
1569 XFreeCursor(dpy, cursor[CurNormal]);
1570 XFreeCursor(dpy, cursor[CurResize]);
1571 XFreeCursor(dpy, cursor[CurMove]);
1572 XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime);
1573 XSync(dpy, False);
1574 }
1576 static void
1577 scan(void) {
1578 unsigned int i, num;
1579 Window *wins, d1, d2;
1580 XWindowAttributes wa;
1582 wins = NULL;
1583 if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1584 for(i = 0; i < num; i++) {
1585 if(!XGetWindowAttributes(dpy, wins[i], &wa))
1586 continue;
1587 if(wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1588 continue;
1589 if(wa.map_state == IsViewable)
1590 manage(wins[i], &wa);
1591 }
1592 }
1593 if(wins)
1594 XFree(wins);
1595 }
1597 static void
1598 setup(void) {
1599 int i, j;
1600 unsigned int mask;
1601 Window w;
1602 XModifierKeymap *modmap;
1603 XSetWindowAttributes wa;
1605 /* init atoms */
1606 wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1607 wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1608 wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1609 netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1610 netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1611 XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1612 PropModeReplace, (unsigned char *) netatom, NetLast);
1613 /* init cursors */
1614 cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1615 cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1616 cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1617 /* init modifier map */
1618 numlockmask = 0;
1619 modmap = XGetModifierMapping(dpy);
1620 for (i = 0; i < 8; i++) {
1621 for (j = 0; j < modmap->max_keypermod; j++) {
1622 if(modmap->modifiermap[i * modmap->max_keypermod + j] == XKeysymToKeycode(dpy, XK_Num_Lock))
1623 numlockmask = (1 << i);
1624 }
1625 }
1626 XFreeModifiermap(modmap);
1627 /* select for events */
1628 wa.event_mask = SubstructureRedirectMask | SubstructureNotifyMask
1629 | EnterWindowMask | LeaveWindowMask;
1630 wa.cursor = cursor[CurNormal];
1631 XChangeWindowAttributes(dpy, root, CWEventMask | CWCursor, &wa);
1632 grabkeys();
1633 initrregs();
1634 ntags = 2;
1635 seltag = True;
1636 /* style */
1637 dc.norm[ColBorder] = getcolor(NORMBORDERCOLOR);
1638 dc.norm[ColBG] = getcolor(NORMBGCOLOR);
1639 dc.norm[ColFG] = getcolor(NORMFGCOLOR);
1640 dc.sel[ColBorder] = getcolor(SELBORDERCOLOR);
1641 dc.sel[ColBG] = getcolor(SELBGCOLOR);
1642 dc.sel[ColFG] = getcolor(SELFGCOLOR);
1643 setfont(FONT);
1644 /* geometry */
1645 sx = sy = 0;
1646 sw = DisplayWidth(dpy, screen);
1647 sh = DisplayHeight(dpy, screen);
1648 nmaster = NMASTER;
1649 bmw = 1;
1650 /* bar */
1651 dc.h = bh = dc.font.height + 2;
1652 wa.override_redirect = 1;
1653 wa.background_pixmap = ParentRelative;
1654 wa.event_mask = ButtonPressMask | ExposureMask;
1655 barwin = XCreateWindow(dpy, root, sx, sy, sw, bh, 0,
1656 DefaultDepth(dpy, screen), CopyFromParent, DefaultVisual(dpy, screen),
1657 CWOverrideRedirect | CWBackPixmap | CWEventMask, &wa);
1658 XDefineCursor(dpy, barwin, cursor[CurNormal]);
1659 XMapRaised(dpy, barwin);
1660 strcpy(stext, "dwm-"VERSION);
1661 /* windowarea */
1662 wax = sx;
1663 way = sy + bh;
1664 wah = sh - bh;
1665 waw = sw;
1666 /* pixmap for everything */
1667 dc.drawable = XCreatePixmap(dpy, root, sw, bh, DefaultDepth(dpy, screen));
1668 dc.gc = XCreateGC(dpy, root, 0, 0);
1669 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
1670 /* multihead support */
1671 selscreen = XQueryPointer(dpy, root, &w, &w, &i, &i, &i, &i, &mask);
1672 }
1674 /*
1675 * Startup Error handler to check if another window manager
1676 * is already running.
1677 */
1678 static int
1679 xerrorstart(Display *dsply, XErrorEvent *ee) {
1680 otherwm = True;
1681 return -1;
1682 }
1686 void
1687 sendevent(Window w, Atom a, long value) {
1688 XEvent e;
1690 e.type = ClientMessage;
1691 e.xclient.window = w;
1692 e.xclient.message_type = a;
1693 e.xclient.format = 32;
1694 e.xclient.data.l[0] = value;
1695 e.xclient.data.l[1] = CurrentTime;
1696 XSendEvent(dpy, w, False, NoEventMask, &e);
1697 XSync(dpy, False);
1698 }
1700 void
1701 quit() {
1702 readin = running = False;
1703 }
1705 /* There's no way to check accesses to destroyed windows, thus those cases are
1706 * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
1707 * default error handler, which may call exit.
1708 */
1709 int
1710 xerror(Display *dpy, XErrorEvent *ee) {
1711 if(ee->error_code == BadWindow
1712 || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1713 || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1714 || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1715 || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1716 || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1717 || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1718 || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1719 return 0;
1720 fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1721 ee->request_code, ee->error_code);
1722 return xerrorxlib(dpy, ee); /* may call exit */
1723 }
1725 int
1726 main(int argc, char *argv[]) {
1727 char *p;
1728 int r, xfd;
1729 fd_set rd;
1731 if(argc == 2 && !strncmp("-v", argv[1], 3)) {
1732 fputs("dwm-"VERSION", (C)opyright MMVI-MMVII Anselm R. Garbe\n", stdout);
1733 exit(EXIT_SUCCESS);
1734 } else if(argc != 1) {
1735 eprint("usage: dwm [-v]\n");
1736 }
1737 setlocale(LC_CTYPE, "");
1738 dpy = XOpenDisplay(0);
1739 if(!dpy) {
1740 eprint("dwm: cannot open display\n");
1741 }
1742 xfd = ConnectionNumber(dpy);
1743 screen = DefaultScreen(dpy);
1744 root = RootWindow(dpy, screen);
1745 otherwm = False;
1746 XSetErrorHandler(xerrorstart);
1747 /* this causes an error if some other window manager is running */
1748 XSelectInput(dpy, root, SubstructureRedirectMask);
1749 XSync(dpy, False);
1750 if(otherwm) {
1751 eprint("dwm: another window manager is already running\n");
1752 }
1754 XSync(dpy, False);
1755 XSetErrorHandler(NULL);
1756 xerrorxlib = XSetErrorHandler(xerror);
1757 XSync(dpy, False);
1758 setup();
1759 drawstatus();
1760 scan();
1762 /* main event loop, also reads status text from stdin */
1763 XSync(dpy, False);
1764 procevent();
1765 readin = True;
1766 while(running) {
1767 FD_ZERO(&rd);
1768 if(readin)
1769 FD_SET(STDIN_FILENO, &rd);
1770 FD_SET(xfd, &rd);
1771 if(select(xfd + 1, &rd, NULL, NULL, NULL) == -1) {
1772 if(errno == EINTR)
1773 continue;
1774 eprint("select failed\n");
1775 }
1776 if(FD_ISSET(STDIN_FILENO, &rd)) {
1777 switch(r = read(STDIN_FILENO, stext, sizeof stext - 1)) {
1778 case -1:
1779 strncpy(stext, strerror(errno), sizeof stext - 1);
1780 stext[sizeof stext - 1] = '\0';
1781 readin = False;
1782 break;
1783 case 0:
1784 strncpy(stext, "EOF", 4);
1785 readin = False;
1786 break;
1787 default:
1788 for(stext[r] = '\0', p = stext + strlen(stext) - 1; p >= stext && *p == '\n'; *p-- = '\0');
1789 for(; p >= stext && *p != '\n'; --p);
1790 if(p > stext)
1791 strncpy(stext, p + 1, sizeof stext);
1792 }
1793 drawstatus();
1794 }
1795 if(FD_ISSET(xfd, &rd))
1796 procevent();
1797 }
1798 cleanup();
1799 XCloseDisplay(dpy);
1800 return 0;
1801 }