aewl

view aewl.c @ 769:49aa8ccceefa

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