aewl
view dwm.c @ 758:bc512840e5a5
removed union arg (using const char* cmd now)
whole bar toggles view if clicked now
author | meillo@marmaro.de |
---|---|
date | Fri, 30 May 2008 21:57:51 +0200 |
parents | bff1012527b3 |
children |
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 struct {
62 int ascent;
63 int descent;
64 int height;
65 XFontSet set;
66 XFontStruct *xfont;
67 } Fnt;
69 typedef struct {
70 int x, y, w, h;
71 unsigned long norm[ColLast];
72 unsigned long sel[ColLast];
73 Drawable drawable;
74 Fnt font;
75 GC gc;
76 } DC; /* draw context */
78 typedef struct Client Client;
79 struct Client {
80 char name[256];
81 int x, y, w, h;
82 int rx, ry, rw, rh; /* revert geometry */
83 int basew, baseh, incw, inch, maxw, maxh, minw, minh;
84 int minax, minay, maxax, maxay;
85 long flags;
86 unsigned int border;
87 Bool isfixed, isfloat, ismax;
88 Bool tag;
89 Client *next;
90 Client *prev;
91 Client *snext;
92 Window win;
93 };
95 typedef struct {
96 const char *clpattern;
97 int tag;
98 Bool isfloat;
99 } Rule;
101 typedef struct {
102 regex_t *clregex;
103 } RReg;
106 typedef struct {
107 unsigned long mod;
108 KeySym keysym;
109 void (*func)(const char* cmd);
110 const char* cmd;
111 } Key;
114 #define CLEANMASK(mask) (mask & ~(numlockmask | LockMask))
115 #define MOUSEMASK (BUTTONMASK | PointerMotionMask)
119 const char *tags[]; /* all tags */
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 ntags, numlockmask; /* number of tags, 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; /* seltag is array of Bool */
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 TAGS
150 RULES
153 /* client.c */
154 void configure(Client *c); /* send synthetic configure event */
155 void focus(Client *c); /* focus c, c may be NULL */
156 Client *getclient(Window w); /* return client of w */
157 Bool isprotodel(Client *c); /* returns True if c->win supports wmatom[WMDelete] */
158 void manage(Window w, XWindowAttributes *wa); /* manage new client */
159 void resize(Client *c, Bool sizehints); /* resize c*/
160 void updatesizehints(Client *c); /* update the size hint variables of c */
161 void updatetitle(Client *c); /* update the name of c */
162 void unmanage(Client *c); /* destroy c */
164 /* draw.c */
165 void drawstatus(void); /* draw the bar */
166 unsigned long getcolor(const char *colstr); /* return color of colstr */
167 void setfont(const char *fontstr); /* set the font for DC */
168 unsigned int textw(const char *text); /* return the width of text in px*/
170 /* event.c */
171 void grabkeys(void); /* grab all keys defined in config.h */
172 void procevent(void); /* process pending X events */
174 /* main.c */
175 void sendevent(Window w, Atom a, long value); /* send synthetic event to w */
176 int xerror(Display *dsply, XErrorEvent *ee); /* dwm's X error handler */
178 /* tag.c */
179 void initrregs(void); /* initialize regexps of rules defined in config.h */
180 Client *getnext(Client *c); /* returns next visible client */
181 void settags(Client *c, Client *trans); /* sets tags of c */
183 /* util.c */
184 void *emallocz(unsigned int size); /* allocates zero-initialized memory, exits on error */
185 void eprint(const char *errstr, ...); /* prints errstr and exits with 1 */
187 /* view.c */
188 void detach(Client *c); /* detaches c from global client list */
189 void dofloat(void); /* arranges all windows floating */
190 void dotile(void); /* arranges all windows tiled */
191 void domax(void); /* arranges all windows fullscreen */
192 Bool isvisible(Client *c); /* returns True if client is visible */
193 void restack(void); /* restores z layers of all clients */
196 void toggleview(); /* toggle the viewed tag */
197 void focusnext(); /* focuses next visible client */
198 void zoom(); /* zooms the focused client to master area */
199 void killclient(); /* kill c nicely */
200 void quit(); /* quit dwm nicely */
201 void togglemode(); /* toggles global arrange function (dotile/dofloat) */
202 void togglefloat(); /* toggles focusesd client between floating/non-floating state */
203 void incnmaster(); /* increments nmaster */
204 void decnmaster(); /* decrements nmaster */
205 void toggletag(); /* toggles c tag */
206 void spawn(const char* cmd); /* forks a new subprocess with cmd */
217 /* from view.c */
218 /* static */
220 static Client *
221 nexttiled(Client *c) {
222 for(c = getnext(c); c && c->isfloat; c = getnext(c->next));
223 return c;
224 }
226 static void
227 togglemax(Client *c) {
228 XEvent ev;
230 if(c->isfixed)
231 return;
233 if((c->ismax = !c->ismax)) {
234 c->rx = c->x; c->x = wax;
235 c->ry = c->y; c->y = way;
236 c->rw = c->w; c->w = waw - 2 * BORDERPX;
237 c->rh = c->h; c->h = wah - 2 * BORDERPX;
238 }
239 else {
240 c->x = c->rx;
241 c->y = c->ry;
242 c->w = c->rw;
243 c->h = c->rh;
244 }
245 resize(c, True);
246 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
247 }
251 void (*arrange)(void) = DEFMODE;
253 void
254 detach(Client *c) {
255 if(c->prev)
256 c->prev->next = c->next;
257 if(c->next)
258 c->next->prev = c->prev;
259 if(c == clients)
260 clients = c->next;
261 c->next = c->prev = NULL;
262 }
264 void
265 dofloat(void) {
266 Client *c;
268 for(c = clients; c; c = c->next) {
269 if(isvisible(c)) {
270 resize(c, True);
271 }
272 else
273 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
274 }
275 if(!sel || !isvisible(sel)) {
276 for(c = stack; c && !isvisible(c); c = c->snext);
277 focus(c);
278 }
279 restack();
280 }
282 void
283 dotile(void) {
284 unsigned int i, n, mw, mh, tw, th;
285 Client *c;
287 for(n = 0, c = nexttiled(clients); c; c = nexttiled(c->next))
288 n++;
289 /* window geoms */
290 mh = (n > nmaster) ? wah / nmaster : wah / (n > 0 ? n : 1);
291 mw = (n > nmaster) ? waw / 2 : waw;
292 th = (n > nmaster) ? wah / (n - nmaster) : 0;
293 tw = waw - mw;
295 for(i = 0, c = clients; c; c = c->next)
296 if(isvisible(c)) {
297 if(c->isfloat) {
298 resize(c, True);
299 continue;
300 }
301 c->ismax = False;
302 c->x = wax;
303 c->y = way;
304 if(i < nmaster) {
305 c->y += i * mh;
306 c->w = mw - 2 * BORDERPX;
307 c->h = mh - 2 * BORDERPX;
308 }
309 else { /* tile window */
310 c->x += mw;
311 c->w = tw - 2 * BORDERPX;
312 if(th > 2 * BORDERPX) {
313 c->y += (i - nmaster) * th;
314 c->h = th - 2 * BORDERPX;
315 }
316 else /* fallback if th <= 2 * BORDERPX */
317 c->h = wah - 2 * BORDERPX;
318 }
319 resize(c, False);
320 i++;
321 }
322 else
323 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
324 if(!sel || !isvisible(sel)) {
325 for(c = stack; c && !isvisible(c); c = c->snext);
326 focus(c);
327 }
328 restack();
329 }
331 /* begin code by mitch */
332 void
333 arrangemax(Client *c) {
334 if(c == sel) {
335 c->ismax = True;
336 c->x = sx;
337 c->y = bh;
338 c->w = sw - 2 * BORDERPX;
339 c->h = sh - bh - 2 * BORDERPX;
340 XRaiseWindow(dpy, c->win);
341 } else {
342 c->ismax = False;
343 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
344 XLowerWindow(dpy, c->win);
345 }
346 }
348 void
349 domax(void) {
350 Client *c;
352 for(c = clients; c; c = c->next) {
353 if(isvisible(c)) {
354 if(c->isfloat) {
355 resize(c, True);
356 continue;
357 }
358 arrangemax(c);
359 resize(c, False);
360 } else {
361 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
362 }
364 }
365 if(!sel || !isvisible(sel)) {
366 for(c = stack; c && !isvisible(c); c = c->snext);
367 focus(c);
368 }
369 restack();
370 }
371 /* end code by mitch */
373 void
374 focusnext() {
375 Client *c;
377 if(!sel)
378 return;
379 if(!(c = getnext(sel->next)))
380 c = getnext(clients);
381 if(c) {
382 focus(c);
383 restack();
384 }
385 }
387 void
388 incnmaster() {
389 if((arrange == dofloat) || (wah / (nmaster + 1) <= 2 * BORDERPX))
390 return;
391 nmaster++;
392 if(sel)
393 arrange();
394 else
395 drawstatus();
396 }
398 void
399 decnmaster() {
400 if((arrange == dofloat) || (nmaster <= 1))
401 return;
402 nmaster--;
403 if(sel)
404 arrange();
405 else
406 drawstatus();
407 }
409 Bool
410 isvisible(Client *c) {
411 if((c->tag && seltag) || (!c->tag && !seltag)) {
412 return True;
413 }
414 return False;
415 }
417 void
418 restack(void) {
419 Client *c;
420 XEvent ev;
422 drawstatus();
423 if(!sel)
424 return;
425 if(sel->isfloat || arrange == dofloat)
426 XRaiseWindow(dpy, sel->win);
428 /* begin code by mitch */
429 if(arrange == domax) {
430 for(c = nexttiled(clients); c; c = nexttiled(c->next)) {
431 arrangemax(c);
432 resize(c, False);
433 }
435 } else if (arrange == dotile) {
436 /* end code by mitch */
438 if(!sel->isfloat)
439 XLowerWindow(dpy, sel->win);
440 for(c = nexttiled(clients); c; c = nexttiled(c->next)) {
441 if(c == sel)
442 continue;
443 XLowerWindow(dpy, c->win);
444 }
445 }
446 XSync(dpy, False);
447 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
448 }
450 void
451 togglefloat() {
452 if (!sel || arrange == dofloat)
453 return;
454 sel->isfloat = !sel->isfloat;
455 arrange();
456 }
458 void
459 togglemode() {
460 /* only toggle between tile and max - float is just available through togglefloat */
461 arrange = (arrange == dotile) ? domax : dotile;
462 if(sel)
463 arrange();
464 else
465 drawstatus();
466 }
468 void
469 toggleview() {
470 seltag = !seltag;
471 arrange();
472 }
474 void
475 zoom() {
476 unsigned int n;
477 Client *c;
479 if(!sel)
480 return;
481 if(sel->isfloat || (arrange == dofloat)) {
482 togglemax(sel);
483 return;
484 }
485 for(n = 0, c = nexttiled(clients); c; c = nexttiled(c->next))
486 n++;
488 if((c = sel) == nexttiled(clients))
489 if(!(c = nexttiled(c->next)))
490 return;
491 detach(c);
492 if(clients)
493 clients->prev = c;
494 c->next = clients;
495 clients = c;
496 focus(c);
497 arrange();
498 }
515 /* from util.c */
518 void *
519 emallocz(unsigned int size) {
520 void *res = calloc(1, size);
522 if(!res)
523 eprint("fatal: could not malloc() %u bytes\n", size);
524 return res;
525 }
527 void
528 eprint(const char *errstr, ...) {
529 va_list ap;
531 va_start(ap, errstr);
532 vfprintf(stderr, errstr, ap);
533 va_end(ap);
534 exit(EXIT_FAILURE);
535 }
537 void
538 spawn(const char* cmd) {
539 static char *shell = NULL;
541 if(!shell && !(shell = getenv("SHELL")))
542 shell = "/bin/sh";
543 if(!cmd)
544 return;
545 /* The double-fork construct avoids zombie processes and keeps the code
546 * clean from stupid signal handlers. */
547 if(fork() == 0) {
548 if(fork() == 0) {
549 if(dpy)
550 close(ConnectionNumber(dpy));
551 setsid();
552 execl(shell, shell, "-c", cmd, (char *)NULL);
553 fprintf(stderr, "dwm: execl '%s -c %s'", shell, cmd);
554 perror(" failed");
555 }
556 exit(0);
557 }
558 wait(0);
559 }
573 /* from tag.c */
575 /* static */
577 Client *
578 getnext(Client *c) {
579 for(; c && !isvisible(c); c = c->next);
580 return c;
581 }
583 void
584 initrregs(void) {
585 unsigned int i;
586 regex_t *reg;
588 if(rreg)
589 return;
590 len = sizeof rule / sizeof rule[0];
591 rreg = emallocz(len * sizeof(RReg));
592 for(i = 0; i < len; i++) {
593 if(rule[i].clpattern) {
594 reg = emallocz(sizeof(regex_t));
595 if(regcomp(reg, rule[i].clpattern, REG_EXTENDED))
596 free(reg);
597 else
598 rreg[i].clregex = reg;
599 }
600 }
601 }
603 void
604 settags(Client *c, Client *trans) {
605 char prop[512];
606 unsigned int i;
607 regmatch_t tmp;
608 Bool matched = trans != NULL;
609 XClassHint ch = { 0 };
611 if(matched) {
612 c->tag = trans->tag;
613 } else {
614 XGetClassHint(dpy, c->win, &ch);
615 snprintf(prop, sizeof prop, "%s:%s:%s",
616 ch.res_class ? ch.res_class : "",
617 ch.res_name ? ch.res_name : "", c->name);
618 for(i = 0; i < len; i++)
619 if(rreg[i].clregex && !regexec(rreg[i].clregex, prop, 1, &tmp, 0)) {
620 c->isfloat = rule[i].isfloat;
621 if (rule[i].tag < 0) {
622 c->tag = seltag;
623 } else if (rule[i].tag == 0) {
624 c->tag = True;
625 } else {
626 c->tag = False;
627 }
628 matched = True;
629 break; /* perform only the first rule matching */
630 }
631 if(ch.res_class)
632 XFree(ch.res_class);
633 if(ch.res_name)
634 XFree(ch.res_name);
635 }
636 if(!matched) {
637 c->tag = seltag;
638 }
639 }
641 void
642 toggletag() {
643 if(!sel)
644 return;
645 sel->tag = !sel->tag;
646 toggleview();
647 }
665 /* from event.c */
666 /* static */
668 KEYS
672 static void
673 movemouse(Client *c) {
674 int x1, y1, ocx, ocy, di;
675 unsigned int dui;
676 Window dummy;
677 XEvent ev;
679 ocx = c->x;
680 ocy = c->y;
681 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
682 None, cursor[CurMove], CurrentTime) != GrabSuccess)
683 return;
684 c->ismax = False;
685 XQueryPointer(dpy, root, &dummy, &dummy, &x1, &y1, &di, &di, &dui);
686 for(;;) {
687 XMaskEvent(dpy, MOUSEMASK | ExposureMask | SubstructureRedirectMask, &ev);
688 switch (ev.type) {
689 case ButtonRelease:
690 resize(c, True);
691 XUngrabPointer(dpy, CurrentTime);
692 return;
693 case ConfigureRequest:
694 case Expose:
695 case MapRequest:
696 handler[ev.type](&ev);
697 break;
698 case MotionNotify:
699 XSync(dpy, False);
700 c->x = ocx + (ev.xmotion.x - x1);
701 c->y = ocy + (ev.xmotion.y - y1);
702 if(abs(wax + c->x) < SNAP)
703 c->x = wax;
704 else if(abs((wax + waw) - (c->x + c->w + 2 * c->border)) < SNAP)
705 c->x = wax + waw - c->w - 2 * c->border;
706 if(abs(way - c->y) < SNAP)
707 c->y = way;
708 else if(abs((way + wah) - (c->y + c->h + 2 * c->border)) < SNAP)
709 c->y = way + wah - c->h - 2 * c->border;
710 resize(c, False);
711 break;
712 }
713 }
714 }
716 static void
717 resizemouse(Client *c) {
718 int ocx, ocy;
719 int nw, nh;
720 XEvent ev;
722 ocx = c->x;
723 ocy = c->y;
724 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
725 None, cursor[CurResize], CurrentTime) != GrabSuccess)
726 return;
727 c->ismax = False;
728 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->border - 1, c->h + c->border - 1);
729 for(;;) {
730 XMaskEvent(dpy, MOUSEMASK | ExposureMask | SubstructureRedirectMask , &ev);
731 switch(ev.type) {
732 case ButtonRelease:
733 resize(c, True);
734 XUngrabPointer(dpy, CurrentTime);
735 return;
736 case ConfigureRequest:
737 case Expose:
738 case MapRequest:
739 handler[ev.type](&ev);
740 break;
741 case MotionNotify:
742 XSync(dpy, False);
743 nw = ev.xmotion.x - ocx - 2 * c->border + 1;
744 c->w = nw > 0 ? nw : 1;
745 nh = ev.xmotion.y - ocy - 2 * c->border + 1;
746 c->h = nh > 0 ? nh : 1;
747 resize(c, True);
748 break;
749 }
750 }
751 }
753 static void
754 buttonpress(XEvent *e) {
755 int x;
756 int i;
757 Client *c;
758 XButtonPressedEvent *ev = &e->xbutton;
760 if(barwin == ev->window) {
761 if(ev->button == Button1) {
762 toggleview();
763 }
764 return;
765 } else if((c = getclient(ev->window))) {
766 focus(c);
767 if(CLEANMASK(ev->state) != MODKEY)
768 return;
769 if(ev->button == Button1 && (arrange == dofloat || c->isfloat)) {
770 restack();
771 movemouse(c);
772 } else if(ev->button == Button3 && (arrange == dofloat || c->isfloat) && !c->isfixed) {
773 restack();
774 resizemouse(c);
775 }
776 }
777 }
779 static void
780 configurerequest(XEvent *e) {
781 unsigned long newmask;
782 Client *c;
783 XConfigureRequestEvent *ev = &e->xconfigurerequest;
784 XWindowChanges wc;
786 if((c = getclient(ev->window))) {
787 c->ismax = False;
788 if(ev->value_mask & CWX)
789 c->x = ev->x;
790 if(ev->value_mask & CWY)
791 c->y = ev->y;
792 if(ev->value_mask & CWWidth)
793 c->w = ev->width;
794 if(ev->value_mask & CWHeight)
795 c->h = ev->height;
796 if(ev->value_mask & CWBorderWidth)
797 c->border = ev->border_width;
798 wc.x = c->x;
799 wc.y = c->y;
800 wc.width = c->w;
801 wc.height = c->h;
802 newmask = ev->value_mask & (~(CWSibling | CWStackMode | CWBorderWidth));
803 if(newmask)
804 XConfigureWindow(dpy, c->win, newmask, &wc);
805 else
806 configure(c);
807 XSync(dpy, False);
808 if(c->isfloat) {
809 resize(c, False);
810 if(!isvisible(c))
811 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
812 }
813 else
814 arrange();
815 } else {
816 wc.x = ev->x;
817 wc.y = ev->y;
818 wc.width = ev->width;
819 wc.height = ev->height;
820 wc.border_width = ev->border_width;
821 wc.sibling = ev->above;
822 wc.stack_mode = ev->detail;
823 XConfigureWindow(dpy, ev->window, ev->value_mask, &wc);
824 XSync(dpy, False);
825 }
826 }
828 static void
829 destroynotify(XEvent *e) {
830 Client *c;
831 XDestroyWindowEvent *ev = &e->xdestroywindow;
833 if((c = getclient(ev->window)))
834 unmanage(c);
835 }
837 static void
838 enternotify(XEvent *e) {
839 Client *c;
840 XCrossingEvent *ev = &e->xcrossing;
842 if(ev->mode != NotifyNormal || ev->detail == NotifyInferior)
843 return;
844 if((c = getclient(ev->window)) && isvisible(c))
845 focus(c);
846 else if(ev->window == root) {
847 selscreen = True;
848 for(c = stack; c && !isvisible(c); c = c->snext);
849 focus(c);
850 }
851 }
853 static void
854 expose(XEvent *e) {
855 XExposeEvent *ev = &e->xexpose;
857 if(ev->count == 0) {
858 if(barwin == ev->window)
859 drawstatus();
860 }
861 }
863 static void
864 keypress(XEvent *e) {
865 static unsigned int len = sizeof key / sizeof key[0];
866 unsigned int i;
867 KeySym keysym;
868 XKeyEvent *ev = &e->xkey;
870 keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
871 for(i = 0; i < len; i++) {
872 if(keysym == key[i].keysym && CLEANMASK(key[i].mod) == CLEANMASK(ev->state)) {
873 if(key[i].func)
874 key[i].func(key[i].cmd);
875 }
876 }
877 }
879 static void
880 leavenotify(XEvent *e) {
881 XCrossingEvent *ev = &e->xcrossing;
883 if((ev->window == root) && !ev->same_screen) {
884 selscreen = False;
885 focus(NULL);
886 }
887 }
889 static void
890 mappingnotify(XEvent *e) {
891 XMappingEvent *ev = &e->xmapping;
893 XRefreshKeyboardMapping(ev);
894 if(ev->request == MappingKeyboard)
895 grabkeys();
896 }
898 static void
899 maprequest(XEvent *e) {
900 static XWindowAttributes wa;
901 XMapRequestEvent *ev = &e->xmaprequest;
903 if(!XGetWindowAttributes(dpy, ev->window, &wa))
904 return;
905 if(wa.override_redirect) {
906 XSelectInput(dpy, ev->window,
907 (StructureNotifyMask | PropertyChangeMask));
908 return;
909 }
910 if(!getclient(ev->window))
911 manage(ev->window, &wa);
912 }
914 static void
915 propertynotify(XEvent *e) {
916 Client *c;
917 Window trans;
918 XPropertyEvent *ev = &e->xproperty;
920 if(ev->state == PropertyDelete)
921 return; /* ignore */
922 if((c = getclient(ev->window))) {
923 switch (ev->atom) {
924 default: break;
925 case XA_WM_TRANSIENT_FOR:
926 XGetTransientForHint(dpy, c->win, &trans);
927 if(!c->isfloat && (c->isfloat = (trans != 0)))
928 arrange();
929 break;
930 case XA_WM_NORMAL_HINTS:
931 updatesizehints(c);
932 break;
933 }
934 if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
935 updatetitle(c);
936 if(c == sel)
937 drawstatus();
938 }
939 }
940 }
942 static void
943 unmapnotify(XEvent *e) {
944 Client *c;
945 XUnmapEvent *ev = &e->xunmap;
947 if((c = getclient(ev->window)))
948 unmanage(c);
949 }
953 void (*handler[LASTEvent]) (XEvent *) = {
954 [ButtonPress] = buttonpress,
955 [ConfigureRequest] = configurerequest,
956 [DestroyNotify] = destroynotify,
957 [EnterNotify] = enternotify,
958 [LeaveNotify] = leavenotify,
959 [Expose] = expose,
960 [KeyPress] = keypress,
961 [MappingNotify] = mappingnotify,
962 [MapRequest] = maprequest,
963 [PropertyNotify] = propertynotify,
964 [UnmapNotify] = unmapnotify
965 };
967 void
968 grabkeys(void) {
969 static unsigned int len = sizeof key / sizeof key[0];
970 unsigned int i;
971 KeyCode code;
973 XUngrabKey(dpy, AnyKey, AnyModifier, root);
974 for(i = 0; i < len; i++) {
975 code = XKeysymToKeycode(dpy, key[i].keysym);
976 XGrabKey(dpy, code, key[i].mod, root, True,
977 GrabModeAsync, GrabModeAsync);
978 XGrabKey(dpy, code, key[i].mod | LockMask, root, True,
979 GrabModeAsync, GrabModeAsync);
980 XGrabKey(dpy, code, key[i].mod | numlockmask, root, True,
981 GrabModeAsync, GrabModeAsync);
982 XGrabKey(dpy, code, key[i].mod | numlockmask | LockMask, root, True,
983 GrabModeAsync, GrabModeAsync);
984 }
985 }
987 void
988 procevent(void) {
989 XEvent ev;
991 while(XPending(dpy)) {
992 XNextEvent(dpy, &ev);
993 if(handler[ev.type])
994 (handler[ev.type])(&ev); /* call handler */
995 }
996 }
1012 /* from draw.c */
1013 /* static */
1015 static unsigned int
1016 textnw(const char *text, unsigned int len) {
1017 XRectangle r;
1019 if(dc.font.set) {
1020 XmbTextExtents(dc.font.set, text, len, NULL, &r);
1021 return r.width;
1022 }
1023 return XTextWidth(dc.font.xfont, text, len);
1024 }
1026 static void
1027 drawtext(const char *text, unsigned long col[ColLast]) {
1028 int x, y, w, h;
1029 static char buf[256];
1030 unsigned int len, olen;
1031 XGCValues gcv;
1032 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
1034 XSetForeground(dpy, dc.gc, col[ColBG]);
1035 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
1036 if(!text)
1037 return;
1038 w = 0;
1039 olen = len = strlen(text);
1040 if(len >= sizeof buf)
1041 len = sizeof buf - 1;
1042 memcpy(buf, text, len);
1043 buf[len] = 0;
1044 h = dc.font.ascent + dc.font.descent;
1045 y = dc.y + (dc.h / 2) - (h / 2) + dc.font.ascent;
1046 x = dc.x + (h / 2);
1047 /* shorten text if necessary */
1048 while(len && (w = textnw(buf, len)) > dc.w - h)
1049 buf[--len] = 0;
1050 if(len < olen) {
1051 if(len > 1)
1052 buf[len - 1] = '.';
1053 if(len > 2)
1054 buf[len - 2] = '.';
1055 if(len > 3)
1056 buf[len - 3] = '.';
1057 }
1058 if(w > dc.w)
1059 return; /* too long */
1060 gcv.foreground = col[ColFG];
1061 if(dc.font.set) {
1062 XChangeGC(dpy, dc.gc, GCForeground, &gcv);
1063 XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
1064 } else {
1065 gcv.font = dc.font.xfont->fid;
1066 XChangeGC(dpy, dc.gc, GCForeground | GCFont, &gcv);
1067 XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
1068 }
1069 }
1073 void
1074 drawstatus(void) {
1075 int x;
1076 unsigned int i;
1078 dc.x = dc.y = 0;
1079 for(i = 0; i < ntags; i++) {
1080 dc.w = textw(tags[i]);
1081 drawtext(tags[i], ( ((i == 0 && seltag) || (i == 1 && !seltag)) ? dc.sel : dc.norm));
1082 dc.x += dc.w + 1;
1083 }
1084 dc.w = bmw;
1085 drawtext("", dc.norm);
1086 x = dc.x + dc.w;
1087 dc.w = textw(stext);
1088 dc.x = sw - dc.w;
1089 if(dc.x < x) {
1090 dc.x = x;
1091 dc.w = sw - x;
1092 }
1093 drawtext(stext, dc.norm);
1094 if((dc.w = dc.x - x) > bh) {
1095 dc.x = x;
1096 drawtext(sel ? sel->name : NULL, dc.norm);
1097 }
1098 XCopyArea(dpy, dc.drawable, barwin, dc.gc, 0, 0, sw, bh, 0, 0);
1099 XSync(dpy, False);
1100 }
1102 unsigned long
1103 getcolor(const char *colstr) {
1104 Colormap cmap = DefaultColormap(dpy, screen);
1105 XColor color;
1107 if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
1108 eprint("error, cannot allocate color '%s'\n", colstr);
1109 return color.pixel;
1110 }
1112 void
1113 setfont(const char *fontstr) {
1114 char *def, **missing;
1115 int i, n;
1117 missing = NULL;
1118 if(dc.font.set)
1119 XFreeFontSet(dpy, dc.font.set);
1120 dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
1121 if(missing) {
1122 while(n--)
1123 fprintf(stderr, "missing fontset: %s\n", missing[n]);
1124 XFreeStringList(missing);
1125 }
1126 if(dc.font.set) {
1127 XFontSetExtents *font_extents;
1128 XFontStruct **xfonts;
1129 char **font_names;
1130 dc.font.ascent = dc.font.descent = 0;
1131 font_extents = XExtentsOfFontSet(dc.font.set);
1132 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
1133 for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
1134 if(dc.font.ascent < (*xfonts)->ascent)
1135 dc.font.ascent = (*xfonts)->ascent;
1136 if(dc.font.descent < (*xfonts)->descent)
1137 dc.font.descent = (*xfonts)->descent;
1138 xfonts++;
1139 }
1140 } else {
1141 if(dc.font.xfont)
1142 XFreeFont(dpy, dc.font.xfont);
1143 dc.font.xfont = NULL;
1144 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr)))
1145 eprint("error, cannot load font: '%s'\n", fontstr);
1146 dc.font.ascent = dc.font.xfont->ascent;
1147 dc.font.descent = dc.font.xfont->descent;
1148 }
1149 dc.font.height = dc.font.ascent + dc.font.descent;
1150 }
1152 unsigned int
1153 textw(const char *text) {
1154 return textnw(text, strlen(text)) + dc.font.height;
1155 }
1167 /* from client.c */
1168 /* static */
1170 static void
1171 detachstack(Client *c) {
1172 Client **tc;
1173 for(tc=&stack; *tc && *tc != c; tc=&(*tc)->snext);
1174 *tc = c->snext;
1175 }
1177 static void
1178 grabbuttons(Client *c, Bool focused) {
1179 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1181 if(focused) {
1182 XGrabButton(dpy, Button1, MODKEY, c->win, False, BUTTONMASK,
1183 GrabModeAsync, GrabModeSync, None, None);
1184 XGrabButton(dpy, Button1, MODKEY | LockMask, c->win, False, BUTTONMASK,
1185 GrabModeAsync, GrabModeSync, None, None);
1186 XGrabButton(dpy, Button1, MODKEY | numlockmask, c->win, False, BUTTONMASK,
1187 GrabModeAsync, GrabModeSync, None, None);
1188 XGrabButton(dpy, Button1, MODKEY | numlockmask | LockMask, c->win, False, BUTTONMASK,
1189 GrabModeAsync, GrabModeSync, None, None);
1191 XGrabButton(dpy, Button2, MODKEY, c->win, False, BUTTONMASK,
1192 GrabModeAsync, GrabModeSync, None, None);
1193 XGrabButton(dpy, Button2, MODKEY | LockMask, c->win, False, BUTTONMASK,
1194 GrabModeAsync, GrabModeSync, None, None);
1195 XGrabButton(dpy, Button2, MODKEY | numlockmask, c->win, False, BUTTONMASK,
1196 GrabModeAsync, GrabModeSync, None, None);
1197 XGrabButton(dpy, Button2, MODKEY | numlockmask | LockMask, c->win, False, BUTTONMASK,
1198 GrabModeAsync, GrabModeSync, None, None);
1200 XGrabButton(dpy, Button3, MODKEY, c->win, False, BUTTONMASK,
1201 GrabModeAsync, GrabModeSync, None, None);
1202 XGrabButton(dpy, Button3, MODKEY | LockMask, c->win, False, BUTTONMASK,
1203 GrabModeAsync, GrabModeSync, None, None);
1204 XGrabButton(dpy, Button3, MODKEY | numlockmask, c->win, False, BUTTONMASK,
1205 GrabModeAsync, GrabModeSync, None, None);
1206 XGrabButton(dpy, Button3, MODKEY | numlockmask | LockMask, c->win, False, BUTTONMASK,
1207 GrabModeAsync, GrabModeSync, None, None);
1208 } else {
1209 XGrabButton(dpy, AnyButton, AnyModifier, c->win, False, BUTTONMASK,
1210 GrabModeAsync, GrabModeSync, None, None);
1211 }
1212 }
1214 static void
1215 setclientstate(Client *c, long state) {
1216 long data[] = {state, None};
1217 XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1218 PropModeReplace, (unsigned char *)data, 2);
1219 }
1221 static int
1222 xerrordummy(Display *dsply, XErrorEvent *ee) {
1223 return 0;
1224 }
1228 void
1229 configure(Client *c) {
1230 XEvent synev;
1232 synev.type = ConfigureNotify;
1233 synev.xconfigure.display = dpy;
1234 synev.xconfigure.event = c->win;
1235 synev.xconfigure.window = c->win;
1236 synev.xconfigure.x = c->x;
1237 synev.xconfigure.y = c->y;
1238 synev.xconfigure.width = c->w;
1239 synev.xconfigure.height = c->h;
1240 synev.xconfigure.border_width = c->border;
1241 synev.xconfigure.above = None;
1242 XSendEvent(dpy, c->win, True, NoEventMask, &synev);
1243 }
1245 void
1246 focus(Client *c) {
1247 if(c && !isvisible(c))
1248 return;
1249 if(sel && sel != c) {
1250 grabbuttons(sel, False);
1251 XSetWindowBorder(dpy, sel->win, dc.norm[ColBorder]);
1252 }
1253 if(c) {
1254 detachstack(c);
1255 c->snext = stack;
1256 stack = c;
1257 grabbuttons(c, True);
1258 }
1259 sel = c;
1260 drawstatus();
1261 if(!selscreen)
1262 return;
1263 if(c) {
1264 XSetWindowBorder(dpy, c->win, dc.sel[ColBorder]);
1265 XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
1266 } else {
1267 XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
1268 }
1269 }
1271 Client *
1272 getclient(Window w) {
1273 Client *c;
1275 for(c = clients; c; c = c->next) {
1276 if(c->win == w) {
1277 return c;
1278 }
1279 }
1280 return NULL;
1281 }
1283 Bool
1284 isprotodel(Client *c) {
1285 int i, n;
1286 Atom *protocols;
1287 Bool ret = False;
1289 if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
1290 for(i = 0; !ret && i < n; i++)
1291 if(protocols[i] == wmatom[WMDelete])
1292 ret = True;
1293 XFree(protocols);
1294 }
1295 return ret;
1296 }
1298 void
1299 killclient() {
1300 if(!sel)
1301 return;
1302 if(isprotodel(sel))
1303 sendevent(sel->win, wmatom[WMProtocols], wmatom[WMDelete]);
1304 else
1305 XKillClient(dpy, sel->win);
1306 }
1308 void
1309 manage(Window w, XWindowAttributes *wa) {
1310 Client *c;
1311 Window trans;
1313 c = emallocz(sizeof(Client));
1314 c->tag = True;
1315 c->win = w;
1316 c->x = wa->x;
1317 c->y = wa->y;
1318 c->w = wa->width;
1319 c->h = wa->height;
1320 if(c->w == sw && c->h == sh) {
1321 c->border = 0;
1322 c->x = sx;
1323 c->y = sy;
1324 } else {
1325 c->border = BORDERPX;
1326 if(c->x + c->w + 2 * c->border > wax + waw)
1327 c->x = wax + waw - c->w - 2 * c->border;
1328 if(c->y + c->h + 2 * c->border > way + wah)
1329 c->y = way + wah - c->h - 2 * c->border;
1330 if(c->x < wax)
1331 c->x = wax;
1332 if(c->y < way)
1333 c->y = way;
1334 }
1335 updatesizehints(c);
1336 XSelectInput(dpy, c->win,
1337 StructureNotifyMask | PropertyChangeMask | EnterWindowMask);
1338 XGetTransientForHint(dpy, c->win, &trans);
1339 grabbuttons(c, False);
1340 XSetWindowBorder(dpy, c->win, dc.norm[ColBorder]);
1341 updatetitle(c);
1342 settags(c, getclient(trans));
1343 if(!c->isfloat)
1344 c->isfloat = trans || c->isfixed;
1345 if(clients)
1346 clients->prev = c;
1347 c->next = clients;
1348 c->snext = stack;
1349 stack = clients = c;
1350 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
1351 XMapWindow(dpy, c->win);
1352 setclientstate(c, NormalState);
1353 if(isvisible(c))
1354 focus(c);
1355 arrange();
1356 }
1358 void
1359 resize(Client *c, Bool sizehints) {
1360 float actual, dx, dy, max, min;
1361 XWindowChanges wc;
1363 if(c->w <= 0 || c->h <= 0)
1364 return;
1365 if(sizehints) {
1366 if(c->minw && c->w < c->minw)
1367 c->w = c->minw;
1368 if(c->minh && c->h < c->minh)
1369 c->h = c->minh;
1370 if(c->maxw && c->w > c->maxw)
1371 c->w = c->maxw;
1372 if(c->maxh && c->h > c->maxh)
1373 c->h = c->maxh;
1374 /* inspired by algorithm from fluxbox */
1375 if(c->minay > 0 && c->maxay && (c->h - c->baseh) > 0) {
1376 dx = (float)(c->w - c->basew);
1377 dy = (float)(c->h - c->baseh);
1378 min = (float)(c->minax) / (float)(c->minay);
1379 max = (float)(c->maxax) / (float)(c->maxay);
1380 actual = dx / dy;
1381 if(max > 0 && min > 0 && actual > 0) {
1382 if(actual < min) {
1383 dy = (dx * min + dy) / (min * min + 1);
1384 dx = dy * min;
1385 c->w = (int)dx + c->basew;
1386 c->h = (int)dy + c->baseh;
1387 }
1388 else if(actual > max) {
1389 dy = (dx * min + dy) / (max * max + 1);
1390 dx = dy * min;
1391 c->w = (int)dx + c->basew;
1392 c->h = (int)dy + c->baseh;
1393 }
1394 }
1395 }
1396 if(c->incw)
1397 c->w -= (c->w - c->basew) % c->incw;
1398 if(c->inch)
1399 c->h -= (c->h - c->baseh) % c->inch;
1400 }
1401 if(c->w == sw && c->h == sh)
1402 c->border = 0;
1403 else
1404 c->border = BORDERPX;
1405 /* offscreen appearance fixes */
1406 if(c->x > sw)
1407 c->x = sw - c->w - 2 * c->border;
1408 if(c->y > sh)
1409 c->y = sh - c->h - 2 * c->border;
1410 if(c->x + c->w + 2 * c->border < sx)
1411 c->x = sx;
1412 if(c->y + c->h + 2 * c->border < sy)
1413 c->y = sy;
1414 wc.x = c->x;
1415 wc.y = c->y;
1416 wc.width = c->w;
1417 wc.height = c->h;
1418 wc.border_width = c->border;
1419 XConfigureWindow(dpy, c->win, CWX | CWY | CWWidth | CWHeight | CWBorderWidth, &wc);
1420 configure(c);
1421 XSync(dpy, False);
1422 }
1424 void
1425 updatesizehints(Client *c) {
1426 long msize;
1427 XSizeHints size;
1429 if(!XGetWMNormalHints(dpy, c->win, &size, &msize) || !size.flags)
1430 size.flags = PSize;
1431 c->flags = size.flags;
1432 if(c->flags & PBaseSize) {
1433 c->basew = size.base_width;
1434 c->baseh = size.base_height;
1435 } else {
1436 c->basew = c->baseh = 0;
1437 }
1438 if(c->flags & PResizeInc) {
1439 c->incw = size.width_inc;
1440 c->inch = size.height_inc;
1441 } else {
1442 c->incw = c->inch = 0;
1443 }
1444 if(c->flags & PMaxSize) {
1445 c->maxw = size.max_width;
1446 c->maxh = size.max_height;
1447 } else {
1448 c->maxw = c->maxh = 0;
1449 }
1450 if(c->flags & PMinSize) {
1451 c->minw = size.min_width;
1452 c->minh = size.min_height;
1453 } else {
1454 c->minw = c->minh = 0;
1455 }
1456 if(c->flags & PAspect) {
1457 c->minax = size.min_aspect.x;
1458 c->minay = size.min_aspect.y;
1459 c->maxax = size.max_aspect.x;
1460 c->maxay = size.max_aspect.y;
1461 } else {
1462 c->minax = c->minay = c->maxax = c->maxay = 0;
1463 }
1464 c->isfixed = (c->maxw && c->minw && c->maxh && c->minh &&
1465 c->maxw == c->minw && c->maxh == c->minh);
1466 }
1468 void
1469 updatetitle(Client *c) {
1470 char **list = NULL;
1471 int n;
1472 XTextProperty name;
1474 name.nitems = 0;
1475 c->name[0] = 0;
1476 XGetTextProperty(dpy, c->win, &name, netatom[NetWMName]);
1477 if(!name.nitems)
1478 XGetWMName(dpy, c->win, &name);
1479 if(!name.nitems)
1480 return;
1481 if(name.encoding == XA_STRING)
1482 strncpy(c->name, (char *)name.value, sizeof c->name);
1483 else {
1484 if(XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success && n > 0 && *list) {
1485 strncpy(c->name, *list, sizeof c->name);
1486 XFreeStringList(list);
1487 }
1488 }
1489 XFree(name.value);
1490 }
1492 void
1493 unmanage(Client *c) {
1494 Client *nc;
1496 /* The server grab construct avoids race conditions. */
1497 XGrabServer(dpy);
1498 XSetErrorHandler(xerrordummy);
1499 detach(c);
1500 detachstack(c);
1501 if(sel == c) {
1502 for(nc = stack; nc && !isvisible(nc); nc = nc->snext);
1503 focus(nc);
1504 }
1505 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1506 setclientstate(c, WithdrawnState);
1507 free(c);
1508 XSync(dpy, False);
1509 XSetErrorHandler(xerror);
1510 XUngrabServer(dpy);
1511 arrange();
1512 }
1532 /* static */
1535 static void
1536 cleanup(void) {
1537 close(STDIN_FILENO);
1538 while(stack) {
1539 resize(stack, True);
1540 unmanage(stack);
1541 }
1542 if(dc.font.set)
1543 XFreeFontSet(dpy, dc.font.set);
1544 else
1545 XFreeFont(dpy, dc.font.xfont);
1546 XUngrabKey(dpy, AnyKey, AnyModifier, root);
1547 XFreePixmap(dpy, dc.drawable);
1548 XFreeGC(dpy, dc.gc);
1549 XDestroyWindow(dpy, barwin);
1550 XFreeCursor(dpy, cursor[CurNormal]);
1551 XFreeCursor(dpy, cursor[CurResize]);
1552 XFreeCursor(dpy, cursor[CurMove]);
1553 XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime);
1554 XSync(dpy, False);
1555 }
1557 static void
1558 scan(void) {
1559 unsigned int i, num;
1560 Window *wins, d1, d2;
1561 XWindowAttributes wa;
1563 wins = NULL;
1564 if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1565 for(i = 0; i < num; i++) {
1566 if(!XGetWindowAttributes(dpy, wins[i], &wa))
1567 continue;
1568 if(wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1569 continue;
1570 if(wa.map_state == IsViewable)
1571 manage(wins[i], &wa);
1572 }
1573 }
1574 if(wins)
1575 XFree(wins);
1576 }
1578 static void
1579 setup(void) {
1580 int i, j;
1581 unsigned int mask;
1582 Window w;
1583 XModifierKeymap *modmap;
1584 XSetWindowAttributes wa;
1586 /* init atoms */
1587 wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1588 wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1589 wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1590 netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1591 netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1592 XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1593 PropModeReplace, (unsigned char *) netatom, NetLast);
1594 /* init cursors */
1595 cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1596 cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1597 cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1598 /* init modifier map */
1599 numlockmask = 0;
1600 modmap = XGetModifierMapping(dpy);
1601 for (i = 0; i < 8; i++) {
1602 for (j = 0; j < modmap->max_keypermod; j++) {
1603 if(modmap->modifiermap[i * modmap->max_keypermod + j] == XKeysymToKeycode(dpy, XK_Num_Lock))
1604 numlockmask = (1 << i);
1605 }
1606 }
1607 XFreeModifiermap(modmap);
1608 /* select for events */
1609 wa.event_mask = SubstructureRedirectMask | SubstructureNotifyMask
1610 | EnterWindowMask | LeaveWindowMask;
1611 wa.cursor = cursor[CurNormal];
1612 XChangeWindowAttributes(dpy, root, CWEventMask | CWCursor, &wa);
1613 grabkeys();
1614 initrregs();
1615 ntags = 2;
1616 seltag = True;
1617 /* style */
1618 dc.norm[ColBorder] = getcolor(NORMBORDERCOLOR);
1619 dc.norm[ColBG] = getcolor(NORMBGCOLOR);
1620 dc.norm[ColFG] = getcolor(NORMFGCOLOR);
1621 dc.sel[ColBorder] = getcolor(SELBORDERCOLOR);
1622 dc.sel[ColBG] = getcolor(SELBGCOLOR);
1623 dc.sel[ColFG] = getcolor(SELFGCOLOR);
1624 setfont(FONT);
1625 /* geometry */
1626 sx = sy = 0;
1627 sw = DisplayWidth(dpy, screen);
1628 sh = DisplayHeight(dpy, screen);
1629 nmaster = NMASTER;
1630 bmw = 1;
1631 /* bar */
1632 dc.h = bh = dc.font.height + 2;
1633 wa.override_redirect = 1;
1634 wa.background_pixmap = ParentRelative;
1635 wa.event_mask = ButtonPressMask | ExposureMask;
1636 barwin = XCreateWindow(dpy, root, sx, sy, sw, bh, 0,
1637 DefaultDepth(dpy, screen), CopyFromParent, DefaultVisual(dpy, screen),
1638 CWOverrideRedirect | CWBackPixmap | CWEventMask, &wa);
1639 XDefineCursor(dpy, barwin, cursor[CurNormal]);
1640 XMapRaised(dpy, barwin);
1641 strcpy(stext, "dwm-"VERSION);
1642 /* windowarea */
1643 wax = sx;
1644 way = sy + bh;
1645 wah = sh - bh;
1646 waw = sw;
1647 /* pixmap for everything */
1648 dc.drawable = XCreatePixmap(dpy, root, sw, bh, DefaultDepth(dpy, screen));
1649 dc.gc = XCreateGC(dpy, root, 0, 0);
1650 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
1651 /* multihead support */
1652 selscreen = XQueryPointer(dpy, root, &w, &w, &i, &i, &i, &i, &mask);
1653 }
1655 /*
1656 * Startup Error handler to check if another window manager
1657 * is already running.
1658 */
1659 static int
1660 xerrorstart(Display *dsply, XErrorEvent *ee) {
1661 otherwm = True;
1662 return -1;
1663 }
1667 void
1668 sendevent(Window w, Atom a, long value) {
1669 XEvent e;
1671 e.type = ClientMessage;
1672 e.xclient.window = w;
1673 e.xclient.message_type = a;
1674 e.xclient.format = 32;
1675 e.xclient.data.l[0] = value;
1676 e.xclient.data.l[1] = CurrentTime;
1677 XSendEvent(dpy, w, False, NoEventMask, &e);
1678 XSync(dpy, False);
1679 }
1681 void
1682 quit() {
1683 readin = running = False;
1684 }
1686 /* There's no way to check accesses to destroyed windows, thus those cases are
1687 * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
1688 * default error handler, which may call exit.
1689 */
1690 int
1691 xerror(Display *dpy, XErrorEvent *ee) {
1692 if(ee->error_code == BadWindow
1693 || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1694 || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1695 || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1696 || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1697 || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1698 || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1699 || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1700 return 0;
1701 fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1702 ee->request_code, ee->error_code);
1703 return xerrorxlib(dpy, ee); /* may call exit */
1704 }
1706 int
1707 main(int argc, char *argv[]) {
1708 char *p;
1709 int r, xfd;
1710 fd_set rd;
1712 if(argc == 2 && !strncmp("-v", argv[1], 3)) {
1713 fputs("dwm-"VERSION", (C)opyright MMVI-MMVII Anselm R. Garbe\n", stdout);
1714 exit(EXIT_SUCCESS);
1715 } else if(argc != 1) {
1716 eprint("usage: dwm [-v]\n");
1717 }
1718 setlocale(LC_CTYPE, "");
1719 dpy = XOpenDisplay(0);
1720 if(!dpy) {
1721 eprint("dwm: cannot open display\n");
1722 }
1723 xfd = ConnectionNumber(dpy);
1724 screen = DefaultScreen(dpy);
1725 root = RootWindow(dpy, screen);
1726 otherwm = False;
1727 XSetErrorHandler(xerrorstart);
1728 /* this causes an error if some other window manager is running */
1729 XSelectInput(dpy, root, SubstructureRedirectMask);
1730 XSync(dpy, False);
1731 if(otherwm) {
1732 eprint("dwm: another window manager is already running\n");
1733 }
1735 XSync(dpy, False);
1736 XSetErrorHandler(NULL);
1737 xerrorxlib = XSetErrorHandler(xerror);
1738 XSync(dpy, False);
1739 setup();
1740 drawstatus();
1741 scan();
1743 /* main event loop, also reads status text from stdin */
1744 XSync(dpy, False);
1745 procevent();
1746 readin = True;
1747 while(running) {
1748 FD_ZERO(&rd);
1749 if(readin)
1750 FD_SET(STDIN_FILENO, &rd);
1751 FD_SET(xfd, &rd);
1752 if(select(xfd + 1, &rd, NULL, NULL, NULL) == -1) {
1753 if(errno == EINTR)
1754 continue;
1755 eprint("select failed\n");
1756 }
1757 if(FD_ISSET(STDIN_FILENO, &rd)) {
1758 switch(r = read(STDIN_FILENO, stext, sizeof stext - 1)) {
1759 case -1:
1760 strncpy(stext, strerror(errno), sizeof stext - 1);
1761 stext[sizeof stext - 1] = '\0';
1762 readin = False;
1763 break;
1764 case 0:
1765 strncpy(stext, "EOF", 4);
1766 readin = False;
1767 break;
1768 default:
1769 for(stext[r] = '\0', p = stext + strlen(stext) - 1; p >= stext && *p == '\n'; *p-- = '\0');
1770 for(; p >= stext && *p != '\n'; --p);
1771 if(p > stext)
1772 strncpy(stext, p + 1, sizeof stext);
1773 }
1774 drawstatus();
1775 }
1776 if(FD_ISSET(xfd, &rd))
1777 procevent();
1778 }
1779 cleanup();
1780 XCloseDisplay(dpy);
1781 return 0;
1782 }