aewl

view aewl.c @ 771:59a6f0ba5478

beautified status bar
author meillo@marmaro.de
date Sat, 06 Dec 2008 10:56:43 +0100
parents 33cec4282120
children 0c1e9952a278
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. [...]
22 *
23 * Keys and tagging rules are organized as arrays and defined in the config.h
24 * file. [...] The current mode is represented by the arrange() function
25 * pointer, which wether points to [domax()] or dotile().
26 *
27 * To understand everything else, start reading main.c:main().
28 *
29 * -- and now about aewl --
30 *
31 * aewl is a stripped down dwm. It stated as a patchset, but finally forked off
32 * completely. The reason for this was the increasing gap between my wish to
33 * stay where dwm was, and dwm direction to go further. Further more did I
34 * always use only a small subset of dwm's features, so condencing dwm had been
35 * my wish for a long time.
36 *
37 * In aewl clients are either tagged or not (only one tag). Visible are either
38 * all tagged clients or all without the tag.
39 */
42 #include <errno.h>
43 #include <locale.h>
44 #include <stdio.h>
45 #include <stdarg.h>
46 #include <stdlib.h>
47 #include <string.h>
48 #include <unistd.h>
49 #include <sys/select.h>
50 #include <sys/types.h>
51 #include <sys/wait.h>
52 #include <X11/cursorfont.h>
53 #include <X11/keysym.h>
54 #include <X11/Xatom.h>
55 #include <X11/Xlib.h>
56 #include <X11/Xproto.h>
57 #include <X11/Xutil.h>
59 #include "config.h"
62 /* mask shorthands, used in event.c and client.c */
63 #define BUTTONMASK (ButtonPressMask | ButtonReleaseMask)
65 enum { NetSupported, NetWMName, NetLast }; /* EWMH atoms */
66 enum { WMProtocols, WMDelete, WMState, WMLast }; /* default atoms */
67 enum { CurNormal, CurResize, CurMove, CurLast }; /* cursor */
68 enum { ColFG, ColBG, ColLast }; /* color */
70 typedef struct {
71 int ascent;
72 int descent;
73 int height;
74 XFontSet set;
75 XFontStruct *xfont;
76 } Fnt;
78 typedef struct {
79 int x, y, w, h;
80 unsigned long norm[ColLast];
81 unsigned long sel[ColLast];
82 Drawable drawable;
83 Fnt font;
84 GC gc;
85 } DC; /* draw context */
87 typedef struct Client Client;
88 struct Client {
89 char name[256];
90 int x, y, w, h;
91 int rx, ry, rw, rh; /* revert geometry */
92 int basew, baseh, incw, inch, maxw, maxh, minw, minh;
93 int minax, minay, maxax, maxay;
94 long flags;
95 unsigned int border;
96 Bool isfixed, isfloat, ismax;
97 Bool tag;
98 Client *next;
99 Client *prev;
100 Client *snext;
101 Window win;
102 };
104 typedef struct {
105 const char* class;
106 const char* instance;
107 const char* title;
108 int tag;
109 Bool isfloat;
110 } Rule;
113 typedef struct {
114 unsigned long mod;
115 KeySym keysym;
116 void (*func)(const char* cmd);
117 const char* cmd;
118 } Key;
121 #define CLEANMASK(mask) (mask & ~(numlockmask | LockMask))
122 #define MOUSEMASK (BUTTONMASK | PointerMotionMask)
126 char stext[256]; /* status text */
127 int bh; /* bar height */
128 int screen, sx, sy, sw, sh; /* screen geometry */
129 int wax, way, wah, waw; /* windowarea geometry */
130 unsigned int nmaster; /* number of master clients */
131 unsigned int numlockmask; /* dynamic lock mask */
132 void (*handler[LASTEvent])(XEvent *); /* event handler */
133 void (*arrange)(void); /* arrange function, indicates mode */
134 Atom wmatom[WMLast], netatom[NetLast];
135 Bool running, selscreen, seltag;
136 Client *clients, *sel, *stack; /* global client list and stack */
137 Cursor cursor[CurLast];
138 DC dc; /* global draw context */
139 Display *dpy;
140 Window root, barwin;
142 Bool running = True;
143 Bool selscreen = True;
144 Client *clients = NULL;
145 Client *sel = NULL;
146 Client *stack = NULL;
147 DC dc = {0};
149 static int (*xerrorxlib)(Display *, XErrorEvent *);
150 static Bool otherwm, readin;
151 static unsigned int len = 0;
154 RULES
157 /* client.c */
158 void configure(Client *c); /* send synthetic configure event */
159 void focus(Client *c); /* focus c, c may be NULL */
160 Client *getclient(Window w); /* return client of w */
161 Bool isprotodel(Client *c); /* returns True if c->win supports wmatom[WMDelete] */
162 void manage(Window w, XWindowAttributes *wa); /* manage new client */
163 void resize(Client *c, Bool sizehints); /* resize c*/
164 void updatesizehints(Client *c); /* update the size hint variables of c */
165 void updatetitle(Client *c); /* update the name of c */
166 void unmanage(Client *c); /* destroy c */
168 /* draw.c */
169 void drawstatus(void); /* draw the bar */
170 unsigned long getcolor(const char *colstr); /* return color of colstr */
171 void setfont(const char *fontstr); /* set the font for DC */
172 unsigned int textw(const char *text); /* return the width of text in px*/
174 /* event.c */
175 void grabkeys(void); /* grab all keys defined in config.h */
176 void procevent(void); /* process pending X events */
178 /* main.c */
179 void sendevent(Window w, Atom a, long value); /* send synthetic event to w */
180 int xerror(Display *dsply, XErrorEvent *ee); /* dwm's X error handler */
182 /* tag.c */
183 Client *getnext(Client *c); /* returns next visible client */
184 void settag(Client *c, Client *trans); /* sets tag of c */
186 /* util.c */
187 void *emallocz(unsigned int size); /* allocates zero-initialized memory, exits on error */
188 void eprint(const char *errstr, ...); /* prints errstr and exits with 1 */
190 /* view.c */
191 void detach(Client *c); /* detaches c from global client list */
192 void dotile(void); /* arranges all windows tiled */
193 void domax(void); /* arranges all windows fullscreen */
194 Bool isvisible(Client *c); /* returns True if client is visible */
195 void restack(void); /* restores z layers of all clients */
198 void toggleview(void); /* toggle the view */
199 void focusnext(void); /* focuses next visible client */
200 void zoom(void); /* zooms the focused client to master area */
201 void killclient(void); /* kill c nicely */
202 void quit(void); /* quit dwm nicely */
203 void togglemode(void); /* toggles global arrange function (dotile/domax) */
204 void togglefloat(void); /* toggles focusesd client between floating/non-floating state */
205 void incnmaster(void); /* increments nmaster */
206 void decnmaster(void); /* decrements nmaster */
207 void toggletag(void); /* toggles tag of c */
208 void spawn(const char* cmd); /* forks a new subprocess with cmd */
219 /* from view.c */
220 /* static */
222 static Client *
223 nexttiled(Client *c) {
224 for(c = getnext(c); c && c->isfloat; c = getnext(c->next));
225 return c;
226 }
228 static void
229 togglemax(Client *c) {
230 XEvent ev;
232 if(c->isfixed)
233 return;
235 if((c->ismax = !c->ismax)) {
236 c->rx = c->x;
237 c->ry = c->y;
238 c->rw = c->w;
239 c->rh = c->h;
240 c->x = wax;
241 c->y = way;
242 c->w = waw - 2 * BORDERPX;
243 c->h = wah - 2 * BORDERPX;
244 } else {
245 c->x = c->rx;
246 c->y = c->ry;
247 c->w = c->rw;
248 c->h = c->rh;
249 }
250 resize(c, False);
251 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
252 }
256 void (*arrange)(void) = DEFMODE;
258 void
259 detach(Client *c) {
260 if(c->prev)
261 c->prev->next = c->next;
262 if(c->next)
263 c->next->prev = c->prev;
264 if(c == clients)
265 clients = c->next;
266 c->next = c->prev = NULL;
267 }
269 void
270 dotile(void) {
271 unsigned int i, n, mw, mh, tw, th;
272 Client *c;
274 for(n = 0, c = nexttiled(clients); c; c = nexttiled(c->next))
275 n++;
276 /* window geoms */
277 mh = (n > nmaster) ? wah / nmaster : wah / (n > 0 ? n : 1);
278 mw = (n > nmaster) ? waw / 2 : waw;
279 th = (n > nmaster) ? wah / (n - nmaster) : 0;
280 tw = waw - mw;
282 for(i = 0, c = clients; c; c = c->next)
283 if(isvisible(c)) {
284 if(c->isfloat) {
285 resize(c, True);
286 continue;
287 }
288 c->ismax = False;
289 c->x = wax;
290 c->y = way;
291 if(i < nmaster) {
292 c->y += i * mh;
293 c->w = mw - 2 * BORDERPX;
294 c->h = mh - 2 * BORDERPX;
295 }
296 else { /* tile window */
297 c->x += mw;
298 c->w = tw - 2 * BORDERPX;
299 if(th > 2 * BORDERPX) {
300 c->y += (i - nmaster) * th;
301 c->h = th - 2 * BORDERPX;
302 }
303 else /* fallback if th <= 2 * BORDERPX */
304 c->h = wah - 2 * BORDERPX;
305 }
306 resize(c, False);
307 i++;
308 }
309 else
310 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
311 if(!sel || !isvisible(sel)) {
312 for(c = stack; c && !isvisible(c); c = c->snext);
313 focus(c);
314 }
315 restack();
316 }
318 void
319 domax(void) {
320 Client *c;
322 for(c = clients; c; c = c->next) {
323 if(isvisible(c)) {
324 if(c->isfloat) {
325 resize(c, True);
326 continue;
327 }
328 c->ismax = True;
329 c->x = wax;
330 c->y = way;
331 c->w = waw - 2 * BORDERPX;
332 c->h = wah - 2 * BORDERPX;
333 resize(c, False);
334 } else {
335 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
336 }
337 }
338 if(!sel || !isvisible(sel)) {
339 for(c = stack; c && !isvisible(c); c = c->snext);
340 focus(c);
341 }
342 restack();
343 }
345 void
346 focusnext() {
347 Client *c;
349 if(!sel)
350 return;
351 if(!(c = getnext(sel->next)))
352 c = getnext(clients);
353 if(c) {
354 focus(c);
355 restack();
356 }
357 }
359 void
360 incnmaster() {
361 if(wah / (nmaster + 1) <= 2 * BORDERPX)
362 return;
363 nmaster++;
364 if(sel)
365 arrange();
366 else
367 drawstatus();
368 }
370 void
371 decnmaster() {
372 if(nmaster <= 1)
373 return;
374 nmaster--;
375 if(sel)
376 arrange();
377 else
378 drawstatus();
379 }
381 Bool
382 isvisible(Client *c) {
383 return (c->tag == seltag);
384 }
386 void
387 restack(void) {
388 Client *c;
389 XEvent ev;
391 drawstatus();
392 if(!sel)
393 return;
394 if(sel->isfloat)
395 XRaiseWindow(dpy, sel->win);
397 if(!sel->isfloat)
398 XLowerWindow(dpy, sel->win);
399 for(c = nexttiled(clients); c; c = nexttiled(c->next)) {
400 if(c == sel)
401 continue;
402 XLowerWindow(dpy, c->win);
403 }
405 XSync(dpy, False);
406 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
407 }
409 void
410 togglefloat() {
411 if (!sel)
412 return;
413 sel->isfloat = !sel->isfloat;
414 arrange();
415 }
417 void
418 togglemode() {
419 /* only toggle between tile and max - float is just available through togglefloat */
420 arrange = (arrange == dotile) ? domax : dotile;
421 if(sel)
422 arrange();
423 else
424 drawstatus();
425 }
427 void
428 toggleview() {
429 seltag = !seltag;
430 arrange();
431 }
433 void
434 zoom() {
435 unsigned int n;
436 Client *c;
438 if(!sel)
439 return;
440 if(sel->isfloat) {
441 togglemax(sel);
442 return;
443 }
444 for(n = 0, c = nexttiled(clients); c; c = nexttiled(c->next))
445 n++;
447 if((c = sel) == nexttiled(clients))
448 if(!(c = nexttiled(c->next)))
449 return;
450 detach(c);
451 if(clients)
452 clients->prev = c;
453 c->next = clients;
454 clients = c;
455 focus(c);
456 arrange();
457 }
474 /* from util.c */
477 void *
478 emallocz(unsigned int size) {
479 void *res = calloc(1, size);
481 if(!res)
482 eprint("fatal: could not malloc() %u bytes\n", size);
483 return res;
484 }
486 void
487 eprint(const char *errstr, ...) {
488 va_list ap;
490 va_start(ap, errstr);
491 vfprintf(stderr, errstr, ap);
492 va_end(ap);
493 exit(EXIT_FAILURE);
494 }
496 void
497 spawn(const char* cmd) {
498 static char *shell = NULL;
500 if(!cmd)
501 return;
502 if(!(shell = getenv("SHELL")))
503 shell = "/bin/sh";
504 /* The double-fork construct avoids zombie processes and keeps the code
505 * clean from stupid signal handlers. */
506 if(fork() == 0) {
507 if(fork() == 0) {
508 if(dpy)
509 close(ConnectionNumber(dpy));
510 setsid();
511 execl(shell, shell, "-c", cmd, (char *)NULL);
512 fprintf(stderr, "dwm: execl '%s -c %s'", shell, cmd);
513 perror(" failed");
514 }
515 exit(0);
516 }
517 wait(0);
518 }
532 /* from tag.c */
534 /* static */
536 Client *
537 getnext(Client *c) {
538 while(c && !isvisible(c)) {
539 c = c->next;
540 }
541 return c;
542 }
544 void
545 settag(Client *c, Client *trans) {
546 unsigned int i;
547 XClassHint ch = { 0 };
549 if(trans) {
550 c->tag = trans->tag;
551 return;
552 }
553 c->tag = seltag; /* default */
554 XGetClassHint(dpy, c->win, &ch);
555 len = sizeof rule / sizeof rule[0];
556 for(i = 0; i < len; i++) {
557 if((rule[i].title && strstr(c->name, rule[i].title))
558 || (ch.res_class && rule[i].class && strstr(ch.res_class, rule[i].class))
559 || (ch.res_name && rule[i].instance && strstr(ch.res_name, rule[i].instance))) {
560 c->isfloat = rule[i].isfloat;
561 if (rule[i].tag < 0) {
562 c->tag = seltag;
563 } else if (rule[i].tag) {
564 c->tag = True;
565 } else {
566 c->tag = False;
567 }
568 break;
569 }
570 }
571 if(ch.res_class)
572 XFree(ch.res_class);
573 if(ch.res_name)
574 XFree(ch.res_name);
575 }
577 void
578 toggletag() {
579 if(!sel)
580 return;
581 sel->tag = !sel->tag;
582 toggleview();
583 }
601 /* from event.c */
602 /* static */
604 KEYS
608 static void
609 movemouse(Client *c) {
610 int x1, y1, ocx, ocy, di;
611 unsigned int dui;
612 Window dummy;
613 XEvent ev;
615 ocx = c->x;
616 ocy = c->y;
617 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
618 None, cursor[CurMove], CurrentTime) != GrabSuccess)
619 return;
620 c->ismax = False;
621 XQueryPointer(dpy, root, &dummy, &dummy, &x1, &y1, &di, &di, &dui);
622 for(;;) {
623 XMaskEvent(dpy, MOUSEMASK | ExposureMask | SubstructureRedirectMask, &ev);
624 switch (ev.type) {
625 case ButtonRelease:
626 resize(c, True);
627 XUngrabPointer(dpy, CurrentTime);
628 return;
629 case ConfigureRequest:
630 case Expose:
631 case MapRequest:
632 handler[ev.type](&ev);
633 break;
634 case MotionNotify:
635 XSync(dpy, False);
636 c->x = ocx + (ev.xmotion.x - x1);
637 c->y = ocy + (ev.xmotion.y - y1);
638 if(abs(wax + c->x) < SNAP)
639 c->x = wax;
640 else if(abs((wax + waw) - (c->x + c->w + 2 * c->border)) < SNAP)
641 c->x = wax + waw - c->w - 2 * c->border;
642 if(abs(way - c->y) < SNAP)
643 c->y = way;
644 else if(abs((way + wah) - (c->y + c->h + 2 * c->border)) < SNAP)
645 c->y = way + wah - c->h - 2 * c->border;
646 resize(c, False);
647 break;
648 }
649 }
650 }
652 static void
653 resizemouse(Client *c) {
654 int ocx, ocy;
655 int nw, nh;
656 XEvent ev;
658 ocx = c->x;
659 ocy = c->y;
660 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
661 None, cursor[CurResize], CurrentTime) != GrabSuccess)
662 return;
663 c->ismax = False;
664 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->border - 1, c->h + c->border - 1);
665 for(;;) {
666 XMaskEvent(dpy, MOUSEMASK | ExposureMask | SubstructureRedirectMask , &ev);
667 switch(ev.type) {
668 case ButtonRelease:
669 resize(c, True);
670 XUngrabPointer(dpy, CurrentTime);
671 return;
672 case ConfigureRequest:
673 case Expose:
674 case MapRequest:
675 handler[ev.type](&ev);
676 break;
677 case MotionNotify:
678 XSync(dpy, False);
679 nw = ev.xmotion.x - ocx - 2 * c->border + 1;
680 c->w = nw > 0 ? nw : 1;
681 nh = ev.xmotion.y - ocy - 2 * c->border + 1;
682 c->h = nh > 0 ? nh : 1;
683 resize(c, True);
684 break;
685 }
686 }
687 }
689 static void
690 buttonpress(XEvent *e) {
691 Client *c;
692 XButtonPressedEvent *ev = &e->xbutton;
694 if(barwin == ev->window) {
695 return;
696 }
697 if((c = getclient(ev->window))) {
698 focus(c);
699 if(CLEANMASK(ev->state) != MODKEY)
700 return;
701 if(ev->button == Button1 && c->isfloat) {
702 restack();
703 movemouse(c);
704 } else if(ev->button == Button3 && c->isfloat && !c->isfixed) {
705 restack();
706 resizemouse(c);
707 }
708 }
709 }
711 static void
712 configurerequest(XEvent *e) {
713 unsigned long newmask;
714 Client *c;
715 XConfigureRequestEvent *ev = &e->xconfigurerequest;
716 XWindowChanges wc;
718 if((c = getclient(ev->window))) {
719 c->ismax = False;
720 if(ev->value_mask & CWX)
721 c->x = ev->x;
722 if(ev->value_mask & CWY)
723 c->y = ev->y;
724 if(ev->value_mask & CWWidth)
725 c->w = ev->width;
726 if(ev->value_mask & CWHeight)
727 c->h = ev->height;
728 if(ev->value_mask & CWBorderWidth)
729 c->border = ev->border_width;
730 wc.x = c->x;
731 wc.y = c->y;
732 wc.width = c->w;
733 wc.height = c->h;
734 newmask = ev->value_mask & (~(CWSibling | CWStackMode | CWBorderWidth));
735 if(newmask)
736 XConfigureWindow(dpy, c->win, newmask, &wc);
737 else
738 configure(c);
739 XSync(dpy, False);
740 if(c->isfloat) {
741 resize(c, False);
742 if(!isvisible(c))
743 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
744 }
745 else
746 arrange();
747 } else {
748 wc.x = ev->x;
749 wc.y = ev->y;
750 wc.width = ev->width;
751 wc.height = ev->height;
752 wc.border_width = ev->border_width;
753 wc.sibling = ev->above;
754 wc.stack_mode = ev->detail;
755 XConfigureWindow(dpy, ev->window, ev->value_mask, &wc);
756 XSync(dpy, False);
757 }
758 }
760 static void
761 destroynotify(XEvent *e) {
762 Client *c;
763 XDestroyWindowEvent *ev = &e->xdestroywindow;
765 if((c = getclient(ev->window)))
766 unmanage(c);
767 }
769 static void
770 enternotify(XEvent *e) {
771 Client *c;
772 XCrossingEvent *ev = &e->xcrossing;
774 if(ev->mode != NotifyNormal || ev->detail == NotifyInferior)
775 return;
776 if((c = getclient(ev->window)) && isvisible(c))
777 focus(c);
778 else if(ev->window == root) {
779 selscreen = True;
780 for(c = stack; c && !isvisible(c); c = c->snext);
781 focus(c);
782 }
783 }
785 static void
786 expose(XEvent *e) {
787 XExposeEvent *ev = &e->xexpose;
789 if(ev->count == 0) {
790 if(barwin == ev->window)
791 drawstatus();
792 }
793 }
795 static void
796 keypress(XEvent *e) {
797 static unsigned int len = sizeof key / sizeof key[0];
798 unsigned int i;
799 KeySym keysym;
800 XKeyEvent *ev = &e->xkey;
802 keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
803 for(i = 0; i < len; i++) {
804 if(keysym == key[i].keysym && CLEANMASK(key[i].mod) == CLEANMASK(ev->state)) {
805 if(key[i].func)
806 key[i].func(key[i].cmd);
807 }
808 }
809 }
811 static void
812 leavenotify(XEvent *e) {
813 XCrossingEvent *ev = &e->xcrossing;
815 if((ev->window == root) && !ev->same_screen) {
816 selscreen = False;
817 focus(NULL);
818 }
819 }
821 static void
822 mappingnotify(XEvent *e) {
823 XMappingEvent *ev = &e->xmapping;
825 XRefreshKeyboardMapping(ev);
826 if(ev->request == MappingKeyboard)
827 grabkeys();
828 }
830 static void
831 maprequest(XEvent *e) {
832 static XWindowAttributes wa;
833 XMapRequestEvent *ev = &e->xmaprequest;
835 if(!XGetWindowAttributes(dpy, ev->window, &wa))
836 return;
837 if(wa.override_redirect) {
838 XSelectInput(dpy, ev->window,
839 (StructureNotifyMask | PropertyChangeMask));
840 return;
841 }
842 if(!getclient(ev->window))
843 manage(ev->window, &wa);
844 }
846 static void
847 propertynotify(XEvent *e) {
848 Client *c;
849 Window trans;
850 XPropertyEvent *ev = &e->xproperty;
852 if(ev->state == PropertyDelete)
853 return; /* ignore */
854 if((c = getclient(ev->window))) {
855 switch (ev->atom) {
856 default: break;
857 case XA_WM_TRANSIENT_FOR:
858 XGetTransientForHint(dpy, c->win, &trans);
859 if(!c->isfloat && (c->isfloat = (trans != 0)))
860 arrange();
861 break;
862 case XA_WM_NORMAL_HINTS:
863 updatesizehints(c);
864 break;
865 }
866 if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
867 updatetitle(c);
868 if(c == sel)
869 drawstatus();
870 }
871 }
872 }
874 static void
875 unmapnotify(XEvent *e) {
876 Client *c;
877 XUnmapEvent *ev = &e->xunmap;
879 if((c = getclient(ev->window)))
880 unmanage(c);
881 }
885 void (*handler[LASTEvent]) (XEvent *) = {
886 [ButtonPress] = buttonpress,
887 [ConfigureRequest] = configurerequest,
888 [DestroyNotify] = destroynotify,
889 [EnterNotify] = enternotify,
890 [LeaveNotify] = leavenotify,
891 [Expose] = expose,
892 [KeyPress] = keypress,
893 [MappingNotify] = mappingnotify,
894 [MapRequest] = maprequest,
895 [PropertyNotify] = propertynotify,
896 [UnmapNotify] = unmapnotify
897 };
899 void
900 grabkeys(void) {
901 static unsigned int len = sizeof key / sizeof key[0];
902 unsigned int i;
903 KeyCode code;
905 XUngrabKey(dpy, AnyKey, AnyModifier, root);
906 for(i = 0; i < len; i++) {
907 code = XKeysymToKeycode(dpy, key[i].keysym);
908 XGrabKey(dpy, code, key[i].mod, root, True,
909 GrabModeAsync, GrabModeAsync);
910 XGrabKey(dpy, code, key[i].mod | LockMask, root, True,
911 GrabModeAsync, GrabModeAsync);
912 XGrabKey(dpy, code, key[i].mod | numlockmask, root, True,
913 GrabModeAsync, GrabModeAsync);
914 XGrabKey(dpy, code, key[i].mod | numlockmask | LockMask, root, True,
915 GrabModeAsync, GrabModeAsync);
916 }
917 }
919 void
920 procevent(void) {
921 XEvent ev;
923 while(XPending(dpy)) {
924 XNextEvent(dpy, &ev);
925 if(handler[ev.type])
926 (handler[ev.type])(&ev); /* call handler */
927 }
928 }
944 /* from draw.c */
945 /* static */
947 static unsigned int
948 textnw(const char *text, unsigned int len) {
949 XRectangle r;
951 if(dc.font.set) {
952 XmbTextExtents(dc.font.set, text, len, NULL, &r);
953 return r.width;
954 }
955 return XTextWidth(dc.font.xfont, text, len);
956 }
958 static void
959 drawtext(const char *text, unsigned long col[ColLast]) {
960 int x, y, w, h;
961 static char buf[256];
962 unsigned int len, olen;
963 XGCValues gcv;
964 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
966 XSetForeground(dpy, dc.gc, col[ColBG]);
967 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
968 if(!text)
969 return;
970 w = 0;
971 olen = len = strlen(text);
972 if(len >= sizeof buf)
973 len = sizeof buf - 1;
974 memcpy(buf, text, len);
975 buf[len] = 0;
976 h = dc.font.ascent + dc.font.descent;
977 y = dc.y + (dc.h / 2) - (h / 2) + dc.font.ascent;
978 x = dc.x + (h / 2);
979 /* shorten text if necessary */
980 while(len && (w = textnw(buf, len)) > dc.w - h)
981 buf[--len] = 0;
982 if(len < olen) {
983 if(len > 1)
984 buf[len - 1] = '.';
985 if(len > 2)
986 buf[len - 2] = '.';
987 if(len > 3)
988 buf[len - 3] = '.';
989 }
990 if(w > dc.w)
991 return; /* too long */
992 gcv.foreground = col[ColFG];
993 if(dc.font.set) {
994 XChangeGC(dpy, dc.gc, GCForeground, &gcv);
995 XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
996 } else {
997 gcv.font = dc.font.xfont->fid;
998 XChangeGC(dpy, dc.gc, GCForeground | GCFont, &gcv);
999 XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
1005 void
1006 drawstatus(void) {
1007 int x;
1008 unsigned long black[ColLast];
1009 black[ColBG] = getcolor("#000000");
1010 black[ColFG] = getcolor("#ffffff");
1012 /* views */
1013 dc.x = dc.y = 0;
1014 dc.w = textw(NAMETAGGED);
1015 drawtext(NAMETAGGED, ( seltag ? dc.sel : dc.norm ));
1017 dc.x += dc.w;
1018 dc.w = BORDERPX;
1019 drawtext(NULL, black);
1021 dc.x += dc.w;
1022 dc.w = textw(NAMEUNTAGGED);
1023 drawtext(NAMEUNTAGGED, ( seltag ? dc.norm : dc.sel ));
1025 dc.x += dc.w;
1026 dc.w = BORDERPX;
1027 drawtext(NULL, black);
1029 /* status text */
1030 x = dc.x + dc.w;
1031 dc.w = textw(stext);
1032 dc.x = sw - dc.w;
1033 if(dc.x < x) {
1034 dc.x = x;
1035 dc.w = sw - x;
1037 drawtext(stext, dc.norm);
1039 /* client title */
1040 if((dc.w = dc.x - x) > bh) {
1041 dc.x = x;
1042 drawtext(sel ? sel->name : NULL, dc.norm);
1044 dc.x += dc.w;
1045 dc.w = BORDERPX;
1046 drawtext(NULL, black);
1049 XCopyArea(dpy, dc.drawable, barwin, dc.gc, 0, 0, sw, bh, 0, 0);
1050 XSync(dpy, False);
1053 unsigned long
1054 getcolor(const char *colstr) {
1055 Colormap cmap = DefaultColormap(dpy, screen);
1056 XColor color;
1058 if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
1059 eprint("error, cannot allocate color '%s'\n", colstr);
1060 return color.pixel;
1063 void
1064 setfont(const char *fontstr) {
1065 char *def, **missing;
1066 int i, n;
1068 missing = NULL;
1069 if(dc.font.set)
1070 XFreeFontSet(dpy, dc.font.set);
1071 dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
1072 if(missing) {
1073 while(n--)
1074 fprintf(stderr, "missing fontset: %s\n", missing[n]);
1075 XFreeStringList(missing);
1077 if(dc.font.set) {
1078 XFontSetExtents *font_extents;
1079 XFontStruct **xfonts;
1080 char **font_names;
1081 dc.font.ascent = dc.font.descent = 0;
1082 font_extents = XExtentsOfFontSet(dc.font.set);
1083 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
1084 for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
1085 if(dc.font.ascent < (*xfonts)->ascent)
1086 dc.font.ascent = (*xfonts)->ascent;
1087 if(dc.font.descent < (*xfonts)->descent)
1088 dc.font.descent = (*xfonts)->descent;
1089 xfonts++;
1091 } else {
1092 if(dc.font.xfont)
1093 XFreeFont(dpy, dc.font.xfont);
1094 dc.font.xfont = NULL;
1095 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr)))
1096 eprint("error, cannot load font: '%s'\n", fontstr);
1097 dc.font.ascent = dc.font.xfont->ascent;
1098 dc.font.descent = dc.font.xfont->descent;
1100 dc.font.height = dc.font.ascent + dc.font.descent;
1103 unsigned int
1104 textw(const char *text) {
1105 return textnw(text, strlen(text)) + dc.font.height;
1118 /* from client.c */
1119 /* static */
1121 static void
1122 detachstack(Client *c) {
1123 Client **tc;
1124 for(tc=&stack; *tc && *tc != c; tc=&(*tc)->snext);
1125 *tc = c->snext;
1128 static void
1129 grabbuttons(Client *c, Bool focused) {
1130 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1132 if(focused) {
1133 XGrabButton(dpy, Button1, MODKEY, c->win, False, BUTTONMASK,
1134 GrabModeAsync, GrabModeSync, None, None);
1135 XGrabButton(dpy, Button1, MODKEY | LockMask, c->win, False, BUTTONMASK,
1136 GrabModeAsync, GrabModeSync, None, None);
1137 XGrabButton(dpy, Button1, MODKEY | numlockmask, c->win, False, BUTTONMASK,
1138 GrabModeAsync, GrabModeSync, None, None);
1139 XGrabButton(dpy, Button1, MODKEY | numlockmask | LockMask, c->win, False, BUTTONMASK,
1140 GrabModeAsync, GrabModeSync, None, None);
1142 XGrabButton(dpy, Button2, MODKEY, c->win, False, BUTTONMASK,
1143 GrabModeAsync, GrabModeSync, None, None);
1144 XGrabButton(dpy, Button2, MODKEY | LockMask, c->win, False, BUTTONMASK,
1145 GrabModeAsync, GrabModeSync, None, None);
1146 XGrabButton(dpy, Button2, MODKEY | numlockmask, c->win, False, BUTTONMASK,
1147 GrabModeAsync, GrabModeSync, None, None);
1148 XGrabButton(dpy, Button2, MODKEY | numlockmask | LockMask, c->win, False, BUTTONMASK,
1149 GrabModeAsync, GrabModeSync, None, None);
1151 XGrabButton(dpy, Button3, MODKEY, c->win, False, BUTTONMASK,
1152 GrabModeAsync, GrabModeSync, None, None);
1153 XGrabButton(dpy, Button3, MODKEY | LockMask, c->win, False, BUTTONMASK,
1154 GrabModeAsync, GrabModeSync, None, None);
1155 XGrabButton(dpy, Button3, MODKEY | numlockmask, c->win, False, BUTTONMASK,
1156 GrabModeAsync, GrabModeSync, None, None);
1157 XGrabButton(dpy, Button3, MODKEY | numlockmask | LockMask, c->win, False, BUTTONMASK,
1158 GrabModeAsync, GrabModeSync, None, None);
1159 } else {
1160 XGrabButton(dpy, AnyButton, AnyModifier, c->win, False, BUTTONMASK,
1161 GrabModeAsync, GrabModeSync, None, None);
1165 static void
1166 setclientstate(Client *c, long state) {
1167 long data[] = {state, None};
1168 XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1169 PropModeReplace, (unsigned char *)data, 2);
1172 static int
1173 xerrordummy(Display *dsply, XErrorEvent *ee) {
1174 return 0;
1179 void
1180 configure(Client *c) {
1181 XEvent synev;
1183 synev.type = ConfigureNotify;
1184 synev.xconfigure.display = dpy;
1185 synev.xconfigure.event = c->win;
1186 synev.xconfigure.window = c->win;
1187 synev.xconfigure.x = c->x;
1188 synev.xconfigure.y = c->y;
1189 synev.xconfigure.width = c->w;
1190 synev.xconfigure.height = c->h;
1191 synev.xconfigure.border_width = c->border;
1192 synev.xconfigure.above = None;
1193 XSendEvent(dpy, c->win, True, NoEventMask, &synev);
1196 void
1197 focus(Client *c) {
1198 if(c && !isvisible(c))
1199 return;
1200 if(sel && sel != c) {
1201 grabbuttons(sel, False);
1202 XSetWindowBorder(dpy, sel->win, dc.norm[ColBG]);
1204 if(c) {
1205 detachstack(c);
1206 c->snext = stack;
1207 stack = c;
1208 grabbuttons(c, True);
1210 sel = c;
1211 drawstatus();
1212 if(!selscreen)
1213 return;
1214 if(c) {
1215 XSetWindowBorder(dpy, c->win, dc.sel[ColBG]);
1216 XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
1217 } else {
1218 XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
1222 Client *
1223 getclient(Window w) {
1224 Client *c;
1226 for(c = clients; c; c = c->next) {
1227 if(c->win == w) {
1228 return c;
1231 return NULL;
1234 Bool
1235 isprotodel(Client *c) {
1236 int i, n;
1237 Atom *protocols;
1238 Bool ret = False;
1240 if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
1241 for(i = 0; !ret && i < n; i++)
1242 if(protocols[i] == wmatom[WMDelete])
1243 ret = True;
1244 XFree(protocols);
1246 return ret;
1249 void
1250 killclient() {
1251 if(!sel)
1252 return;
1253 if(isprotodel(sel))
1254 sendevent(sel->win, wmatom[WMProtocols], wmatom[WMDelete]);
1255 else
1256 XKillClient(dpy, sel->win);
1259 void
1260 manage(Window w, XWindowAttributes *wa) {
1261 Client *c;
1262 Window trans;
1264 c = emallocz(sizeof(Client));
1265 c->tag = True;
1266 c->win = w;
1267 c->x = wa->x;
1268 c->y = wa->y;
1269 c->w = wa->width;
1270 c->h = wa->height;
1271 if(c->w == sw && c->h == sh) {
1272 c->border = 0;
1273 c->x = sx;
1274 c->y = sy;
1275 } else {
1276 c->border = BORDERPX;
1277 if(c->x + c->w + 2 * c->border > wax + waw)
1278 c->x = wax + waw - c->w - 2 * c->border;
1279 if(c->y + c->h + 2 * c->border > way + wah)
1280 c->y = way + wah - c->h - 2 * c->border;
1281 if(c->x < wax)
1282 c->x = wax;
1283 if(c->y < way)
1284 c->y = way;
1286 updatesizehints(c);
1287 XSelectInput(dpy, c->win,
1288 StructureNotifyMask | PropertyChangeMask | EnterWindowMask);
1289 XGetTransientForHint(dpy, c->win, &trans);
1290 grabbuttons(c, False);
1291 XSetWindowBorder(dpy, c->win, dc.norm[ColBG]);
1292 updatetitle(c);
1293 settag(c, getclient(trans));
1294 if(!c->isfloat)
1295 c->isfloat = trans || c->isfixed;
1296 if(clients)
1297 clients->prev = c;
1298 c->next = clients;
1299 c->snext = stack;
1300 stack = clients = c;
1301 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
1302 XMapWindow(dpy, c->win);
1303 setclientstate(c, NormalState);
1304 if(isvisible(c))
1305 focus(c);
1306 arrange();
1309 void
1310 resize(Client *c, Bool sizehints) {
1311 float actual, dx, dy, max, min;
1312 XWindowChanges wc;
1314 if(c->w <= 0 || c->h <= 0)
1315 return;
1316 if(sizehints) {
1317 if(c->minw && c->w < c->minw)
1318 c->w = c->minw;
1319 if(c->minh && c->h < c->minh)
1320 c->h = c->minh;
1321 if(c->maxw && c->w > c->maxw)
1322 c->w = c->maxw;
1323 if(c->maxh && c->h > c->maxh)
1324 c->h = c->maxh;
1325 /* inspired by algorithm from fluxbox */
1326 if(c->minay > 0 && c->maxay && (c->h - c->baseh) > 0) {
1327 dx = (float)(c->w - c->basew);
1328 dy = (float)(c->h - c->baseh);
1329 min = (float)(c->minax) / (float)(c->minay);
1330 max = (float)(c->maxax) / (float)(c->maxay);
1331 actual = dx / dy;
1332 if(max > 0 && min > 0 && actual > 0) {
1333 if(actual < min) {
1334 dy = (dx * min + dy) / (min * min + 1);
1335 dx = dy * min;
1336 c->w = (int)dx + c->basew;
1337 c->h = (int)dy + c->baseh;
1339 else if(actual > max) {
1340 dy = (dx * min + dy) / (max * max + 1);
1341 dx = dy * min;
1342 c->w = (int)dx + c->basew;
1343 c->h = (int)dy + c->baseh;
1347 if(c->incw)
1348 c->w -= (c->w - c->basew) % c->incw;
1349 if(c->inch)
1350 c->h -= (c->h - c->baseh) % c->inch;
1352 if(c->w == sw && c->h == sh)
1353 c->border = 0;
1354 else
1355 c->border = BORDERPX;
1356 /* offscreen appearance fixes */
1357 if(c->x > sw)
1358 c->x = sw - c->w - 2 * c->border;
1359 if(c->y > sh)
1360 c->y = sh - c->h - 2 * c->border;
1361 if(c->x + c->w + 2 * c->border < sx)
1362 c->x = sx;
1363 if(c->y + c->h + 2 * c->border < sy)
1364 c->y = sy;
1365 wc.x = c->x;
1366 wc.y = c->y;
1367 wc.width = c->w;
1368 wc.height = c->h;
1369 wc.border_width = c->border;
1370 XConfigureWindow(dpy, c->win, CWX | CWY | CWWidth | CWHeight | CWBorderWidth, &wc);
1371 configure(c);
1372 XSync(dpy, False);
1375 void
1376 updatesizehints(Client *c) {
1377 long msize;
1378 XSizeHints size;
1380 if(!XGetWMNormalHints(dpy, c->win, &size, &msize) || !size.flags)
1381 size.flags = PSize;
1382 c->flags = size.flags;
1383 if(c->flags & PBaseSize) {
1384 c->basew = size.base_width;
1385 c->baseh = size.base_height;
1386 } else {
1387 c->basew = c->baseh = 0;
1389 if(c->flags & PResizeInc) {
1390 c->incw = size.width_inc;
1391 c->inch = size.height_inc;
1392 } else {
1393 c->incw = c->inch = 0;
1395 if(c->flags & PMaxSize) {
1396 c->maxw = size.max_width;
1397 c->maxh = size.max_height;
1398 } else {
1399 c->maxw = c->maxh = 0;
1401 if(c->flags & PMinSize) {
1402 c->minw = size.min_width;
1403 c->minh = size.min_height;
1404 } else {
1405 c->minw = c->minh = 0;
1407 if(c->flags & PAspect) {
1408 c->minax = size.min_aspect.x;
1409 c->minay = size.min_aspect.y;
1410 c->maxax = size.max_aspect.x;
1411 c->maxay = size.max_aspect.y;
1412 } else {
1413 c->minax = c->minay = c->maxax = c->maxay = 0;
1415 c->isfixed = (c->maxw && c->minw && c->maxh && c->minh &&
1416 c->maxw == c->minw && c->maxh == c->minh);
1419 void
1420 updatetitle(Client *c) {
1421 char **list = NULL;
1422 int n;
1423 XTextProperty name;
1425 name.nitems = 0;
1426 c->name[0] = 0;
1427 XGetTextProperty(dpy, c->win, &name, netatom[NetWMName]);
1428 if(!name.nitems)
1429 XGetWMName(dpy, c->win, &name);
1430 if(!name.nitems)
1431 return;
1432 if(name.encoding == XA_STRING)
1433 strncpy(c->name, (char *)name.value, sizeof c->name);
1434 else {
1435 if(XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success && n > 0 && *list) {
1436 strncpy(c->name, *list, sizeof c->name);
1437 XFreeStringList(list);
1440 XFree(name.value);
1443 void
1444 unmanage(Client *c) {
1445 Client *nc;
1447 /* The server grab construct avoids race conditions. */
1448 XGrabServer(dpy);
1449 XSetErrorHandler(xerrordummy);
1450 detach(c);
1451 detachstack(c);
1452 if(sel == c) {
1453 for(nc = stack; nc && !isvisible(nc); nc = nc->snext);
1454 focus(nc);
1456 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1457 setclientstate(c, WithdrawnState);
1458 free(c);
1459 XSync(dpy, False);
1460 XSetErrorHandler(xerror);
1461 XUngrabServer(dpy);
1462 arrange();
1483 /* static */
1486 static void
1487 cleanup(void) {
1488 close(STDIN_FILENO);
1489 while(stack) {
1490 resize(stack, True);
1491 unmanage(stack);
1493 if(dc.font.set)
1494 XFreeFontSet(dpy, dc.font.set);
1495 else
1496 XFreeFont(dpy, dc.font.xfont);
1497 XUngrabKey(dpy, AnyKey, AnyModifier, root);
1498 XFreePixmap(dpy, dc.drawable);
1499 XFreeGC(dpy, dc.gc);
1500 XDestroyWindow(dpy, barwin);
1501 XFreeCursor(dpy, cursor[CurNormal]);
1502 XFreeCursor(dpy, cursor[CurResize]);
1503 XFreeCursor(dpy, cursor[CurMove]);
1504 XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime);
1505 XSync(dpy, False);
1508 static void
1509 scan(void) {
1510 unsigned int i, num;
1511 Window *wins, d1, d2;
1512 XWindowAttributes wa;
1514 wins = NULL;
1515 if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1516 for(i = 0; i < num; i++) {
1517 if(!XGetWindowAttributes(dpy, wins[i], &wa))
1518 continue;
1519 if(wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1520 continue;
1521 if(wa.map_state == IsViewable)
1522 manage(wins[i], &wa);
1525 if(wins)
1526 XFree(wins);
1529 static void
1530 setup(void) {
1531 int i, j;
1532 unsigned int mask;
1533 Window w;
1534 XModifierKeymap *modmap;
1535 XSetWindowAttributes wa;
1537 /* init atoms */
1538 wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1539 wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1540 wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1541 netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1542 netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1543 XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1544 PropModeReplace, (unsigned char *) netatom, NetLast);
1545 /* init cursors */
1546 cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1547 cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1548 cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1549 /* init modifier map */
1550 numlockmask = 0;
1551 modmap = XGetModifierMapping(dpy);
1552 for (i = 0; i < 8; i++) {
1553 for (j = 0; j < modmap->max_keypermod; j++) {
1554 if(modmap->modifiermap[i * modmap->max_keypermod + j] == XKeysymToKeycode(dpy, XK_Num_Lock))
1555 numlockmask = (1 << i);
1558 XFreeModifiermap(modmap);
1559 /* select for events */
1560 wa.event_mask = SubstructureRedirectMask | SubstructureNotifyMask
1561 | EnterWindowMask | LeaveWindowMask;
1562 wa.cursor = cursor[CurNormal];
1563 XChangeWindowAttributes(dpy, root, CWEventMask | CWCursor, &wa);
1564 grabkeys();
1565 seltag = True;
1566 /* style */
1567 dc.norm[ColBG] = getcolor(NORMBGCOLOR);
1568 dc.norm[ColFG] = getcolor(NORMFGCOLOR);
1569 dc.sel[ColBG] = getcolor(SELBGCOLOR);
1570 dc.sel[ColFG] = getcolor(SELFGCOLOR);
1571 setfont(FONT);
1572 /* geometry */
1573 sx = sy = 0;
1574 sw = DisplayWidth(dpy, screen);
1575 sh = DisplayHeight(dpy, screen);
1576 nmaster = NMASTER;
1577 /* bar */
1578 dc.h = bh = dc.font.height + 2;
1579 wa.override_redirect = 1;
1580 wa.background_pixmap = ParentRelative;
1581 wa.event_mask = ButtonPressMask | ExposureMask;
1582 barwin = XCreateWindow(dpy, root, sx, sy, sw, bh, 0,
1583 DefaultDepth(dpy, screen), CopyFromParent, DefaultVisual(dpy, screen),
1584 CWOverrideRedirect | CWBackPixmap | CWEventMask, &wa);
1585 XDefineCursor(dpy, barwin, cursor[CurNormal]);
1586 XMapRaised(dpy, barwin);
1587 strcpy(stext, "dwm-"VERSION);
1588 /* windowarea */
1589 wax = sx;
1590 way = sy + bh;
1591 wah = sh - bh;
1592 waw = sw;
1593 /* pixmap for everything */
1594 dc.drawable = XCreatePixmap(dpy, root, sw, bh, DefaultDepth(dpy, screen));
1595 dc.gc = XCreateGC(dpy, root, 0, 0);
1596 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
1597 /* multihead support */
1598 selscreen = XQueryPointer(dpy, root, &w, &w, &i, &i, &i, &i, &mask);
1601 /*
1602 * Startup Error handler to check if another window manager
1603 * is already running.
1604 */
1605 static int
1606 xerrorstart(Display *dsply, XErrorEvent *ee) {
1607 otherwm = True;
1608 return -1;
1613 void
1614 sendevent(Window w, Atom a, long value) {
1615 XEvent e;
1617 e.type = ClientMessage;
1618 e.xclient.window = w;
1619 e.xclient.message_type = a;
1620 e.xclient.format = 32;
1621 e.xclient.data.l[0] = value;
1622 e.xclient.data.l[1] = CurrentTime;
1623 XSendEvent(dpy, w, False, NoEventMask, &e);
1624 XSync(dpy, False);
1627 void
1628 quit() {
1629 readin = running = False;
1632 /* There's no way to check accesses to destroyed windows, thus those cases are
1633 * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
1634 * default error handler, which may call exit.
1635 */
1636 int
1637 xerror(Display *dpy, XErrorEvent *ee) {
1638 if(ee->error_code == BadWindow
1639 || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1640 || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1641 || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1642 || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1643 || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1644 || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1645 || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1646 return 0;
1647 fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1648 ee->request_code, ee->error_code);
1649 return xerrorxlib(dpy, ee); /* may call exit */
1652 int
1653 main(int argc, char *argv[]) {
1654 char *p;
1655 int r, xfd;
1656 fd_set rd;
1658 if(argc == 2 && !strncmp("-v", argv[1], 3)) {
1659 fputs("dwm-"VERSION", (C)opyright MMVI-MMVII Anselm R. Garbe\n", stdout);
1660 exit(EXIT_SUCCESS);
1661 } else if(argc != 1) {
1662 eprint("usage: dwm [-v]\n");
1664 setlocale(LC_CTYPE, "");
1665 dpy = XOpenDisplay(0);
1666 if(!dpy) {
1667 eprint("dwm: cannot open display\n");
1669 xfd = ConnectionNumber(dpy);
1670 screen = DefaultScreen(dpy);
1671 root = RootWindow(dpy, screen);
1672 otherwm = False;
1673 XSetErrorHandler(xerrorstart);
1674 /* this causes an error if some other window manager is running */
1675 XSelectInput(dpy, root, SubstructureRedirectMask);
1676 XSync(dpy, False);
1677 if(otherwm) {
1678 eprint("dwm: another window manager is already running\n");
1681 XSync(dpy, False);
1682 XSetErrorHandler(NULL);
1683 xerrorxlib = XSetErrorHandler(xerror);
1684 XSync(dpy, False);
1685 setup();
1686 drawstatus();
1687 scan();
1689 /* main event loop, also reads status text from stdin */
1690 XSync(dpy, False);
1691 procevent();
1692 readin = True;
1693 while(running) {
1694 FD_ZERO(&rd);
1695 if(readin)
1696 FD_SET(STDIN_FILENO, &rd);
1697 FD_SET(xfd, &rd);
1698 if(select(xfd + 1, &rd, NULL, NULL, NULL) == -1) {
1699 if(errno == EINTR)
1700 continue;
1701 eprint("select failed\n");
1703 if(FD_ISSET(STDIN_FILENO, &rd)) {
1704 switch(r = read(STDIN_FILENO, stext, sizeof stext - 1)) {
1705 case -1:
1706 strncpy(stext, strerror(errno), sizeof stext - 1);
1707 stext[sizeof stext - 1] = '\0';
1708 readin = False;
1709 break;
1710 case 0:
1711 strncpy(stext, "EOF", 4);
1712 readin = False;
1713 break;
1714 default:
1715 for(stext[r] = '\0', p = stext + strlen(stext) - 1; p >= stext && *p == '\n'; *p-- = '\0');
1716 for(; p >= stext && *p != '\n'; --p);
1717 if(p > stext)
1718 strncpy(stext, p + 1, sizeof stext);
1720 drawstatus();
1722 if(FD_ISSET(xfd, &rd))
1723 procevent();
1725 cleanup();
1726 XCloseDisplay(dpy);
1727 return 0;