aewl

view aewl.c @ 768:a1c6805aa018

simplified and corrected domax() and restack()
author meillo@marmaro.de
date Fri, 05 Dec 2008 21:14:50 +0100
parents 706991d15451
children 49aa8ccceefa
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 "config.h"
45 #include <errno.h>
46 #include <locale.h>
47 #include <stdio.h>
48 #include <stdarg.h>
49 #include <stdlib.h>
50 #include <string.h>
51 #include <unistd.h>
52 #include <sys/select.h>
53 #include <sys/types.h>
54 #include <sys/wait.h>
55 #include <X11/cursorfont.h>
56 #include <X11/keysym.h>
57 #include <X11/Xatom.h>
58 #include <X11/Xlib.h>
59 #include <X11/Xproto.h>
60 #include <X11/Xutil.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, bmw; /* bar height, bar mode label width */
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; c->x = wax;
237 c->ry = c->y; c->y = way;
238 c->rw = c->w; c->w = waw - 2 * BORDERPX;
239 c->rh = c->h; c->h = wah - 2 * BORDERPX;
240 }
241 else {
242 c->x = c->rx;
243 c->y = c->ry;
244 c->w = c->rw;
245 c->h = c->rh;
246 }
247 resize(c, True);
248 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
249 }
253 void (*arrange)(void) = DEFMODE;
255 void
256 detach(Client *c) {
257 if(c->prev)
258 c->prev->next = c->next;
259 if(c->next)
260 c->next->prev = c->prev;
261 if(c == clients)
262 clients = c->next;
263 c->next = c->prev = NULL;
264 }
266 void
267 dotile(void) {
268 unsigned int i, n, mw, mh, tw, th;
269 Client *c;
271 for(n = 0, c = nexttiled(clients); c; c = nexttiled(c->next))
272 n++;
273 /* window geoms */
274 mh = (n > nmaster) ? wah / nmaster : wah / (n > 0 ? n : 1);
275 mw = (n > nmaster) ? waw / 2 : waw;
276 th = (n > nmaster) ? wah / (n - nmaster) : 0;
277 tw = waw - mw;
279 for(i = 0, c = clients; c; c = c->next)
280 if(isvisible(c)) {
281 if(c->isfloat) {
282 resize(c, True);
283 continue;
284 }
285 c->ismax = False;
286 c->x = wax;
287 c->y = way;
288 if(i < nmaster) {
289 c->y += i * mh;
290 c->w = mw - 2 * BORDERPX;
291 c->h = mh - 2 * BORDERPX;
292 }
293 else { /* tile window */
294 c->x += mw;
295 c->w = tw - 2 * BORDERPX;
296 if(th > 2 * BORDERPX) {
297 c->y += (i - nmaster) * th;
298 c->h = th - 2 * BORDERPX;
299 }
300 else /* fallback if th <= 2 * BORDERPX */
301 c->h = wah - 2 * BORDERPX;
302 }
303 resize(c, False);
304 i++;
305 }
306 else
307 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
308 if(!sel || !isvisible(sel)) {
309 for(c = stack; c && !isvisible(c); c = c->snext);
310 focus(c);
311 }
312 restack();
313 }
315 /* begin code by mitch */
316 void
317 domax(void) {
318 Client *c;
320 for(c = clients; c; c = c->next) {
321 if(isvisible(c)) {
322 if(c->isfloat) {
323 resize(c, True);
324 continue;
325 }
326 c->ismax = True;
327 c->x = sx;
328 c->y = bh;
329 c->w = sw - 2 * BORDERPX;
330 c->h = sh - bh - 2 * BORDERPX;
331 resize(c, False);
332 } else {
333 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
334 }
335 }
336 if(!sel || !isvisible(sel)) {
337 for(c = stack; c && !isvisible(c); c = c->snext);
338 focus(c);
339 }
340 restack();
341 }
342 /* end code by mitch */
344 void
345 focusnext() {
346 Client *c;
348 if(!sel)
349 return;
350 if(!(c = getnext(sel->next)))
351 c = getnext(clients);
352 if(c) {
353 focus(c);
354 restack();
355 }
356 }
358 void
359 incnmaster() {
360 if(wah / (nmaster + 1) <= 2 * BORDERPX)
361 return;
362 nmaster++;
363 if(sel)
364 arrange();
365 else
366 drawstatus();
367 }
369 void
370 decnmaster() {
371 if(nmaster <= 1)
372 return;
373 nmaster--;
374 if(sel)
375 arrange();
376 else
377 drawstatus();
378 }
380 Bool
381 isvisible(Client *c) {
382 return (c->tag == seltag);
383 }
385 void
386 restack(void) {
387 Client *c;
388 XEvent ev;
390 drawstatus();
391 if(!sel)
392 return;
393 if(sel->isfloat)
394 XRaiseWindow(dpy, sel->win);
396 if(!sel->isfloat)
397 XLowerWindow(dpy, sel->win);
398 for(c = nexttiled(clients); c; c = nexttiled(c->next)) {
399 if(c == sel)
400 continue;
401 XLowerWindow(dpy, c->win);
402 }
404 XSync(dpy, False);
405 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
406 }
408 void
409 togglefloat() {
410 if (!sel)
411 return;
412 sel->isfloat = !sel->isfloat;
413 arrange();
414 }
416 void
417 togglemode() {
418 /* only toggle between tile and max - float is just available through togglefloat */
419 arrange = (arrange == dotile) ? domax : dotile;
420 if(sel)
421 arrange();
422 else
423 drawstatus();
424 }
426 void
427 toggleview() {
428 seltag = !seltag;
429 arrange();
430 }
432 void
433 zoom() {
434 unsigned int n;
435 Client *c;
437 if(!sel)
438 return;
439 if(sel->isfloat) {
440 togglemax(sel);
441 return;
442 }
443 for(n = 0, c = nexttiled(clients); c; c = nexttiled(c->next))
444 n++;
446 if((c = sel) == nexttiled(clients))
447 if(!(c = nexttiled(c->next)))
448 return;
449 detach(c);
450 if(clients)
451 clients->prev = c;
452 c->next = clients;
453 clients = c;
454 focus(c);
455 arrange();
456 }
473 /* from util.c */
476 void *
477 emallocz(unsigned int size) {
478 void *res = calloc(1, size);
480 if(!res)
481 eprint("fatal: could not malloc() %u bytes\n", size);
482 return res;
483 }
485 void
486 eprint(const char *errstr, ...) {
487 va_list ap;
489 va_start(ap, errstr);
490 vfprintf(stderr, errstr, ap);
491 va_end(ap);
492 exit(EXIT_FAILURE);
493 }
495 void
496 spawn(const char* cmd) {
497 static char *shell = NULL;
499 if(!shell && !(shell = getenv("SHELL")))
500 shell = "/bin/sh";
501 if(!cmd)
502 return;
503 /* The double-fork construct avoids zombie processes and keeps the code
504 * clean from stupid signal handlers. */
505 if(fork() == 0) {
506 if(fork() == 0) {
507 if(dpy)
508 close(ConnectionNumber(dpy));
509 setsid();
510 execl(shell, shell, "-c", cmd, (char *)NULL);
511 fprintf(stderr, "dwm: execl '%s -c %s'", shell, cmd);
512 perror(" failed");
513 }
514 exit(0);
515 }
516 wait(0);
517 }
531 /* from tag.c */
533 /* static */
535 Client *
536 getnext(Client *c) {
537 while(c && !isvisible(c)) {
538 c = c->next;
539 }
540 return c;
541 }
543 void
544 settag(Client *c, Client *trans) {
545 unsigned int i;
546 XClassHint ch = { 0 };
548 if(trans) {
549 c->tag = trans->tag;
550 return;
551 }
552 c->tag = seltag; /* default */
553 XGetClassHint(dpy, c->win, &ch);
554 len = sizeof rule / sizeof rule[0];
555 for(i = 0; i < len; i++) {
556 if((rule[i].title && strstr(c->name, rule[i].title))
557 || (ch.res_class && rule[i].class && strstr(ch.res_class, rule[i].class))
558 || (ch.res_name && rule[i].instance && strstr(ch.res_name, rule[i].instance))) {
559 c->isfloat = rule[i].isfloat;
560 if (rule[i].tag < 0) {
561 c->tag = seltag;
562 } else if (rule[i].tag) {
563 c->tag = True;
564 } else {
565 c->tag = False;
566 }
567 break;
568 }
569 }
570 if(ch.res_class)
571 XFree(ch.res_class);
572 if(ch.res_name)
573 XFree(ch.res_name);
574 }
576 void
577 toggletag() {
578 if(!sel)
579 return;
580 sel->tag = !sel->tag;
581 toggleview();
582 }
600 /* from event.c */
601 /* static */
603 KEYS
607 static void
608 movemouse(Client *c) {
609 int x1, y1, ocx, ocy, di;
610 unsigned int dui;
611 Window dummy;
612 XEvent ev;
614 ocx = c->x;
615 ocy = c->y;
616 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
617 None, cursor[CurMove], CurrentTime) != GrabSuccess)
618 return;
619 c->ismax = False;
620 XQueryPointer(dpy, root, &dummy, &dummy, &x1, &y1, &di, &di, &dui);
621 for(;;) {
622 XMaskEvent(dpy, MOUSEMASK | ExposureMask | SubstructureRedirectMask, &ev);
623 switch (ev.type) {
624 case ButtonRelease:
625 resize(c, True);
626 XUngrabPointer(dpy, CurrentTime);
627 return;
628 case ConfigureRequest:
629 case Expose:
630 case MapRequest:
631 handler[ev.type](&ev);
632 break;
633 case MotionNotify:
634 XSync(dpy, False);
635 c->x = ocx + (ev.xmotion.x - x1);
636 c->y = ocy + (ev.xmotion.y - y1);
637 if(abs(wax + c->x) < SNAP)
638 c->x = wax;
639 else if(abs((wax + waw) - (c->x + c->w + 2 * c->border)) < SNAP)
640 c->x = wax + waw - c->w - 2 * c->border;
641 if(abs(way - c->y) < SNAP)
642 c->y = way;
643 else if(abs((way + wah) - (c->y + c->h + 2 * c->border)) < SNAP)
644 c->y = way + wah - c->h - 2 * c->border;
645 resize(c, False);
646 break;
647 }
648 }
649 }
651 static void
652 resizemouse(Client *c) {
653 int ocx, ocy;
654 int nw, nh;
655 XEvent ev;
657 ocx = c->x;
658 ocy = c->y;
659 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
660 None, cursor[CurResize], CurrentTime) != GrabSuccess)
661 return;
662 c->ismax = False;
663 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->border - 1, c->h + c->border - 1);
664 for(;;) {
665 XMaskEvent(dpy, MOUSEMASK | ExposureMask | SubstructureRedirectMask , &ev);
666 switch(ev.type) {
667 case ButtonRelease:
668 resize(c, True);
669 XUngrabPointer(dpy, CurrentTime);
670 return;
671 case ConfigureRequest:
672 case Expose:
673 case MapRequest:
674 handler[ev.type](&ev);
675 break;
676 case MotionNotify:
677 XSync(dpy, False);
678 nw = ev.xmotion.x - ocx - 2 * c->border + 1;
679 c->w = nw > 0 ? nw : 1;
680 nh = ev.xmotion.y - ocy - 2 * c->border + 1;
681 c->h = nh > 0 ? nh : 1;
682 resize(c, True);
683 break;
684 }
685 }
686 }
688 static void
689 buttonpress(XEvent *e) {
690 Client *c;
691 XButtonPressedEvent *ev = &e->xbutton;
693 if(barwin == ev->window) {
694 return;
695 }
696 if((c = getclient(ev->window))) {
697 focus(c);
698 if(CLEANMASK(ev->state) != MODKEY)
699 return;
700 if(ev->button == Button1 && c->isfloat) {
701 restack();
702 movemouse(c);
703 } else if(ev->button == Button3 && c->isfloat && !c->isfixed) {
704 restack();
705 resizemouse(c);
706 }
707 }
708 }
710 static void
711 configurerequest(XEvent *e) {
712 unsigned long newmask;
713 Client *c;
714 XConfigureRequestEvent *ev = &e->xconfigurerequest;
715 XWindowChanges wc;
717 if((c = getclient(ev->window))) {
718 c->ismax = False;
719 if(ev->value_mask & CWX)
720 c->x = ev->x;
721 if(ev->value_mask & CWY)
722 c->y = ev->y;
723 if(ev->value_mask & CWWidth)
724 c->w = ev->width;
725 if(ev->value_mask & CWHeight)
726 c->h = ev->height;
727 if(ev->value_mask & CWBorderWidth)
728 c->border = ev->border_width;
729 wc.x = c->x;
730 wc.y = c->y;
731 wc.width = c->w;
732 wc.height = c->h;
733 newmask = ev->value_mask & (~(CWSibling | CWStackMode | CWBorderWidth));
734 if(newmask)
735 XConfigureWindow(dpy, c->win, newmask, &wc);
736 else
737 configure(c);
738 XSync(dpy, False);
739 if(c->isfloat) {
740 resize(c, False);
741 if(!isvisible(c))
742 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
743 }
744 else
745 arrange();
746 } else {
747 wc.x = ev->x;
748 wc.y = ev->y;
749 wc.width = ev->width;
750 wc.height = ev->height;
751 wc.border_width = ev->border_width;
752 wc.sibling = ev->above;
753 wc.stack_mode = ev->detail;
754 XConfigureWindow(dpy, ev->window, ev->value_mask, &wc);
755 XSync(dpy, False);
756 }
757 }
759 static void
760 destroynotify(XEvent *e) {
761 Client *c;
762 XDestroyWindowEvent *ev = &e->xdestroywindow;
764 if((c = getclient(ev->window)))
765 unmanage(c);
766 }
768 static void
769 enternotify(XEvent *e) {
770 Client *c;
771 XCrossingEvent *ev = &e->xcrossing;
773 if(ev->mode != NotifyNormal || ev->detail == NotifyInferior)
774 return;
775 if((c = getclient(ev->window)) && isvisible(c))
776 focus(c);
777 else if(ev->window == root) {
778 selscreen = True;
779 for(c = stack; c && !isvisible(c); c = c->snext);
780 focus(c);
781 }
782 }
784 static void
785 expose(XEvent *e) {
786 XExposeEvent *ev = &e->xexpose;
788 if(ev->count == 0) {
789 if(barwin == ev->window)
790 drawstatus();
791 }
792 }
794 static void
795 keypress(XEvent *e) {
796 static unsigned int len = sizeof key / sizeof key[0];
797 unsigned int i;
798 KeySym keysym;
799 XKeyEvent *ev = &e->xkey;
801 keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
802 for(i = 0; i < len; i++) {
803 if(keysym == key[i].keysym && CLEANMASK(key[i].mod) == CLEANMASK(ev->state)) {
804 if(key[i].func)
805 key[i].func(key[i].cmd);
806 }
807 }
808 }
810 static void
811 leavenotify(XEvent *e) {
812 XCrossingEvent *ev = &e->xcrossing;
814 if((ev->window == root) && !ev->same_screen) {
815 selscreen = False;
816 focus(NULL);
817 }
818 }
820 static void
821 mappingnotify(XEvent *e) {
822 XMappingEvent *ev = &e->xmapping;
824 XRefreshKeyboardMapping(ev);
825 if(ev->request == MappingKeyboard)
826 grabkeys();
827 }
829 static void
830 maprequest(XEvent *e) {
831 static XWindowAttributes wa;
832 XMapRequestEvent *ev = &e->xmaprequest;
834 if(!XGetWindowAttributes(dpy, ev->window, &wa))
835 return;
836 if(wa.override_redirect) {
837 XSelectInput(dpy, ev->window,
838 (StructureNotifyMask | PropertyChangeMask));
839 return;
840 }
841 if(!getclient(ev->window))
842 manage(ev->window, &wa);
843 }
845 static void
846 propertynotify(XEvent *e) {
847 Client *c;
848 Window trans;
849 XPropertyEvent *ev = &e->xproperty;
851 if(ev->state == PropertyDelete)
852 return; /* ignore */
853 if((c = getclient(ev->window))) {
854 switch (ev->atom) {
855 default: break;
856 case XA_WM_TRANSIENT_FOR:
857 XGetTransientForHint(dpy, c->win, &trans);
858 if(!c->isfloat && (c->isfloat = (trans != 0)))
859 arrange();
860 break;
861 case XA_WM_NORMAL_HINTS:
862 updatesizehints(c);
863 break;
864 }
865 if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
866 updatetitle(c);
867 if(c == sel)
868 drawstatus();
869 }
870 }
871 }
873 static void
874 unmapnotify(XEvent *e) {
875 Client *c;
876 XUnmapEvent *ev = &e->xunmap;
878 if((c = getclient(ev->window)))
879 unmanage(c);
880 }
884 void (*handler[LASTEvent]) (XEvent *) = {
885 [ButtonPress] = buttonpress,
886 [ConfigureRequest] = configurerequest,
887 [DestroyNotify] = destroynotify,
888 [EnterNotify] = enternotify,
889 [LeaveNotify] = leavenotify,
890 [Expose] = expose,
891 [KeyPress] = keypress,
892 [MappingNotify] = mappingnotify,
893 [MapRequest] = maprequest,
894 [PropertyNotify] = propertynotify,
895 [UnmapNotify] = unmapnotify
896 };
898 void
899 grabkeys(void) {
900 static unsigned int len = sizeof key / sizeof key[0];
901 unsigned int i;
902 KeyCode code;
904 XUngrabKey(dpy, AnyKey, AnyModifier, root);
905 for(i = 0; i < len; i++) {
906 code = XKeysymToKeycode(dpy, key[i].keysym);
907 XGrabKey(dpy, code, key[i].mod, root, True,
908 GrabModeAsync, GrabModeAsync);
909 XGrabKey(dpy, code, key[i].mod | LockMask, root, True,
910 GrabModeAsync, GrabModeAsync);
911 XGrabKey(dpy, code, key[i].mod | numlockmask, root, True,
912 GrabModeAsync, GrabModeAsync);
913 XGrabKey(dpy, code, key[i].mod | numlockmask | LockMask, root, True,
914 GrabModeAsync, GrabModeAsync);
915 }
916 }
918 void
919 procevent(void) {
920 XEvent ev;
922 while(XPending(dpy)) {
923 XNextEvent(dpy, &ev);
924 if(handler[ev.type])
925 (handler[ev.type])(&ev); /* call handler */
926 }
927 }
943 /* from draw.c */
944 /* static */
946 static unsigned int
947 textnw(const char *text, unsigned int len) {
948 XRectangle r;
950 if(dc.font.set) {
951 XmbTextExtents(dc.font.set, text, len, NULL, &r);
952 return r.width;
953 }
954 return XTextWidth(dc.font.xfont, text, len);
955 }
957 static void
958 drawtext(const char *text, unsigned long col[ColLast]) {
959 int x, y, w, h;
960 static char buf[256];
961 unsigned int len, olen;
962 XGCValues gcv;
963 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
965 XSetForeground(dpy, dc.gc, col[ColBG]);
966 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
967 if(!text)
968 return;
969 w = 0;
970 olen = len = strlen(text);
971 if(len >= sizeof buf)
972 len = sizeof buf - 1;
973 memcpy(buf, text, len);
974 buf[len] = 0;
975 h = dc.font.ascent + dc.font.descent;
976 y = dc.y + (dc.h / 2) - (h / 2) + dc.font.ascent;
977 x = dc.x + (h / 2);
978 /* shorten text if necessary */
979 while(len && (w = textnw(buf, len)) > dc.w - h)
980 buf[--len] = 0;
981 if(len < olen) {
982 if(len > 1)
983 buf[len - 1] = '.';
984 if(len > 2)
985 buf[len - 2] = '.';
986 if(len > 3)
987 buf[len - 3] = '.';
988 }
989 if(w > dc.w)
990 return; /* too long */
991 gcv.foreground = col[ColFG];
992 if(dc.font.set) {
993 XChangeGC(dpy, dc.gc, GCForeground, &gcv);
994 XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
995 } else {
996 gcv.font = dc.font.xfont->fid;
997 XChangeGC(dpy, dc.gc, GCForeground | GCFont, &gcv);
998 XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
999 }
1004 void
1005 drawstatus(void) {
1006 int x;
1008 dc.x = dc.y = 0;
1009 dc.w = textw(NAMETAGGED);
1010 drawtext(NAMETAGGED, ( seltag ? dc.sel : dc.norm ));
1011 dc.x += dc.w + 1;
1012 dc.w = textw(NAMEUNTAGGED);
1013 drawtext(NAMEUNTAGGED, ( seltag ? dc.norm : dc.sel ));
1014 dc.x += dc.w + 1;
1015 dc.w = bmw;
1016 drawtext("", dc.norm);
1017 x = dc.x + dc.w;
1018 dc.w = textw(stext);
1019 dc.x = sw - dc.w;
1020 if(dc.x < x) {
1021 dc.x = x;
1022 dc.w = sw - x;
1024 drawtext(stext, dc.norm);
1025 if((dc.w = dc.x - x) > bh) {
1026 dc.x = x;
1027 drawtext(sel ? sel->name : NULL, dc.norm);
1029 XCopyArea(dpy, dc.drawable, barwin, dc.gc, 0, 0, sw, bh, 0, 0);
1030 XSync(dpy, False);
1033 unsigned long
1034 getcolor(const char *colstr) {
1035 Colormap cmap = DefaultColormap(dpy, screen);
1036 XColor color;
1038 if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
1039 eprint("error, cannot allocate color '%s'\n", colstr);
1040 return color.pixel;
1043 void
1044 setfont(const char *fontstr) {
1045 char *def, **missing;
1046 int i, n;
1048 missing = NULL;
1049 if(dc.font.set)
1050 XFreeFontSet(dpy, dc.font.set);
1051 dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
1052 if(missing) {
1053 while(n--)
1054 fprintf(stderr, "missing fontset: %s\n", missing[n]);
1055 XFreeStringList(missing);
1057 if(dc.font.set) {
1058 XFontSetExtents *font_extents;
1059 XFontStruct **xfonts;
1060 char **font_names;
1061 dc.font.ascent = dc.font.descent = 0;
1062 font_extents = XExtentsOfFontSet(dc.font.set);
1063 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
1064 for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
1065 if(dc.font.ascent < (*xfonts)->ascent)
1066 dc.font.ascent = (*xfonts)->ascent;
1067 if(dc.font.descent < (*xfonts)->descent)
1068 dc.font.descent = (*xfonts)->descent;
1069 xfonts++;
1071 } else {
1072 if(dc.font.xfont)
1073 XFreeFont(dpy, dc.font.xfont);
1074 dc.font.xfont = NULL;
1075 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr)))
1076 eprint("error, cannot load font: '%s'\n", fontstr);
1077 dc.font.ascent = dc.font.xfont->ascent;
1078 dc.font.descent = dc.font.xfont->descent;
1080 dc.font.height = dc.font.ascent + dc.font.descent;
1083 unsigned int
1084 textw(const char *text) {
1085 return textnw(text, strlen(text)) + dc.font.height;
1098 /* from client.c */
1099 /* static */
1101 static void
1102 detachstack(Client *c) {
1103 Client **tc;
1104 for(tc=&stack; *tc && *tc != c; tc=&(*tc)->snext);
1105 *tc = c->snext;
1108 static void
1109 grabbuttons(Client *c, Bool focused) {
1110 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1112 if(focused) {
1113 XGrabButton(dpy, Button1, MODKEY, c->win, False, BUTTONMASK,
1114 GrabModeAsync, GrabModeSync, None, None);
1115 XGrabButton(dpy, Button1, MODKEY | LockMask, c->win, False, BUTTONMASK,
1116 GrabModeAsync, GrabModeSync, None, None);
1117 XGrabButton(dpy, Button1, MODKEY | numlockmask, c->win, False, BUTTONMASK,
1118 GrabModeAsync, GrabModeSync, None, None);
1119 XGrabButton(dpy, Button1, MODKEY | numlockmask | LockMask, c->win, False, BUTTONMASK,
1120 GrabModeAsync, GrabModeSync, None, None);
1122 XGrabButton(dpy, Button2, MODKEY, c->win, False, BUTTONMASK,
1123 GrabModeAsync, GrabModeSync, None, None);
1124 XGrabButton(dpy, Button2, MODKEY | LockMask, c->win, False, BUTTONMASK,
1125 GrabModeAsync, GrabModeSync, None, None);
1126 XGrabButton(dpy, Button2, MODKEY | numlockmask, c->win, False, BUTTONMASK,
1127 GrabModeAsync, GrabModeSync, None, None);
1128 XGrabButton(dpy, Button2, MODKEY | numlockmask | LockMask, c->win, False, BUTTONMASK,
1129 GrabModeAsync, GrabModeSync, None, None);
1131 XGrabButton(dpy, Button3, MODKEY, c->win, False, BUTTONMASK,
1132 GrabModeAsync, GrabModeSync, None, None);
1133 XGrabButton(dpy, Button3, MODKEY | LockMask, c->win, False, BUTTONMASK,
1134 GrabModeAsync, GrabModeSync, None, None);
1135 XGrabButton(dpy, Button3, MODKEY | numlockmask, c->win, False, BUTTONMASK,
1136 GrabModeAsync, GrabModeSync, None, None);
1137 XGrabButton(dpy, Button3, MODKEY | numlockmask | LockMask, c->win, False, BUTTONMASK,
1138 GrabModeAsync, GrabModeSync, None, None);
1139 } else {
1140 XGrabButton(dpy, AnyButton, AnyModifier, c->win, False, BUTTONMASK,
1141 GrabModeAsync, GrabModeSync, None, None);
1145 static void
1146 setclientstate(Client *c, long state) {
1147 long data[] = {state, None};
1148 XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1149 PropModeReplace, (unsigned char *)data, 2);
1152 static int
1153 xerrordummy(Display *dsply, XErrorEvent *ee) {
1154 return 0;
1159 void
1160 configure(Client *c) {
1161 XEvent synev;
1163 synev.type = ConfigureNotify;
1164 synev.xconfigure.display = dpy;
1165 synev.xconfigure.event = c->win;
1166 synev.xconfigure.window = c->win;
1167 synev.xconfigure.x = c->x;
1168 synev.xconfigure.y = c->y;
1169 synev.xconfigure.width = c->w;
1170 synev.xconfigure.height = c->h;
1171 synev.xconfigure.border_width = c->border;
1172 synev.xconfigure.above = None;
1173 XSendEvent(dpy, c->win, True, NoEventMask, &synev);
1176 void
1177 focus(Client *c) {
1178 if(c && !isvisible(c))
1179 return;
1180 if(sel && sel != c) {
1181 grabbuttons(sel, False);
1182 XSetWindowBorder(dpy, sel->win, dc.norm[ColBG]);
1184 if(c) {
1185 detachstack(c);
1186 c->snext = stack;
1187 stack = c;
1188 grabbuttons(c, True);
1190 sel = c;
1191 drawstatus();
1192 if(!selscreen)
1193 return;
1194 if(c) {
1195 XSetWindowBorder(dpy, c->win, dc.sel[ColBG]);
1196 XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
1197 } else {
1198 XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
1202 Client *
1203 getclient(Window w) {
1204 Client *c;
1206 for(c = clients; c; c = c->next) {
1207 if(c->win == w) {
1208 return c;
1211 return NULL;
1214 Bool
1215 isprotodel(Client *c) {
1216 int i, n;
1217 Atom *protocols;
1218 Bool ret = False;
1220 if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
1221 for(i = 0; !ret && i < n; i++)
1222 if(protocols[i] == wmatom[WMDelete])
1223 ret = True;
1224 XFree(protocols);
1226 return ret;
1229 void
1230 killclient() {
1231 if(!sel)
1232 return;
1233 if(isprotodel(sel))
1234 sendevent(sel->win, wmatom[WMProtocols], wmatom[WMDelete]);
1235 else
1236 XKillClient(dpy, sel->win);
1239 void
1240 manage(Window w, XWindowAttributes *wa) {
1241 Client *c;
1242 Window trans;
1244 c = emallocz(sizeof(Client));
1245 c->tag = True;
1246 c->win = w;
1247 c->x = wa->x;
1248 c->y = wa->y;
1249 c->w = wa->width;
1250 c->h = wa->height;
1251 if(c->w == sw && c->h == sh) {
1252 c->border = 0;
1253 c->x = sx;
1254 c->y = sy;
1255 } else {
1256 c->border = BORDERPX;
1257 if(c->x + c->w + 2 * c->border > wax + waw)
1258 c->x = wax + waw - c->w - 2 * c->border;
1259 if(c->y + c->h + 2 * c->border > way + wah)
1260 c->y = way + wah - c->h - 2 * c->border;
1261 if(c->x < wax)
1262 c->x = wax;
1263 if(c->y < way)
1264 c->y = way;
1266 updatesizehints(c);
1267 XSelectInput(dpy, c->win,
1268 StructureNotifyMask | PropertyChangeMask | EnterWindowMask);
1269 XGetTransientForHint(dpy, c->win, &trans);
1270 grabbuttons(c, False);
1271 XSetWindowBorder(dpy, c->win, dc.norm[ColBG]);
1272 updatetitle(c);
1273 settag(c, getclient(trans));
1274 if(!c->isfloat)
1275 c->isfloat = trans || c->isfixed;
1276 if(clients)
1277 clients->prev = c;
1278 c->next = clients;
1279 c->snext = stack;
1280 stack = clients = c;
1281 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
1282 XMapWindow(dpy, c->win);
1283 setclientstate(c, NormalState);
1284 if(isvisible(c))
1285 focus(c);
1286 arrange();
1289 void
1290 resize(Client *c, Bool sizehints) {
1291 float actual, dx, dy, max, min;
1292 XWindowChanges wc;
1294 if(c->w <= 0 || c->h <= 0)
1295 return;
1296 if(sizehints) {
1297 if(c->minw && c->w < c->minw)
1298 c->w = c->minw;
1299 if(c->minh && c->h < c->minh)
1300 c->h = c->minh;
1301 if(c->maxw && c->w > c->maxw)
1302 c->w = c->maxw;
1303 if(c->maxh && c->h > c->maxh)
1304 c->h = c->maxh;
1305 /* inspired by algorithm from fluxbox */
1306 if(c->minay > 0 && c->maxay && (c->h - c->baseh) > 0) {
1307 dx = (float)(c->w - c->basew);
1308 dy = (float)(c->h - c->baseh);
1309 min = (float)(c->minax) / (float)(c->minay);
1310 max = (float)(c->maxax) / (float)(c->maxay);
1311 actual = dx / dy;
1312 if(max > 0 && min > 0 && actual > 0) {
1313 if(actual < min) {
1314 dy = (dx * min + dy) / (min * min + 1);
1315 dx = dy * min;
1316 c->w = (int)dx + c->basew;
1317 c->h = (int)dy + c->baseh;
1319 else if(actual > max) {
1320 dy = (dx * min + dy) / (max * max + 1);
1321 dx = dy * min;
1322 c->w = (int)dx + c->basew;
1323 c->h = (int)dy + c->baseh;
1327 if(c->incw)
1328 c->w -= (c->w - c->basew) % c->incw;
1329 if(c->inch)
1330 c->h -= (c->h - c->baseh) % c->inch;
1332 if(c->w == sw && c->h == sh)
1333 c->border = 0;
1334 else
1335 c->border = BORDERPX;
1336 /* offscreen appearance fixes */
1337 if(c->x > sw)
1338 c->x = sw - c->w - 2 * c->border;
1339 if(c->y > sh)
1340 c->y = sh - c->h - 2 * c->border;
1341 if(c->x + c->w + 2 * c->border < sx)
1342 c->x = sx;
1343 if(c->y + c->h + 2 * c->border < sy)
1344 c->y = sy;
1345 wc.x = c->x;
1346 wc.y = c->y;
1347 wc.width = c->w;
1348 wc.height = c->h;
1349 wc.border_width = c->border;
1350 XConfigureWindow(dpy, c->win, CWX | CWY | CWWidth | CWHeight | CWBorderWidth, &wc);
1351 configure(c);
1352 XSync(dpy, False);
1355 void
1356 updatesizehints(Client *c) {
1357 long msize;
1358 XSizeHints size;
1360 if(!XGetWMNormalHints(dpy, c->win, &size, &msize) || !size.flags)
1361 size.flags = PSize;
1362 c->flags = size.flags;
1363 if(c->flags & PBaseSize) {
1364 c->basew = size.base_width;
1365 c->baseh = size.base_height;
1366 } else {
1367 c->basew = c->baseh = 0;
1369 if(c->flags & PResizeInc) {
1370 c->incw = size.width_inc;
1371 c->inch = size.height_inc;
1372 } else {
1373 c->incw = c->inch = 0;
1375 if(c->flags & PMaxSize) {
1376 c->maxw = size.max_width;
1377 c->maxh = size.max_height;
1378 } else {
1379 c->maxw = c->maxh = 0;
1381 if(c->flags & PMinSize) {
1382 c->minw = size.min_width;
1383 c->minh = size.min_height;
1384 } else {
1385 c->minw = c->minh = 0;
1387 if(c->flags & PAspect) {
1388 c->minax = size.min_aspect.x;
1389 c->minay = size.min_aspect.y;
1390 c->maxax = size.max_aspect.x;
1391 c->maxay = size.max_aspect.y;
1392 } else {
1393 c->minax = c->minay = c->maxax = c->maxay = 0;
1395 c->isfixed = (c->maxw && c->minw && c->maxh && c->minh &&
1396 c->maxw == c->minw && c->maxh == c->minh);
1399 void
1400 updatetitle(Client *c) {
1401 char **list = NULL;
1402 int n;
1403 XTextProperty name;
1405 name.nitems = 0;
1406 c->name[0] = 0;
1407 XGetTextProperty(dpy, c->win, &name, netatom[NetWMName]);
1408 if(!name.nitems)
1409 XGetWMName(dpy, c->win, &name);
1410 if(!name.nitems)
1411 return;
1412 if(name.encoding == XA_STRING)
1413 strncpy(c->name, (char *)name.value, sizeof c->name);
1414 else {
1415 if(XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success && n > 0 && *list) {
1416 strncpy(c->name, *list, sizeof c->name);
1417 XFreeStringList(list);
1420 XFree(name.value);
1423 void
1424 unmanage(Client *c) {
1425 Client *nc;
1427 /* The server grab construct avoids race conditions. */
1428 XGrabServer(dpy);
1429 XSetErrorHandler(xerrordummy);
1430 detach(c);
1431 detachstack(c);
1432 if(sel == c) {
1433 for(nc = stack; nc && !isvisible(nc); nc = nc->snext);
1434 focus(nc);
1436 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1437 setclientstate(c, WithdrawnState);
1438 free(c);
1439 XSync(dpy, False);
1440 XSetErrorHandler(xerror);
1441 XUngrabServer(dpy);
1442 arrange();
1463 /* static */
1466 static void
1467 cleanup(void) {
1468 close(STDIN_FILENO);
1469 while(stack) {
1470 resize(stack, True);
1471 unmanage(stack);
1473 if(dc.font.set)
1474 XFreeFontSet(dpy, dc.font.set);
1475 else
1476 XFreeFont(dpy, dc.font.xfont);
1477 XUngrabKey(dpy, AnyKey, AnyModifier, root);
1478 XFreePixmap(dpy, dc.drawable);
1479 XFreeGC(dpy, dc.gc);
1480 XDestroyWindow(dpy, barwin);
1481 XFreeCursor(dpy, cursor[CurNormal]);
1482 XFreeCursor(dpy, cursor[CurResize]);
1483 XFreeCursor(dpy, cursor[CurMove]);
1484 XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime);
1485 XSync(dpy, False);
1488 static void
1489 scan(void) {
1490 unsigned int i, num;
1491 Window *wins, d1, d2;
1492 XWindowAttributes wa;
1494 wins = NULL;
1495 if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1496 for(i = 0; i < num; i++) {
1497 if(!XGetWindowAttributes(dpy, wins[i], &wa))
1498 continue;
1499 if(wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1500 continue;
1501 if(wa.map_state == IsViewable)
1502 manage(wins[i], &wa);
1505 if(wins)
1506 XFree(wins);
1509 static void
1510 setup(void) {
1511 int i, j;
1512 unsigned int mask;
1513 Window w;
1514 XModifierKeymap *modmap;
1515 XSetWindowAttributes wa;
1517 /* init atoms */
1518 wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1519 wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1520 wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1521 netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1522 netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1523 XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1524 PropModeReplace, (unsigned char *) netatom, NetLast);
1525 /* init cursors */
1526 cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1527 cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1528 cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1529 /* init modifier map */
1530 numlockmask = 0;
1531 modmap = XGetModifierMapping(dpy);
1532 for (i = 0; i < 8; i++) {
1533 for (j = 0; j < modmap->max_keypermod; j++) {
1534 if(modmap->modifiermap[i * modmap->max_keypermod + j] == XKeysymToKeycode(dpy, XK_Num_Lock))
1535 numlockmask = (1 << i);
1538 XFreeModifiermap(modmap);
1539 /* select for events */
1540 wa.event_mask = SubstructureRedirectMask | SubstructureNotifyMask
1541 | EnterWindowMask | LeaveWindowMask;
1542 wa.cursor = cursor[CurNormal];
1543 XChangeWindowAttributes(dpy, root, CWEventMask | CWCursor, &wa);
1544 grabkeys();
1545 seltag = True;
1546 /* style */
1547 dc.norm[ColBG] = getcolor(NORMBGCOLOR);
1548 dc.norm[ColFG] = getcolor(NORMFGCOLOR);
1549 dc.sel[ColBG] = getcolor(SELBGCOLOR);
1550 dc.sel[ColFG] = getcolor(SELFGCOLOR);
1551 setfont(FONT);
1552 /* geometry */
1553 sx = sy = 0;
1554 sw = DisplayWidth(dpy, screen);
1555 sh = DisplayHeight(dpy, screen);
1556 nmaster = NMASTER;
1557 bmw = 1;
1558 /* bar */
1559 dc.h = bh = dc.font.height + 2;
1560 wa.override_redirect = 1;
1561 wa.background_pixmap = ParentRelative;
1562 wa.event_mask = ButtonPressMask | ExposureMask;
1563 barwin = XCreateWindow(dpy, root, sx, sy, sw, bh, 0,
1564 DefaultDepth(dpy, screen), CopyFromParent, DefaultVisual(dpy, screen),
1565 CWOverrideRedirect | CWBackPixmap | CWEventMask, &wa);
1566 XDefineCursor(dpy, barwin, cursor[CurNormal]);
1567 XMapRaised(dpy, barwin);
1568 strcpy(stext, "dwm-"VERSION);
1569 /* windowarea */
1570 wax = sx;
1571 way = sy + bh;
1572 wah = sh - bh;
1573 waw = sw;
1574 /* pixmap for everything */
1575 dc.drawable = XCreatePixmap(dpy, root, sw, bh, DefaultDepth(dpy, screen));
1576 dc.gc = XCreateGC(dpy, root, 0, 0);
1577 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
1578 /* multihead support */
1579 selscreen = XQueryPointer(dpy, root, &w, &w, &i, &i, &i, &i, &mask);
1582 /*
1583 * Startup Error handler to check if another window manager
1584 * is already running.
1585 */
1586 static int
1587 xerrorstart(Display *dsply, XErrorEvent *ee) {
1588 otherwm = True;
1589 return -1;
1594 void
1595 sendevent(Window w, Atom a, long value) {
1596 XEvent e;
1598 e.type = ClientMessage;
1599 e.xclient.window = w;
1600 e.xclient.message_type = a;
1601 e.xclient.format = 32;
1602 e.xclient.data.l[0] = value;
1603 e.xclient.data.l[1] = CurrentTime;
1604 XSendEvent(dpy, w, False, NoEventMask, &e);
1605 XSync(dpy, False);
1608 void
1609 quit() {
1610 readin = running = False;
1613 /* There's no way to check accesses to destroyed windows, thus those cases are
1614 * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
1615 * default error handler, which may call exit.
1616 */
1617 int
1618 xerror(Display *dpy, XErrorEvent *ee) {
1619 if(ee->error_code == BadWindow
1620 || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1621 || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1622 || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1623 || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1624 || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1625 || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1626 || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1627 return 0;
1628 fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1629 ee->request_code, ee->error_code);
1630 return xerrorxlib(dpy, ee); /* may call exit */
1633 int
1634 main(int argc, char *argv[]) {
1635 char *p;
1636 int r, xfd;
1637 fd_set rd;
1639 if(argc == 2 && !strncmp("-v", argv[1], 3)) {
1640 fputs("dwm-"VERSION", (C)opyright MMVI-MMVII Anselm R. Garbe\n", stdout);
1641 exit(EXIT_SUCCESS);
1642 } else if(argc != 1) {
1643 eprint("usage: dwm [-v]\n");
1645 setlocale(LC_CTYPE, "");
1646 dpy = XOpenDisplay(0);
1647 if(!dpy) {
1648 eprint("dwm: cannot open display\n");
1650 xfd = ConnectionNumber(dpy);
1651 screen = DefaultScreen(dpy);
1652 root = RootWindow(dpy, screen);
1653 otherwm = False;
1654 XSetErrorHandler(xerrorstart);
1655 /* this causes an error if some other window manager is running */
1656 XSelectInput(dpy, root, SubstructureRedirectMask);
1657 XSync(dpy, False);
1658 if(otherwm) {
1659 eprint("dwm: another window manager is already running\n");
1662 XSync(dpy, False);
1663 XSetErrorHandler(NULL);
1664 xerrorxlib = XSetErrorHandler(xerror);
1665 XSync(dpy, False);
1666 setup();
1667 drawstatus();
1668 scan();
1670 /* main event loop, also reads status text from stdin */
1671 XSync(dpy, False);
1672 procevent();
1673 readin = True;
1674 while(running) {
1675 FD_ZERO(&rd);
1676 if(readin)
1677 FD_SET(STDIN_FILENO, &rd);
1678 FD_SET(xfd, &rd);
1679 if(select(xfd + 1, &rd, NULL, NULL, NULL) == -1) {
1680 if(errno == EINTR)
1681 continue;
1682 eprint("select failed\n");
1684 if(FD_ISSET(STDIN_FILENO, &rd)) {
1685 switch(r = read(STDIN_FILENO, stext, sizeof stext - 1)) {
1686 case -1:
1687 strncpy(stext, strerror(errno), sizeof stext - 1);
1688 stext[sizeof stext - 1] = '\0';
1689 readin = False;
1690 break;
1691 case 0:
1692 strncpy(stext, "EOF", 4);
1693 readin = False;
1694 break;
1695 default:
1696 for(stext[r] = '\0', p = stext + strlen(stext) - 1; p >= stext && *p == '\n'; *p-- = '\0');
1697 for(; p >= stext && *p != '\n'; --p);
1698 if(p > stext)
1699 strncpy(stext, p + 1, sizeof stext);
1701 drawstatus();
1703 if(FD_ISSET(xfd, &rd))
1704 procevent();
1706 cleanup();
1707 XCloseDisplay(dpy);
1708 return 0;