aewl

view aewl.c @ 770:33cec4282120

removed notice about code by mitch, cause everything special about it is removed now
author meillo@marmaro.de
date Fri, 05 Dec 2008 21:45:42 +0100
parents 49aa8ccceefa
children 59a6f0ba5478
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 void
321 domax(void) {
322 Client *c;
324 for(c = clients; c; c = c->next) {
325 if(isvisible(c)) {
326 if(c->isfloat) {
327 resize(c, True);
328 continue;
329 }
330 c->ismax = True;
331 c->x = wax;
332 c->y = way;
333 c->w = waw - 2 * BORDERPX;
334 c->h = wah - 2 * BORDERPX;
335 resize(c, False);
336 } else {
337 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
338 }
339 }
340 if(!sel || !isvisible(sel)) {
341 for(c = stack; c && !isvisible(c); c = c->snext);
342 focus(c);
343 }
344 restack();
345 }
347 void
348 focusnext() {
349 Client *c;
351 if(!sel)
352 return;
353 if(!(c = getnext(sel->next)))
354 c = getnext(clients);
355 if(c) {
356 focus(c);
357 restack();
358 }
359 }
361 void
362 incnmaster() {
363 if(wah / (nmaster + 1) <= 2 * BORDERPX)
364 return;
365 nmaster++;
366 if(sel)
367 arrange();
368 else
369 drawstatus();
370 }
372 void
373 decnmaster() {
374 if(nmaster <= 1)
375 return;
376 nmaster--;
377 if(sel)
378 arrange();
379 else
380 drawstatus();
381 }
383 Bool
384 isvisible(Client *c) {
385 return (c->tag == seltag);
386 }
388 void
389 restack(void) {
390 Client *c;
391 XEvent ev;
393 drawstatus();
394 if(!sel)
395 return;
396 if(sel->isfloat)
397 XRaiseWindow(dpy, sel->win);
399 if(!sel->isfloat)
400 XLowerWindow(dpy, sel->win);
401 for(c = nexttiled(clients); c; c = nexttiled(c->next)) {
402 if(c == sel)
403 continue;
404 XLowerWindow(dpy, c->win);
405 }
407 XSync(dpy, False);
408 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
409 }
411 void
412 togglefloat() {
413 if (!sel)
414 return;
415 sel->isfloat = !sel->isfloat;
416 arrange();
417 }
419 void
420 togglemode() {
421 /* only toggle between tile and max - float is just available through togglefloat */
422 arrange = (arrange == dotile) ? domax : dotile;
423 if(sel)
424 arrange();
425 else
426 drawstatus();
427 }
429 void
430 toggleview() {
431 seltag = !seltag;
432 arrange();
433 }
435 void
436 zoom() {
437 unsigned int n;
438 Client *c;
440 if(!sel)
441 return;
442 if(sel->isfloat) {
443 togglemax(sel);
444 return;
445 }
446 for(n = 0, c = nexttiled(clients); c; c = nexttiled(c->next))
447 n++;
449 if((c = sel) == nexttiled(clients))
450 if(!(c = nexttiled(c->next)))
451 return;
452 detach(c);
453 if(clients)
454 clients->prev = c;
455 c->next = clients;
456 clients = c;
457 focus(c);
458 arrange();
459 }
476 /* from util.c */
479 void *
480 emallocz(unsigned int size) {
481 void *res = calloc(1, size);
483 if(!res)
484 eprint("fatal: could not malloc() %u bytes\n", size);
485 return res;
486 }
488 void
489 eprint(const char *errstr, ...) {
490 va_list ap;
492 va_start(ap, errstr);
493 vfprintf(stderr, errstr, ap);
494 va_end(ap);
495 exit(EXIT_FAILURE);
496 }
498 void
499 spawn(const char* cmd) {
500 static char *shell = NULL;
502 if(!cmd)
503 return;
504 if(!(shell = getenv("SHELL")))
505 shell = "/bin/sh";
506 /* The double-fork construct avoids zombie processes and keeps the code
507 * clean from stupid signal handlers. */
508 if(fork() == 0) {
509 if(fork() == 0) {
510 if(dpy)
511 close(ConnectionNumber(dpy));
512 setsid();
513 execl(shell, shell, "-c", cmd, (char *)NULL);
514 fprintf(stderr, "dwm: execl '%s -c %s'", shell, cmd);
515 perror(" failed");
516 }
517 exit(0);
518 }
519 wait(0);
520 }
534 /* from tag.c */
536 /* static */
538 Client *
539 getnext(Client *c) {
540 while(c && !isvisible(c)) {
541 c = c->next;
542 }
543 return c;
544 }
546 void
547 settag(Client *c, Client *trans) {
548 unsigned int i;
549 XClassHint ch = { 0 };
551 if(trans) {
552 c->tag = trans->tag;
553 return;
554 }
555 c->tag = seltag; /* default */
556 XGetClassHint(dpy, c->win, &ch);
557 len = sizeof rule / sizeof rule[0];
558 for(i = 0; i < len; i++) {
559 if((rule[i].title && strstr(c->name, rule[i].title))
560 || (ch.res_class && rule[i].class && strstr(ch.res_class, rule[i].class))
561 || (ch.res_name && rule[i].instance && strstr(ch.res_name, rule[i].instance))) {
562 c->isfloat = rule[i].isfloat;
563 if (rule[i].tag < 0) {
564 c->tag = seltag;
565 } else if (rule[i].tag) {
566 c->tag = True;
567 } else {
568 c->tag = False;
569 }
570 break;
571 }
572 }
573 if(ch.res_class)
574 XFree(ch.res_class);
575 if(ch.res_name)
576 XFree(ch.res_name);
577 }
579 void
580 toggletag() {
581 if(!sel)
582 return;
583 sel->tag = !sel->tag;
584 toggleview();
585 }
603 /* from event.c */
604 /* static */
606 KEYS
610 static void
611 movemouse(Client *c) {
612 int x1, y1, ocx, ocy, di;
613 unsigned int dui;
614 Window dummy;
615 XEvent ev;
617 ocx = c->x;
618 ocy = c->y;
619 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
620 None, cursor[CurMove], CurrentTime) != GrabSuccess)
621 return;
622 c->ismax = False;
623 XQueryPointer(dpy, root, &dummy, &dummy, &x1, &y1, &di, &di, &dui);
624 for(;;) {
625 XMaskEvent(dpy, MOUSEMASK | ExposureMask | SubstructureRedirectMask, &ev);
626 switch (ev.type) {
627 case ButtonRelease:
628 resize(c, True);
629 XUngrabPointer(dpy, CurrentTime);
630 return;
631 case ConfigureRequest:
632 case Expose:
633 case MapRequest:
634 handler[ev.type](&ev);
635 break;
636 case MotionNotify:
637 XSync(dpy, False);
638 c->x = ocx + (ev.xmotion.x - x1);
639 c->y = ocy + (ev.xmotion.y - y1);
640 if(abs(wax + c->x) < SNAP)
641 c->x = wax;
642 else if(abs((wax + waw) - (c->x + c->w + 2 * c->border)) < SNAP)
643 c->x = wax + waw - c->w - 2 * c->border;
644 if(abs(way - c->y) < SNAP)
645 c->y = way;
646 else if(abs((way + wah) - (c->y + c->h + 2 * c->border)) < SNAP)
647 c->y = way + wah - c->h - 2 * c->border;
648 resize(c, False);
649 break;
650 }
651 }
652 }
654 static void
655 resizemouse(Client *c) {
656 int ocx, ocy;
657 int nw, nh;
658 XEvent ev;
660 ocx = c->x;
661 ocy = c->y;
662 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
663 None, cursor[CurResize], CurrentTime) != GrabSuccess)
664 return;
665 c->ismax = False;
666 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->border - 1, c->h + c->border - 1);
667 for(;;) {
668 XMaskEvent(dpy, MOUSEMASK | ExposureMask | SubstructureRedirectMask , &ev);
669 switch(ev.type) {
670 case ButtonRelease:
671 resize(c, True);
672 XUngrabPointer(dpy, CurrentTime);
673 return;
674 case ConfigureRequest:
675 case Expose:
676 case MapRequest:
677 handler[ev.type](&ev);
678 break;
679 case MotionNotify:
680 XSync(dpy, False);
681 nw = ev.xmotion.x - ocx - 2 * c->border + 1;
682 c->w = nw > 0 ? nw : 1;
683 nh = ev.xmotion.y - ocy - 2 * c->border + 1;
684 c->h = nh > 0 ? nh : 1;
685 resize(c, True);
686 break;
687 }
688 }
689 }
691 static void
692 buttonpress(XEvent *e) {
693 Client *c;
694 XButtonPressedEvent *ev = &e->xbutton;
696 if(barwin == ev->window) {
697 return;
698 }
699 if((c = getclient(ev->window))) {
700 focus(c);
701 if(CLEANMASK(ev->state) != MODKEY)
702 return;
703 if(ev->button == Button1 && c->isfloat) {
704 restack();
705 movemouse(c);
706 } else if(ev->button == Button3 && c->isfloat && !c->isfixed) {
707 restack();
708 resizemouse(c);
709 }
710 }
711 }
713 static void
714 configurerequest(XEvent *e) {
715 unsigned long newmask;
716 Client *c;
717 XConfigureRequestEvent *ev = &e->xconfigurerequest;
718 XWindowChanges wc;
720 if((c = getclient(ev->window))) {
721 c->ismax = False;
722 if(ev->value_mask & CWX)
723 c->x = ev->x;
724 if(ev->value_mask & CWY)
725 c->y = ev->y;
726 if(ev->value_mask & CWWidth)
727 c->w = ev->width;
728 if(ev->value_mask & CWHeight)
729 c->h = ev->height;
730 if(ev->value_mask & CWBorderWidth)
731 c->border = ev->border_width;
732 wc.x = c->x;
733 wc.y = c->y;
734 wc.width = c->w;
735 wc.height = c->h;
736 newmask = ev->value_mask & (~(CWSibling | CWStackMode | CWBorderWidth));
737 if(newmask)
738 XConfigureWindow(dpy, c->win, newmask, &wc);
739 else
740 configure(c);
741 XSync(dpy, False);
742 if(c->isfloat) {
743 resize(c, False);
744 if(!isvisible(c))
745 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
746 }
747 else
748 arrange();
749 } else {
750 wc.x = ev->x;
751 wc.y = ev->y;
752 wc.width = ev->width;
753 wc.height = ev->height;
754 wc.border_width = ev->border_width;
755 wc.sibling = ev->above;
756 wc.stack_mode = ev->detail;
757 XConfigureWindow(dpy, ev->window, ev->value_mask, &wc);
758 XSync(dpy, False);
759 }
760 }
762 static void
763 destroynotify(XEvent *e) {
764 Client *c;
765 XDestroyWindowEvent *ev = &e->xdestroywindow;
767 if((c = getclient(ev->window)))
768 unmanage(c);
769 }
771 static void
772 enternotify(XEvent *e) {
773 Client *c;
774 XCrossingEvent *ev = &e->xcrossing;
776 if(ev->mode != NotifyNormal || ev->detail == NotifyInferior)
777 return;
778 if((c = getclient(ev->window)) && isvisible(c))
779 focus(c);
780 else if(ev->window == root) {
781 selscreen = True;
782 for(c = stack; c && !isvisible(c); c = c->snext);
783 focus(c);
784 }
785 }
787 static void
788 expose(XEvent *e) {
789 XExposeEvent *ev = &e->xexpose;
791 if(ev->count == 0) {
792 if(barwin == ev->window)
793 drawstatus();
794 }
795 }
797 static void
798 keypress(XEvent *e) {
799 static unsigned int len = sizeof key / sizeof key[0];
800 unsigned int i;
801 KeySym keysym;
802 XKeyEvent *ev = &e->xkey;
804 keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
805 for(i = 0; i < len; i++) {
806 if(keysym == key[i].keysym && CLEANMASK(key[i].mod) == CLEANMASK(ev->state)) {
807 if(key[i].func)
808 key[i].func(key[i].cmd);
809 }
810 }
811 }
813 static void
814 leavenotify(XEvent *e) {
815 XCrossingEvent *ev = &e->xcrossing;
817 if((ev->window == root) && !ev->same_screen) {
818 selscreen = False;
819 focus(NULL);
820 }
821 }
823 static void
824 mappingnotify(XEvent *e) {
825 XMappingEvent *ev = &e->xmapping;
827 XRefreshKeyboardMapping(ev);
828 if(ev->request == MappingKeyboard)
829 grabkeys();
830 }
832 static void
833 maprequest(XEvent *e) {
834 static XWindowAttributes wa;
835 XMapRequestEvent *ev = &e->xmaprequest;
837 if(!XGetWindowAttributes(dpy, ev->window, &wa))
838 return;
839 if(wa.override_redirect) {
840 XSelectInput(dpy, ev->window,
841 (StructureNotifyMask | PropertyChangeMask));
842 return;
843 }
844 if(!getclient(ev->window))
845 manage(ev->window, &wa);
846 }
848 static void
849 propertynotify(XEvent *e) {
850 Client *c;
851 Window trans;
852 XPropertyEvent *ev = &e->xproperty;
854 if(ev->state == PropertyDelete)
855 return; /* ignore */
856 if((c = getclient(ev->window))) {
857 switch (ev->atom) {
858 default: break;
859 case XA_WM_TRANSIENT_FOR:
860 XGetTransientForHint(dpy, c->win, &trans);
861 if(!c->isfloat && (c->isfloat = (trans != 0)))
862 arrange();
863 break;
864 case XA_WM_NORMAL_HINTS:
865 updatesizehints(c);
866 break;
867 }
868 if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
869 updatetitle(c);
870 if(c == sel)
871 drawstatus();
872 }
873 }
874 }
876 static void
877 unmapnotify(XEvent *e) {
878 Client *c;
879 XUnmapEvent *ev = &e->xunmap;
881 if((c = getclient(ev->window)))
882 unmanage(c);
883 }
887 void (*handler[LASTEvent]) (XEvent *) = {
888 [ButtonPress] = buttonpress,
889 [ConfigureRequest] = configurerequest,
890 [DestroyNotify] = destroynotify,
891 [EnterNotify] = enternotify,
892 [LeaveNotify] = leavenotify,
893 [Expose] = expose,
894 [KeyPress] = keypress,
895 [MappingNotify] = mappingnotify,
896 [MapRequest] = maprequest,
897 [PropertyNotify] = propertynotify,
898 [UnmapNotify] = unmapnotify
899 };
901 void
902 grabkeys(void) {
903 static unsigned int len = sizeof key / sizeof key[0];
904 unsigned int i;
905 KeyCode code;
907 XUngrabKey(dpy, AnyKey, AnyModifier, root);
908 for(i = 0; i < len; i++) {
909 code = XKeysymToKeycode(dpy, key[i].keysym);
910 XGrabKey(dpy, code, key[i].mod, root, True,
911 GrabModeAsync, GrabModeAsync);
912 XGrabKey(dpy, code, key[i].mod | LockMask, root, True,
913 GrabModeAsync, GrabModeAsync);
914 XGrabKey(dpy, code, key[i].mod | numlockmask, root, True,
915 GrabModeAsync, GrabModeAsync);
916 XGrabKey(dpy, code, key[i].mod | numlockmask | LockMask, root, True,
917 GrabModeAsync, GrabModeAsync);
918 }
919 }
921 void
922 procevent(void) {
923 XEvent ev;
925 while(XPending(dpy)) {
926 XNextEvent(dpy, &ev);
927 if(handler[ev.type])
928 (handler[ev.type])(&ev); /* call handler */
929 }
930 }
946 /* from draw.c */
947 /* static */
949 static unsigned int
950 textnw(const char *text, unsigned int len) {
951 XRectangle r;
953 if(dc.font.set) {
954 XmbTextExtents(dc.font.set, text, len, NULL, &r);
955 return r.width;
956 }
957 return XTextWidth(dc.font.xfont, text, len);
958 }
960 static void
961 drawtext(const char *text, unsigned long col[ColLast]) {
962 int x, y, w, h;
963 static char buf[256];
964 unsigned int len, olen;
965 XGCValues gcv;
966 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
968 XSetForeground(dpy, dc.gc, col[ColBG]);
969 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
970 if(!text)
971 return;
972 w = 0;
973 olen = len = strlen(text);
974 if(len >= sizeof buf)
975 len = sizeof buf - 1;
976 memcpy(buf, text, len);
977 buf[len] = 0;
978 h = dc.font.ascent + dc.font.descent;
979 y = dc.y + (dc.h / 2) - (h / 2) + dc.font.ascent;
980 x = dc.x + (h / 2);
981 /* shorten text if necessary */
982 while(len && (w = textnw(buf, len)) > dc.w - h)
983 buf[--len] = 0;
984 if(len < olen) {
985 if(len > 1)
986 buf[len - 1] = '.';
987 if(len > 2)
988 buf[len - 2] = '.';
989 if(len > 3)
990 buf[len - 3] = '.';
991 }
992 if(w > dc.w)
993 return; /* too long */
994 gcv.foreground = col[ColFG];
995 if(dc.font.set) {
996 XChangeGC(dpy, dc.gc, GCForeground, &gcv);
997 XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
998 } else {
999 gcv.font = dc.font.xfont->fid;
1000 XChangeGC(dpy, dc.gc, GCForeground | GCFont, &gcv);
1001 XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
1007 void
1008 drawstatus(void) {
1009 int x;
1011 dc.x = dc.y = 0;
1012 dc.w = textw(NAMETAGGED);
1013 drawtext(NAMETAGGED, ( seltag ? dc.sel : dc.norm ));
1014 dc.x += dc.w + 1;
1015 dc.w = textw(NAMEUNTAGGED);
1016 drawtext(NAMEUNTAGGED, ( seltag ? dc.norm : dc.sel ));
1017 dc.x += dc.w + 1;
1018 dc.w = bmw;
1019 drawtext("", dc.norm);
1020 x = dc.x + dc.w;
1021 dc.w = textw(stext);
1022 dc.x = sw - dc.w;
1023 if(dc.x < x) {
1024 dc.x = x;
1025 dc.w = sw - x;
1027 drawtext(stext, dc.norm);
1028 if((dc.w = dc.x - x) > bh) {
1029 dc.x = x;
1030 drawtext(sel ? sel->name : NULL, dc.norm);
1032 XCopyArea(dpy, dc.drawable, barwin, dc.gc, 0, 0, sw, bh, 0, 0);
1033 XSync(dpy, False);
1036 unsigned long
1037 getcolor(const char *colstr) {
1038 Colormap cmap = DefaultColormap(dpy, screen);
1039 XColor color;
1041 if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
1042 eprint("error, cannot allocate color '%s'\n", colstr);
1043 return color.pixel;
1046 void
1047 setfont(const char *fontstr) {
1048 char *def, **missing;
1049 int i, n;
1051 missing = NULL;
1052 if(dc.font.set)
1053 XFreeFontSet(dpy, dc.font.set);
1054 dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
1055 if(missing) {
1056 while(n--)
1057 fprintf(stderr, "missing fontset: %s\n", missing[n]);
1058 XFreeStringList(missing);
1060 if(dc.font.set) {
1061 XFontSetExtents *font_extents;
1062 XFontStruct **xfonts;
1063 char **font_names;
1064 dc.font.ascent = dc.font.descent = 0;
1065 font_extents = XExtentsOfFontSet(dc.font.set);
1066 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
1067 for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
1068 if(dc.font.ascent < (*xfonts)->ascent)
1069 dc.font.ascent = (*xfonts)->ascent;
1070 if(dc.font.descent < (*xfonts)->descent)
1071 dc.font.descent = (*xfonts)->descent;
1072 xfonts++;
1074 } else {
1075 if(dc.font.xfont)
1076 XFreeFont(dpy, dc.font.xfont);
1077 dc.font.xfont = NULL;
1078 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr)))
1079 eprint("error, cannot load font: '%s'\n", fontstr);
1080 dc.font.ascent = dc.font.xfont->ascent;
1081 dc.font.descent = dc.font.xfont->descent;
1083 dc.font.height = dc.font.ascent + dc.font.descent;
1086 unsigned int
1087 textw(const char *text) {
1088 return textnw(text, strlen(text)) + dc.font.height;
1101 /* from client.c */
1102 /* static */
1104 static void
1105 detachstack(Client *c) {
1106 Client **tc;
1107 for(tc=&stack; *tc && *tc != c; tc=&(*tc)->snext);
1108 *tc = c->snext;
1111 static void
1112 grabbuttons(Client *c, Bool focused) {
1113 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1115 if(focused) {
1116 XGrabButton(dpy, Button1, MODKEY, c->win, False, BUTTONMASK,
1117 GrabModeAsync, GrabModeSync, None, None);
1118 XGrabButton(dpy, Button1, MODKEY | LockMask, c->win, False, BUTTONMASK,
1119 GrabModeAsync, GrabModeSync, None, None);
1120 XGrabButton(dpy, Button1, MODKEY | numlockmask, c->win, False, BUTTONMASK,
1121 GrabModeAsync, GrabModeSync, None, None);
1122 XGrabButton(dpy, Button1, MODKEY | numlockmask | LockMask, c->win, False, BUTTONMASK,
1123 GrabModeAsync, GrabModeSync, None, None);
1125 XGrabButton(dpy, Button2, MODKEY, c->win, False, BUTTONMASK,
1126 GrabModeAsync, GrabModeSync, None, None);
1127 XGrabButton(dpy, Button2, MODKEY | LockMask, c->win, False, BUTTONMASK,
1128 GrabModeAsync, GrabModeSync, None, None);
1129 XGrabButton(dpy, Button2, MODKEY | numlockmask, c->win, False, BUTTONMASK,
1130 GrabModeAsync, GrabModeSync, None, None);
1131 XGrabButton(dpy, Button2, MODKEY | numlockmask | LockMask, c->win, False, BUTTONMASK,
1132 GrabModeAsync, GrabModeSync, None, None);
1134 XGrabButton(dpy, Button3, MODKEY, c->win, False, BUTTONMASK,
1135 GrabModeAsync, GrabModeSync, None, None);
1136 XGrabButton(dpy, Button3, MODKEY | LockMask, c->win, False, BUTTONMASK,
1137 GrabModeAsync, GrabModeSync, None, None);
1138 XGrabButton(dpy, Button3, MODKEY | numlockmask, c->win, False, BUTTONMASK,
1139 GrabModeAsync, GrabModeSync, None, None);
1140 XGrabButton(dpy, Button3, MODKEY | numlockmask | LockMask, c->win, False, BUTTONMASK,
1141 GrabModeAsync, GrabModeSync, None, None);
1142 } else {
1143 XGrabButton(dpy, AnyButton, AnyModifier, c->win, False, BUTTONMASK,
1144 GrabModeAsync, GrabModeSync, None, None);
1148 static void
1149 setclientstate(Client *c, long state) {
1150 long data[] = {state, None};
1151 XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1152 PropModeReplace, (unsigned char *)data, 2);
1155 static int
1156 xerrordummy(Display *dsply, XErrorEvent *ee) {
1157 return 0;
1162 void
1163 configure(Client *c) {
1164 XEvent synev;
1166 synev.type = ConfigureNotify;
1167 synev.xconfigure.display = dpy;
1168 synev.xconfigure.event = c->win;
1169 synev.xconfigure.window = c->win;
1170 synev.xconfigure.x = c->x;
1171 synev.xconfigure.y = c->y;
1172 synev.xconfigure.width = c->w;
1173 synev.xconfigure.height = c->h;
1174 synev.xconfigure.border_width = c->border;
1175 synev.xconfigure.above = None;
1176 XSendEvent(dpy, c->win, True, NoEventMask, &synev);
1179 void
1180 focus(Client *c) {
1181 if(c && !isvisible(c))
1182 return;
1183 if(sel && sel != c) {
1184 grabbuttons(sel, False);
1185 XSetWindowBorder(dpy, sel->win, dc.norm[ColBG]);
1187 if(c) {
1188 detachstack(c);
1189 c->snext = stack;
1190 stack = c;
1191 grabbuttons(c, True);
1193 sel = c;
1194 drawstatus();
1195 if(!selscreen)
1196 return;
1197 if(c) {
1198 XSetWindowBorder(dpy, c->win, dc.sel[ColBG]);
1199 XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
1200 } else {
1201 XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
1205 Client *
1206 getclient(Window w) {
1207 Client *c;
1209 for(c = clients; c; c = c->next) {
1210 if(c->win == w) {
1211 return c;
1214 return NULL;
1217 Bool
1218 isprotodel(Client *c) {
1219 int i, n;
1220 Atom *protocols;
1221 Bool ret = False;
1223 if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
1224 for(i = 0; !ret && i < n; i++)
1225 if(protocols[i] == wmatom[WMDelete])
1226 ret = True;
1227 XFree(protocols);
1229 return ret;
1232 void
1233 killclient() {
1234 if(!sel)
1235 return;
1236 if(isprotodel(sel))
1237 sendevent(sel->win, wmatom[WMProtocols], wmatom[WMDelete]);
1238 else
1239 XKillClient(dpy, sel->win);
1242 void
1243 manage(Window w, XWindowAttributes *wa) {
1244 Client *c;
1245 Window trans;
1247 c = emallocz(sizeof(Client));
1248 c->tag = True;
1249 c->win = w;
1250 c->x = wa->x;
1251 c->y = wa->y;
1252 c->w = wa->width;
1253 c->h = wa->height;
1254 if(c->w == sw && c->h == sh) {
1255 c->border = 0;
1256 c->x = sx;
1257 c->y = sy;
1258 } else {
1259 c->border = BORDERPX;
1260 if(c->x + c->w + 2 * c->border > wax + waw)
1261 c->x = wax + waw - c->w - 2 * c->border;
1262 if(c->y + c->h + 2 * c->border > way + wah)
1263 c->y = way + wah - c->h - 2 * c->border;
1264 if(c->x < wax)
1265 c->x = wax;
1266 if(c->y < way)
1267 c->y = way;
1269 updatesizehints(c);
1270 XSelectInput(dpy, c->win,
1271 StructureNotifyMask | PropertyChangeMask | EnterWindowMask);
1272 XGetTransientForHint(dpy, c->win, &trans);
1273 grabbuttons(c, False);
1274 XSetWindowBorder(dpy, c->win, dc.norm[ColBG]);
1275 updatetitle(c);
1276 settag(c, getclient(trans));
1277 if(!c->isfloat)
1278 c->isfloat = trans || c->isfixed;
1279 if(clients)
1280 clients->prev = c;
1281 c->next = clients;
1282 c->snext = stack;
1283 stack = clients = c;
1284 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
1285 XMapWindow(dpy, c->win);
1286 setclientstate(c, NormalState);
1287 if(isvisible(c))
1288 focus(c);
1289 arrange();
1292 void
1293 resize(Client *c, Bool sizehints) {
1294 float actual, dx, dy, max, min;
1295 XWindowChanges wc;
1297 if(c->w <= 0 || c->h <= 0)
1298 return;
1299 if(sizehints) {
1300 if(c->minw && c->w < c->minw)
1301 c->w = c->minw;
1302 if(c->minh && c->h < c->minh)
1303 c->h = c->minh;
1304 if(c->maxw && c->w > c->maxw)
1305 c->w = c->maxw;
1306 if(c->maxh && c->h > c->maxh)
1307 c->h = c->maxh;
1308 /* inspired by algorithm from fluxbox */
1309 if(c->minay > 0 && c->maxay && (c->h - c->baseh) > 0) {
1310 dx = (float)(c->w - c->basew);
1311 dy = (float)(c->h - c->baseh);
1312 min = (float)(c->minax) / (float)(c->minay);
1313 max = (float)(c->maxax) / (float)(c->maxay);
1314 actual = dx / dy;
1315 if(max > 0 && min > 0 && actual > 0) {
1316 if(actual < min) {
1317 dy = (dx * min + dy) / (min * min + 1);
1318 dx = dy * min;
1319 c->w = (int)dx + c->basew;
1320 c->h = (int)dy + c->baseh;
1322 else if(actual > max) {
1323 dy = (dx * min + dy) / (max * max + 1);
1324 dx = dy * min;
1325 c->w = (int)dx + c->basew;
1326 c->h = (int)dy + c->baseh;
1330 if(c->incw)
1331 c->w -= (c->w - c->basew) % c->incw;
1332 if(c->inch)
1333 c->h -= (c->h - c->baseh) % c->inch;
1335 if(c->w == sw && c->h == sh)
1336 c->border = 0;
1337 else
1338 c->border = BORDERPX;
1339 /* offscreen appearance fixes */
1340 if(c->x > sw)
1341 c->x = sw - c->w - 2 * c->border;
1342 if(c->y > sh)
1343 c->y = sh - c->h - 2 * c->border;
1344 if(c->x + c->w + 2 * c->border < sx)
1345 c->x = sx;
1346 if(c->y + c->h + 2 * c->border < sy)
1347 c->y = sy;
1348 wc.x = c->x;
1349 wc.y = c->y;
1350 wc.width = c->w;
1351 wc.height = c->h;
1352 wc.border_width = c->border;
1353 XConfigureWindow(dpy, c->win, CWX | CWY | CWWidth | CWHeight | CWBorderWidth, &wc);
1354 configure(c);
1355 XSync(dpy, False);
1358 void
1359 updatesizehints(Client *c) {
1360 long msize;
1361 XSizeHints size;
1363 if(!XGetWMNormalHints(dpy, c->win, &size, &msize) || !size.flags)
1364 size.flags = PSize;
1365 c->flags = size.flags;
1366 if(c->flags & PBaseSize) {
1367 c->basew = size.base_width;
1368 c->baseh = size.base_height;
1369 } else {
1370 c->basew = c->baseh = 0;
1372 if(c->flags & PResizeInc) {
1373 c->incw = size.width_inc;
1374 c->inch = size.height_inc;
1375 } else {
1376 c->incw = c->inch = 0;
1378 if(c->flags & PMaxSize) {
1379 c->maxw = size.max_width;
1380 c->maxh = size.max_height;
1381 } else {
1382 c->maxw = c->maxh = 0;
1384 if(c->flags & PMinSize) {
1385 c->minw = size.min_width;
1386 c->minh = size.min_height;
1387 } else {
1388 c->minw = c->minh = 0;
1390 if(c->flags & PAspect) {
1391 c->minax = size.min_aspect.x;
1392 c->minay = size.min_aspect.y;
1393 c->maxax = size.max_aspect.x;
1394 c->maxay = size.max_aspect.y;
1395 } else {
1396 c->minax = c->minay = c->maxax = c->maxay = 0;
1398 c->isfixed = (c->maxw && c->minw && c->maxh && c->minh &&
1399 c->maxw == c->minw && c->maxh == c->minh);
1402 void
1403 updatetitle(Client *c) {
1404 char **list = NULL;
1405 int n;
1406 XTextProperty name;
1408 name.nitems = 0;
1409 c->name[0] = 0;
1410 XGetTextProperty(dpy, c->win, &name, netatom[NetWMName]);
1411 if(!name.nitems)
1412 XGetWMName(dpy, c->win, &name);
1413 if(!name.nitems)
1414 return;
1415 if(name.encoding == XA_STRING)
1416 strncpy(c->name, (char *)name.value, sizeof c->name);
1417 else {
1418 if(XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success && n > 0 && *list) {
1419 strncpy(c->name, *list, sizeof c->name);
1420 XFreeStringList(list);
1423 XFree(name.value);
1426 void
1427 unmanage(Client *c) {
1428 Client *nc;
1430 /* The server grab construct avoids race conditions. */
1431 XGrabServer(dpy);
1432 XSetErrorHandler(xerrordummy);
1433 detach(c);
1434 detachstack(c);
1435 if(sel == c) {
1436 for(nc = stack; nc && !isvisible(nc); nc = nc->snext);
1437 focus(nc);
1439 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1440 setclientstate(c, WithdrawnState);
1441 free(c);
1442 XSync(dpy, False);
1443 XSetErrorHandler(xerror);
1444 XUngrabServer(dpy);
1445 arrange();
1466 /* static */
1469 static void
1470 cleanup(void) {
1471 close(STDIN_FILENO);
1472 while(stack) {
1473 resize(stack, True);
1474 unmanage(stack);
1476 if(dc.font.set)
1477 XFreeFontSet(dpy, dc.font.set);
1478 else
1479 XFreeFont(dpy, dc.font.xfont);
1480 XUngrabKey(dpy, AnyKey, AnyModifier, root);
1481 XFreePixmap(dpy, dc.drawable);
1482 XFreeGC(dpy, dc.gc);
1483 XDestroyWindow(dpy, barwin);
1484 XFreeCursor(dpy, cursor[CurNormal]);
1485 XFreeCursor(dpy, cursor[CurResize]);
1486 XFreeCursor(dpy, cursor[CurMove]);
1487 XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime);
1488 XSync(dpy, False);
1491 static void
1492 scan(void) {
1493 unsigned int i, num;
1494 Window *wins, d1, d2;
1495 XWindowAttributes wa;
1497 wins = NULL;
1498 if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1499 for(i = 0; i < num; i++) {
1500 if(!XGetWindowAttributes(dpy, wins[i], &wa))
1501 continue;
1502 if(wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1503 continue;
1504 if(wa.map_state == IsViewable)
1505 manage(wins[i], &wa);
1508 if(wins)
1509 XFree(wins);
1512 static void
1513 setup(void) {
1514 int i, j;
1515 unsigned int mask;
1516 Window w;
1517 XModifierKeymap *modmap;
1518 XSetWindowAttributes wa;
1520 /* init atoms */
1521 wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1522 wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1523 wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1524 netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1525 netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1526 XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1527 PropModeReplace, (unsigned char *) netatom, NetLast);
1528 /* init cursors */
1529 cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1530 cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1531 cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1532 /* init modifier map */
1533 numlockmask = 0;
1534 modmap = XGetModifierMapping(dpy);
1535 for (i = 0; i < 8; i++) {
1536 for (j = 0; j < modmap->max_keypermod; j++) {
1537 if(modmap->modifiermap[i * modmap->max_keypermod + j] == XKeysymToKeycode(dpy, XK_Num_Lock))
1538 numlockmask = (1 << i);
1541 XFreeModifiermap(modmap);
1542 /* select for events */
1543 wa.event_mask = SubstructureRedirectMask | SubstructureNotifyMask
1544 | EnterWindowMask | LeaveWindowMask;
1545 wa.cursor = cursor[CurNormal];
1546 XChangeWindowAttributes(dpy, root, CWEventMask | CWCursor, &wa);
1547 grabkeys();
1548 seltag = True;
1549 /* style */
1550 dc.norm[ColBG] = getcolor(NORMBGCOLOR);
1551 dc.norm[ColFG] = getcolor(NORMFGCOLOR);
1552 dc.sel[ColBG] = getcolor(SELBGCOLOR);
1553 dc.sel[ColFG] = getcolor(SELFGCOLOR);
1554 setfont(FONT);
1555 /* geometry */
1556 sx = sy = 0;
1557 sw = DisplayWidth(dpy, screen);
1558 sh = DisplayHeight(dpy, screen);
1559 nmaster = NMASTER;
1560 bmw = 1;
1561 /* bar */
1562 dc.h = bh = dc.font.height + 2;
1563 wa.override_redirect = 1;
1564 wa.background_pixmap = ParentRelative;
1565 wa.event_mask = ButtonPressMask | ExposureMask;
1566 barwin = XCreateWindow(dpy, root, sx, sy, sw, bh, 0,
1567 DefaultDepth(dpy, screen), CopyFromParent, DefaultVisual(dpy, screen),
1568 CWOverrideRedirect | CWBackPixmap | CWEventMask, &wa);
1569 XDefineCursor(dpy, barwin, cursor[CurNormal]);
1570 XMapRaised(dpy, barwin);
1571 strcpy(stext, "dwm-"VERSION);
1572 /* windowarea */
1573 wax = sx;
1574 way = sy + bh;
1575 wah = sh - bh;
1576 waw = sw;
1577 /* pixmap for everything */
1578 dc.drawable = XCreatePixmap(dpy, root, sw, bh, DefaultDepth(dpy, screen));
1579 dc.gc = XCreateGC(dpy, root, 0, 0);
1580 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
1581 /* multihead support */
1582 selscreen = XQueryPointer(dpy, root, &w, &w, &i, &i, &i, &i, &mask);
1585 /*
1586 * Startup Error handler to check if another window manager
1587 * is already running.
1588 */
1589 static int
1590 xerrorstart(Display *dsply, XErrorEvent *ee) {
1591 otherwm = True;
1592 return -1;
1597 void
1598 sendevent(Window w, Atom a, long value) {
1599 XEvent e;
1601 e.type = ClientMessage;
1602 e.xclient.window = w;
1603 e.xclient.message_type = a;
1604 e.xclient.format = 32;
1605 e.xclient.data.l[0] = value;
1606 e.xclient.data.l[1] = CurrentTime;
1607 XSendEvent(dpy, w, False, NoEventMask, &e);
1608 XSync(dpy, False);
1611 void
1612 quit() {
1613 readin = running = False;
1616 /* There's no way to check accesses to destroyed windows, thus those cases are
1617 * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
1618 * default error handler, which may call exit.
1619 */
1620 int
1621 xerror(Display *dpy, XErrorEvent *ee) {
1622 if(ee->error_code == BadWindow
1623 || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1624 || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1625 || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1626 || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1627 || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1628 || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1629 || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1630 return 0;
1631 fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1632 ee->request_code, ee->error_code);
1633 return xerrorxlib(dpy, ee); /* may call exit */
1636 int
1637 main(int argc, char *argv[]) {
1638 char *p;
1639 int r, xfd;
1640 fd_set rd;
1642 if(argc == 2 && !strncmp("-v", argv[1], 3)) {
1643 fputs("dwm-"VERSION", (C)opyright MMVI-MMVII Anselm R. Garbe\n", stdout);
1644 exit(EXIT_SUCCESS);
1645 } else if(argc != 1) {
1646 eprint("usage: dwm [-v]\n");
1648 setlocale(LC_CTYPE, "");
1649 dpy = XOpenDisplay(0);
1650 if(!dpy) {
1651 eprint("dwm: cannot open display\n");
1653 xfd = ConnectionNumber(dpy);
1654 screen = DefaultScreen(dpy);
1655 root = RootWindow(dpy, screen);
1656 otherwm = False;
1657 XSetErrorHandler(xerrorstart);
1658 /* this causes an error if some other window manager is running */
1659 XSelectInput(dpy, root, SubstructureRedirectMask);
1660 XSync(dpy, False);
1661 if(otherwm) {
1662 eprint("dwm: another window manager is already running\n");
1665 XSync(dpy, False);
1666 XSetErrorHandler(NULL);
1667 xerrorxlib = XSetErrorHandler(xerror);
1668 XSync(dpy, False);
1669 setup();
1670 drawstatus();
1671 scan();
1673 /* main event loop, also reads status text from stdin */
1674 XSync(dpy, False);
1675 procevent();
1676 readin = True;
1677 while(running) {
1678 FD_ZERO(&rd);
1679 if(readin)
1680 FD_SET(STDIN_FILENO, &rd);
1681 FD_SET(xfd, &rd);
1682 if(select(xfd + 1, &rd, NULL, NULL, NULL) == -1) {
1683 if(errno == EINTR)
1684 continue;
1685 eprint("select failed\n");
1687 if(FD_ISSET(STDIN_FILENO, &rd)) {
1688 switch(r = read(STDIN_FILENO, stext, sizeof stext - 1)) {
1689 case -1:
1690 strncpy(stext, strerror(errno), sizeof stext - 1);
1691 stext[sizeof stext - 1] = '\0';
1692 readin = False;
1693 break;
1694 case 0:
1695 strncpy(stext, "EOF", 4);
1696 readin = False;
1697 break;
1698 default:
1699 for(stext[r] = '\0', p = stext + strlen(stext) - 1; p >= stext && *p == '\n'; *p-- = '\0');
1700 for(; p >= stext && *p != '\n'; --p);
1701 if(p > stext)
1702 strncpy(stext, p + 1, sizeof stext);
1704 drawstatus();
1706 if(FD_ISSET(xfd, &rd))
1707 procevent();
1709 cleanup();
1710 XCloseDisplay(dpy);
1711 return 0;