1 /* See LICENSE file for copyright and license details.
3 * dynamic window manager is designed like any other X client as well. It is
4 * driven through handling X events. In contrast to other X clients, a window
5 * manager selects for SubstructureRedirectMask on the root window, to receive
6 * events about window (dis-)appearance. Only one X connection at a time is
7 * allowed to select for this event mask.
9 * Calls to fetch an X event from the event queue are blocking. Due reading
10 * status text from standard input, a select()-driven main loop has been
11 * implemented which selects for reads on the X connection and STDIN_FILENO to
12 * handle all data smoothly. The event handlers of dwm are organized in an
13 * array which is accessed whenever a new event has been fetched. This allows
14 * event dispatching in O(1) time.
16 * Each child of the root window is called a client, except windows which have
17 * set the override_redirect flag. Clients are organized in a global
18 * doubly-linked client list, the focus history is remembered through a global
19 * stack list. Each client contains an array of Bools of the same size as the
20 * global tags array to indicate the tags of a client.
22 * Keys and tagging rules are organized as arrays and defined in config.h.
24 * To understand everything else, start reading main().
33 #include <sys/select.h>
34 #include <sys/types.h>
36 #include <X11/cursorfont.h>
37 #include <X11/keysym.h>
38 #include <X11/Xatom.h>
40 #include <X11/Xproto.h>
41 #include <X11/Xutil.h>
44 #define BUTTONMASK (ButtonPressMask|ButtonReleaseMask)
45 #define CLEANMASK(mask) (mask & ~(numlockmask|LockMask))
46 #define LENGTH(x) (sizeof x / sizeof x[0])
48 #define MOUSEMASK (BUTTONMASK|PointerMotionMask)
51 enum { CurNormal, CurResize, CurMove, CurLast }; /* cursor */
52 enum { ColBorder, ColFG, ColBG, ColLast }; /* color */
53 enum { NetSupported, NetWMName, NetLast }; /* EWMH atoms */
54 enum { WMProtocols, WMDelete, WMName, WMState, WMLast };/* default atoms */
57 typedef struct Client Client;
61 int basew, baseh, incw, inch, maxw, maxh, minw, minh;
62 int minax, maxax, minay, maxay;
64 unsigned int border, oldborder;
65 Bool isbanned, isfixed, isfloating, isurgent;
75 unsigned long norm[ColLast];
76 unsigned long sel[ColLast];
86 } DC; /* draw context */
91 void (*func)(const char *arg);
97 void (*arrange)(void);
99 } Layout; /* TODO: layout should keep an auxilliary pointer to its Geometry,
100 instead of having all those layout specific vars globally */
108 /* function declarations */
109 void applyrules(Client *c);
111 void attach(Client *c);
112 void attachstack(Client *c);
114 void buttonpress(XEvent *e);
115 void checkotherwm(void);
117 void configure(Client *c);
118 void configurenotify(XEvent *e);
119 void configurerequest(XEvent *e);
120 void destroynotify(XEvent *e);
121 void detach(Client *c);
122 void detachstack(Client *c);
124 void drawsquare(Bool filled, Bool empty, Bool invert, unsigned long col[ColLast]);
125 void drawtext(const char *text, unsigned long col[ColLast], Bool invert);
126 void *emallocz(unsigned int size);
127 void enternotify(XEvent *e);
128 void eprint(const char *errstr, ...);
129 void expose(XEvent *e);
130 void floating(void); /* default floating layout */
131 void focus(Client *c);
132 void focusin(XEvent *e);
133 void focusnext(const char *arg);
134 void focusprev(const char *arg);
135 Client *getclient(Window w);
136 unsigned long getcolor(const char *colstr);
137 long getstate(Window w);
138 Bool gettextprop(Window w, Atom atom, char *text, unsigned int size);
139 void grabbuttons(Client *c, Bool focused);
141 unsigned int idxoftag(const char *t);
142 void initfont(const char *fontstr);
143 Bool isoccupied(unsigned int t);
144 Bool isprotodel(Client *c);
145 Bool isurgent(unsigned int t);
146 Bool isvisible(Client *c);
147 void keypress(XEvent *e);
148 void killclient(const char *arg);
149 void manage(Window w, XWindowAttributes *wa);
150 void mappingnotify(XEvent *e);
151 void maprequest(XEvent *e);
153 void movemouse(Client *c);
154 Client *nexttiled(Client *c);
155 void propertynotify(XEvent *e);
156 void quit(const char *arg);
157 void reapply(const char *arg);
158 void resize(Client *c, int x, int y, int w, int h, Bool sizehints);
159 void resizemouse(Client *c);
163 void setclientstate(Client *c, long state);
164 void setdefaultgeoms(void);
165 void setlayout(const char *arg);
167 void spawn(const char *arg);
168 void tag(const char *arg);
169 unsigned int textnw(const char *text, unsigned int len);
170 unsigned int textw(const char *text);
172 void tilehstack(unsigned int n);
173 unsigned int tilemaster(void);
175 void tilevstack(unsigned int n);
176 void togglefloating(const char *arg);
177 void toggletag(const char *arg);
178 void toggleview(const char *arg);
179 void unban(Client *c);
180 void unmanage(Client *c);
181 void unmapnotify(XEvent *e);
182 void updatebarpos(void);
183 void updatesizehints(Client *c);
184 void updatetitle(Client *c);
185 void updatewmhints(Client *c);
186 void view(const char *arg);
187 void viewprevtag(const char *arg); /* views previous selected tags */
188 int xerror(Display *dpy, XErrorEvent *ee);
189 int xerrordummy(Display *dpy, XErrorEvent *ee);
190 int xerrorstart(Display *dpy, XErrorEvent *ee);
191 void zoom(const char *arg);
194 char stext[256], buf[256];
195 int screen, sx, sy, sw, sh;
196 int (*xerrorxlib)(Display *, XErrorEvent *);
197 int bx, by, bw, bh, blw, mx, my, mw, mh, mox, moy, mow, moh, tx, ty, tw, th, wx, wy, ww, wh;
198 unsigned int numlockmask = 0;
199 void (*handler[LASTEvent]) (XEvent *) = {
200 [ButtonPress] = buttonpress,
201 [ConfigureRequest] = configurerequest,
202 [ConfigureNotify] = configurenotify,
203 [DestroyNotify] = destroynotify,
204 [EnterNotify] = enternotify,
207 [KeyPress] = keypress,
208 [MappingNotify] = mappingnotify,
209 [MapRequest] = maprequest,
210 [PropertyNotify] = propertynotify,
211 [UnmapNotify] = unmapnotify
213 Atom wmatom[WMLast], netatom[NetLast];
214 Bool otherwm, readin;
218 Client *clients = NULL;
220 Client *stack = NULL;
221 Cursor cursor[CurLast];
226 void (*setgeoms)(void) = setdefaultgeoms;
228 /* configuration, allows nested code to access above variables */
230 #define TAGSZ (LENGTH(tags) * sizeof(Bool))
231 static Bool tmp[LENGTH(tags)];
233 /* function implementations */
236 applyrules(Client *c) {
238 Bool matched = False;
240 XClassHint ch = { 0 };
243 XGetClassHint(dpy, c->win, &ch);
244 for(i = 0; i < LENGTH(rules); i++) {
246 if(strstr(c->name, r->prop)
247 || (ch.res_class && strstr(ch.res_class, r->prop))
248 || (ch.res_name && strstr(ch.res_name, r->prop)))
250 c->isfloating = r->isfloating;
252 c->tags[idxoftag(r->tag)] = True;
262 memcpy(c->tags, seltags, TAGSZ);
269 for(c = clients; c; c = c->next)
289 attachstack(Client *c) {
298 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
303 buttonpress(XEvent *e) {
306 XButtonPressedEvent *ev = &e->xbutton;
308 if(ev->window == barwin) {
310 for(i = 0; i < LENGTH(tags); i++) {
313 if(ev->button == Button1) {
314 if(ev->state & MODKEY)
319 else if(ev->button == Button3) {
320 if(ev->state & MODKEY)
329 else if((c = getclient(ev->window))) {
331 if(CLEANMASK(ev->state) != MODKEY)
333 if(ev->button == Button1) {
337 else if(ev->button == Button2) {
338 if((floating != lt->arrange) && c->isfloating)
339 togglefloating(NULL);
343 else if(ev->button == Button3 && !c->isfixed) {
353 XSetErrorHandler(xerrorstart);
355 /* this causes an error if some other window manager is running */
356 XSelectInput(dpy, DefaultRootWindow(dpy), SubstructureRedirectMask);
359 eprint("dwm: another window manager is already running\n");
361 XSetErrorHandler(NULL);
362 xerrorxlib = XSetErrorHandler(xerror);
374 XFreeFontSet(dpy, dc.font.set);
376 XFreeFont(dpy, dc.font.xfont);
377 XUngrabKey(dpy, AnyKey, AnyModifier, root);
378 XFreePixmap(dpy, dc.drawable);
380 XFreeCursor(dpy, cursor[CurNormal]);
381 XFreeCursor(dpy, cursor[CurResize]);
382 XFreeCursor(dpy, cursor[CurMove]);
383 XDestroyWindow(dpy, barwin);
385 XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime);
389 configure(Client *c) {
392 ce.type = ConfigureNotify;
400 ce.border_width = c->border;
402 ce.override_redirect = False;
403 XSendEvent(dpy, c->win, False, StructureNotifyMask, (XEvent *)&ce);
407 configurenotify(XEvent *e) {
408 XConfigureEvent *ev = &e->xconfigure;
410 if(ev->window == root && (ev->width != sw || ev->height != sh)) {
418 configurerequest(XEvent *e) {
420 XConfigureRequestEvent *ev = &e->xconfigurerequest;
423 if((c = getclient(ev->window))) {
424 if(ev->value_mask & CWBorderWidth)
425 c->border = ev->border_width;
426 if(c->isfixed || c->isfloating || lt->isfloating) {
427 if(ev->value_mask & CWX)
429 if(ev->value_mask & CWY)
431 if(ev->value_mask & CWWidth)
433 if(ev->value_mask & CWHeight)
435 if((c->x - sx + c->w) > sw && c->isfloating)
436 c->x = sx + (sw / 2 - c->w / 2); /* center in x direction */
437 if((c->y - sy + c->h) > sh && c->isfloating)
438 c->y = sy + (sh / 2 - c->h / 2); /* center in y direction */
439 if((ev->value_mask & (CWX|CWY))
440 && !(ev->value_mask & (CWWidth|CWHeight)))
443 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h);
451 wc.width = ev->width;
452 wc.height = ev->height;
453 wc.border_width = ev->border_width;
454 wc.sibling = ev->above;
455 wc.stack_mode = ev->detail;
456 XConfigureWindow(dpy, ev->window, ev->value_mask, &wc);
462 destroynotify(XEvent *e) {
464 XDestroyWindowEvent *ev = &e->xdestroywindow;
466 if((c = getclient(ev->window)))
473 c->prev->next = c->next;
475 c->next->prev = c->prev;
478 c->next = c->prev = NULL;
482 detachstack(Client *c) {
485 for(tc=&stack; *tc && *tc != c; tc=&(*tc)->snext);
495 for(c = stack; c && !isvisible(c); c = c->snext);
496 for(i = 0; i < LENGTH(tags); i++) {
497 dc.w = textw(tags[i]);
499 drawtext(tags[i], dc.sel, isurgent(i));
500 drawsquare(c && c->tags[i], isoccupied(i), isurgent(i), dc.sel);
503 drawtext(tags[i], dc.norm, isurgent(i));
504 drawsquare(c && c->tags[i], isoccupied(i), isurgent(i), dc.norm);
509 drawtext(lt->symbol, dc.norm, False);
517 drawtext(stext, dc.norm, False);
518 if((dc.w = dc.x - x) > bh) {
521 drawtext(c->name, dc.sel, False);
522 drawsquare(False, c->isfloating, False, dc.sel);
525 drawtext(NULL, dc.norm, False);
527 XCopyArea(dpy, dc.drawable, barwin, dc.gc, 0, 0, bw, bh, 0, 0);
532 drawsquare(Bool filled, Bool empty, Bool invert, unsigned long col[ColLast]) {
535 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
537 gcv.foreground = col[invert ? ColBG : ColFG];
538 XChangeGC(dpy, dc.gc, GCForeground, &gcv);
539 x = (dc.font.ascent + dc.font.descent + 2) / 4;
543 r.width = r.height = x + 1;
544 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
547 r.width = r.height = x;
548 XDrawRectangles(dpy, dc.drawable, dc.gc, &r, 1);
553 drawtext(const char *text, unsigned long col[ColLast], Bool invert) {
555 unsigned int len, olen;
556 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
558 XSetForeground(dpy, dc.gc, col[invert ? ColFG : ColBG]);
559 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
563 olen = len = strlen(text);
564 if(len >= sizeof buf)
565 len = sizeof buf - 1;
566 memcpy(buf, text, len);
568 h = dc.font.ascent + dc.font.descent;
569 y = dc.y + (dc.h / 2) - (h / 2) + dc.font.ascent;
571 /* shorten text if necessary */
572 while(len && (w = textnw(buf, len)) > dc.w - h)
583 return; /* too long */
584 XSetForeground(dpy, dc.gc, col[invert ? ColBG : ColFG]);
586 XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
588 XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
592 emallocz(unsigned int size) {
593 void *res = calloc(1, size);
596 eprint("fatal: could not malloc() %u bytes\n", size);
601 enternotify(XEvent *e) {
603 XCrossingEvent *ev = &e->xcrossing;
605 if((ev->mode != NotifyNormal || ev->detail == NotifyInferior) && ev->window != root)
607 if((c = getclient(ev->window)))
614 eprint(const char *errstr, ...) {
617 va_start(ap, errstr);
618 vfprintf(stderr, errstr, ap);
625 XExposeEvent *ev = &e->xexpose;
627 if(ev->count == 0 && (ev->window == barwin))
632 floating(void) { /* default floating layout */
635 for(c = clients; c; c = c->next)
637 resize(c, c->x, c->y, c->w, c->h, True);
642 if(!c || (c && !isvisible(c)))
643 for(c = stack; c && !isvisible(c); c = c->snext);
644 if(sel && sel != c) {
645 grabbuttons(sel, False);
646 XSetWindowBorder(dpy, sel->win, dc.norm[ColBorder]);
651 grabbuttons(c, True);
655 XSetWindowBorder(dpy, c->win, dc.sel[ColBorder]);
656 XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
659 XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
664 focusin(XEvent *e) { /* there are some broken focus acquiring clients */
665 XFocusChangeEvent *ev = &e->xfocus;
667 if(sel && ev->window != sel->win)
668 XSetInputFocus(dpy, sel->win, RevertToPointerRoot, CurrentTime);
672 focusnext(const char *arg) {
677 for(c = sel->next; c && !isvisible(c); c = c->next);
679 for(c = clients; c && !isvisible(c); c = c->next);
687 focusprev(const char *arg) {
692 for(c = sel->prev; c && !isvisible(c); c = c->prev);
694 for(c = clients; c && c->next; c = c->next);
695 for(; c && !isvisible(c); c = c->prev);
704 getclient(Window w) {
707 for(c = clients; c && c->win != w; c = c->next);
712 getcolor(const char *colstr) {
713 Colormap cmap = DefaultColormap(dpy, screen);
716 if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
717 eprint("error, cannot allocate color '%s'\n", colstr);
725 unsigned char *p = NULL;
726 unsigned long n, extra;
729 status = XGetWindowProperty(dpy, w, wmatom[WMState], 0L, 2L, False, wmatom[WMState],
730 &real, &format, &n, &extra, (unsigned char **)&p);
731 if(status != Success)
740 gettextprop(Window w, Atom atom, char *text, unsigned int size) {
745 if(!text || size == 0)
748 XGetTextProperty(dpy, w, &name, atom);
751 if(name.encoding == XA_STRING)
752 strncpy(text, (char *)name.value, size - 1);
754 if(XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success
756 strncpy(text, *list, size - 1);
757 XFreeStringList(list);
760 text[size - 1] = '\0';
766 grabbuttons(Client *c, Bool focused) {
767 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
770 XGrabButton(dpy, Button1, MODKEY, c->win, False, BUTTONMASK,
771 GrabModeAsync, GrabModeSync, None, None);
772 XGrabButton(dpy, Button1, MODKEY|LockMask, c->win, False, BUTTONMASK,
773 GrabModeAsync, GrabModeSync, None, None);
774 XGrabButton(dpy, Button1, MODKEY|numlockmask, c->win, False, BUTTONMASK,
775 GrabModeAsync, GrabModeSync, None, None);
776 XGrabButton(dpy, Button1, MODKEY|numlockmask|LockMask, c->win, False, BUTTONMASK,
777 GrabModeAsync, GrabModeSync, None, None);
779 XGrabButton(dpy, Button2, MODKEY, c->win, False, BUTTONMASK,
780 GrabModeAsync, GrabModeSync, None, None);
781 XGrabButton(dpy, Button2, MODKEY|LockMask, c->win, False, BUTTONMASK,
782 GrabModeAsync, GrabModeSync, None, None);
783 XGrabButton(dpy, Button2, MODKEY|numlockmask, c->win, False, BUTTONMASK,
784 GrabModeAsync, GrabModeSync, None, None);
785 XGrabButton(dpy, Button2, MODKEY|numlockmask|LockMask, c->win, False, BUTTONMASK,
786 GrabModeAsync, GrabModeSync, None, None);
788 XGrabButton(dpy, Button3, MODKEY, c->win, False, BUTTONMASK,
789 GrabModeAsync, GrabModeSync, None, None);
790 XGrabButton(dpy, Button3, MODKEY|LockMask, c->win, False, BUTTONMASK,
791 GrabModeAsync, GrabModeSync, None, None);
792 XGrabButton(dpy, Button3, MODKEY|numlockmask, c->win, False, BUTTONMASK,
793 GrabModeAsync, GrabModeSync, None, None);
794 XGrabButton(dpy, Button3, MODKEY|numlockmask|LockMask, c->win, False, BUTTONMASK,
795 GrabModeAsync, GrabModeSync, None, None);
798 XGrabButton(dpy, AnyButton, AnyModifier, c->win, False, BUTTONMASK,
799 GrabModeAsync, GrabModeSync, None, None);
806 XModifierKeymap *modmap;
808 /* init modifier map */
809 modmap = XGetModifierMapping(dpy);
810 for(i = 0; i < 8; i++)
811 for(j = 0; j < modmap->max_keypermod; j++) {
812 if(modmap->modifiermap[i * modmap->max_keypermod + j] == XKeysymToKeycode(dpy, XK_Num_Lock))
813 numlockmask = (1 << i);
815 XFreeModifiermap(modmap);
817 XUngrabKey(dpy, AnyKey, AnyModifier, root);
818 for(i = 0; i < LENGTH(keys); i++) {
819 code = XKeysymToKeycode(dpy, keys[i].keysym);
820 XGrabKey(dpy, code, keys[i].mod, root, True,
821 GrabModeAsync, GrabModeAsync);
822 XGrabKey(dpy, code, keys[i].mod|LockMask, root, True,
823 GrabModeAsync, GrabModeAsync);
824 XGrabKey(dpy, code, keys[i].mod|numlockmask, root, True,
825 GrabModeAsync, GrabModeAsync);
826 XGrabKey(dpy, code, keys[i].mod|numlockmask|LockMask, root, True,
827 GrabModeAsync, GrabModeAsync);
832 idxoftag(const char *t) {
835 for(i = 0; (i < LENGTH(tags)) && (tags[i] != t); i++);
836 return (i < LENGTH(tags)) ? i : 0;
840 initfont(const char *fontstr) {
841 char *def, **missing;
846 XFreeFontSet(dpy, dc.font.set);
847 dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
850 fprintf(stderr, "dwm: missing fontset: %s\n", missing[n]);
851 XFreeStringList(missing);
854 XFontSetExtents *font_extents;
855 XFontStruct **xfonts;
857 dc.font.ascent = dc.font.descent = 0;
858 font_extents = XExtentsOfFontSet(dc.font.set);
859 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
860 for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
861 if(dc.font.ascent < (*xfonts)->ascent)
862 dc.font.ascent = (*xfonts)->ascent;
863 if(dc.font.descent < (*xfonts)->descent)
864 dc.font.descent = (*xfonts)->descent;
870 XFreeFont(dpy, dc.font.xfont);
871 dc.font.xfont = NULL;
872 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr))
873 && !(dc.font.xfont = XLoadQueryFont(dpy, "fixed")))
874 eprint("error, cannot load font: '%s'\n", fontstr);
875 dc.font.ascent = dc.font.xfont->ascent;
876 dc.font.descent = dc.font.xfont->descent;
878 dc.font.height = dc.font.ascent + dc.font.descent;
882 isoccupied(unsigned int t) {
885 for(c = clients; c; c = c->next)
892 isprotodel(Client *c) {
897 if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
898 for(i = 0; !ret && i < n; i++)
899 if(protocols[i] == wmatom[WMDelete])
907 isurgent(unsigned int t) {
910 for(c = clients; c; c = c->next)
911 if(c->isurgent && c->tags[t])
917 isvisible(Client *c) {
920 for(i = 0; i < LENGTH(tags); i++)
921 if(c->tags[i] && seltags[i])
927 keypress(XEvent *e) {
933 keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
934 for(i = 0; i < LENGTH(keys); i++)
935 if(keysym == keys[i].keysym
936 && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state))
939 keys[i].func(keys[i].arg);
944 killclient(const char *arg) {
949 if(isprotodel(sel)) {
950 ev.type = ClientMessage;
951 ev.xclient.window = sel->win;
952 ev.xclient.message_type = wmatom[WMProtocols];
953 ev.xclient.format = 32;
954 ev.xclient.data.l[0] = wmatom[WMDelete];
955 ev.xclient.data.l[1] = CurrentTime;
956 XSendEvent(dpy, sel->win, False, NoEventMask, &ev);
959 XKillClient(dpy, sel->win);
963 manage(Window w, XWindowAttributes *wa) {
964 Client *c, *t = NULL;
969 c = emallocz(sizeof(Client));
970 c->tags = emallocz(TAGSZ);
978 c->oldborder = wa->border_width;
979 if(c->w == sw && c->h == sh) {
982 c->border = wa->border_width;
985 if(c->x + c->w + 2 * c->border > wx + ww)
986 c->x = wx + ww - c->w - 2 * c->border;
987 if(c->y + c->h + 2 * c->border > wy + wh)
988 c->y = wy + wh - c->h - 2 * c->border;
993 c->border = BORDERPX;
996 wc.border_width = c->border;
997 XConfigureWindow(dpy, w, CWBorderWidth, &wc);
998 XSetWindowBorder(dpy, w, dc.norm[ColBorder]);
999 configure(c); /* propagates border_width, if size doesn't change */
1001 XSelectInput(dpy, w, EnterWindowMask|FocusChangeMask|PropertyChangeMask|StructureNotifyMask);
1002 grabbuttons(c, False);
1004 if((rettrans = XGetTransientForHint(dpy, w, &trans) == Success))
1005 for(t = clients; t && t->win != trans; t = t->next);
1007 memcpy(c->tags, t->tags, TAGSZ);
1011 c->isfloating = (rettrans == Success) || c->isfixed;
1014 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h); /* some windows require this */
1016 XMapWindow(dpy, c->win);
1017 setclientstate(c, NormalState);
1022 mappingnotify(XEvent *e) {
1023 XMappingEvent *ev = &e->xmapping;
1025 XRefreshKeyboardMapping(ev);
1026 if(ev->request == MappingKeyboard)
1031 maprequest(XEvent *e) {
1032 static XWindowAttributes wa;
1033 XMapRequestEvent *ev = &e->xmaprequest;
1035 if(!XGetWindowAttributes(dpy, ev->window, &wa))
1037 if(wa.override_redirect)
1039 if(!getclient(ev->window))
1040 manage(ev->window, &wa);
1047 for(c = clients; c; c = c->next)
1049 resize(c, mox, moy, mow, moh, RESIZEHINTS);
1053 movemouse(Client *c) {
1054 int x1, y1, ocx, ocy, di, nx, ny;
1061 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1062 None, cursor[CurMove], CurrentTime) != GrabSuccess)
1064 XQueryPointer(dpy, root, &dummy, &dummy, &x1, &y1, &di, &di, &dui);
1066 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
1069 XUngrabPointer(dpy, CurrentTime);
1071 case ConfigureRequest:
1074 handler[ev.type](&ev);
1078 nx = ocx + (ev.xmotion.x - x1);
1079 ny = ocy + (ev.xmotion.y - y1);
1080 if(abs(wx - nx) < SNAP)
1082 else if(abs((wx + ww) - (nx + c->w + 2 * c->border)) < SNAP)
1083 nx = wx + ww - c->w - 2 * c->border;
1084 if(abs(wy - ny) < SNAP)
1086 else if(abs((wy + wh) - (ny + c->h + 2 * c->border)) < SNAP)
1087 ny = wy + wh - c->h - 2 * c->border;
1088 if(!c->isfloating && !lt->isfloating && (abs(nx - c->x) > SNAP || abs(ny - c->y) > SNAP))
1089 togglefloating(NULL);
1090 if((lt->isfloating) || c->isfloating)
1091 resize(c, nx, ny, c->w, c->h, False);
1098 nexttiled(Client *c) {
1099 for(; c && (c->isfloating || !isvisible(c)); c = c->next);
1104 propertynotify(XEvent *e) {
1107 XPropertyEvent *ev = &e->xproperty;
1109 if(ev->state == PropertyDelete)
1110 return; /* ignore */
1111 if((c = getclient(ev->window))) {
1114 case XA_WM_TRANSIENT_FOR:
1115 XGetTransientForHint(dpy, c->win, &trans);
1116 if(!c->isfloating && (c->isfloating = (getclient(trans) != NULL)))
1119 case XA_WM_NORMAL_HINTS:
1127 if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
1136 quit(const char *arg) {
1137 readin = running = False;
1141 reapply(const char *arg) {
1142 static Bool zerotags[LENGTH(tags)] = { 0 };
1145 for(c = clients; c; c = c->next) {
1146 memcpy(c->tags, zerotags, sizeof zerotags);
1153 resize(Client *c, int x, int y, int w, int h, Bool sizehints) {
1157 /* set minimum possible */
1163 /* temporarily remove base dimensions */
1167 /* adjust for aspect limits */
1168 if (c->minay > 0 && c->maxay > 0 && c->minax > 0 && c->maxax > 0) {
1169 if (w * c->maxay > h * c->maxax)
1170 w = h * c->maxax / c->maxay;
1171 else if (w * c->minay < h * c->minax)
1172 h = w * c->minay / c->minax;
1175 /* adjust for increment value */
1181 /* restore base dimensions */
1185 if(c->minw > 0 && w < c->minw)
1187 if(c->minh > 0 && h < c->minh)
1189 if(c->maxw > 0 && w > c->maxw)
1191 if(c->maxh > 0 && h > c->maxh)
1194 if(w <= 0 || h <= 0)
1197 x = sw - w - 2 * c->border;
1199 y = sh - h - 2 * c->border;
1200 if(x + w + 2 * c->border < sx)
1202 if(y + h + 2 * c->border < sy)
1204 if(c->x != x || c->y != y || c->w != w || c->h != h) {
1207 c->w = wc.width = w;
1208 c->h = wc.height = h;
1209 wc.border_width = c->border;
1210 XConfigureWindow(dpy, c->win,
1211 CWX|CWY|CWWidth|CWHeight|CWBorderWidth, &wc);
1218 resizemouse(Client *c) {
1225 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1226 None, cursor[CurResize], CurrentTime) != GrabSuccess)
1228 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->border - 1, c->h + c->border - 1);
1230 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask , &ev);
1233 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0,
1234 c->w + c->border - 1, c->h + c->border - 1);
1235 XUngrabPointer(dpy, CurrentTime);
1236 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1238 case ConfigureRequest:
1241 handler[ev.type](&ev);
1245 if((nw = ev.xmotion.x - ocx - 2 * c->border + 1) <= 0)
1247 if((nh = ev.xmotion.y - ocy - 2 * c->border + 1) <= 0)
1249 if(!c->isfloating && !lt->isfloating && (abs(nw - c->w) > SNAP || abs(nh - c->h) > SNAP))
1250 togglefloating(NULL);
1251 if((lt->isfloating) || c->isfloating)
1252 resize(c, c->x, c->y, nw, nh, True);
1267 if(sel->isfloating || lt->isfloating)
1268 XRaiseWindow(dpy, sel->win);
1269 if(!lt->isfloating) {
1270 wc.stack_mode = Below;
1271 wc.sibling = barwin;
1272 if(!sel->isfloating) {
1273 XConfigureWindow(dpy, sel->win, CWSibling|CWStackMode, &wc);
1274 wc.sibling = sel->win;
1276 for(c = nexttiled(clients); c; c = nexttiled(c->next)) {
1279 XConfigureWindow(dpy, c->win, CWSibling|CWStackMode, &wc);
1280 wc.sibling = c->win;
1284 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1290 char sbuf[sizeof stext];
1293 unsigned int len, offset;
1296 /* main event loop, also reads status text from stdin */
1298 xfd = ConnectionNumber(dpy);
1301 len = sizeof stext - 1;
1302 sbuf[len] = stext[len] = '\0'; /* 0-terminator is never touched */
1306 FD_SET(STDIN_FILENO, &rd);
1308 if(select(xfd + 1, &rd, NULL, NULL, NULL) == -1) {
1311 eprint("select failed\n");
1313 if(FD_ISSET(STDIN_FILENO, &rd)) {
1314 switch((r = read(STDIN_FILENO, sbuf + offset, len - offset))) {
1316 strncpy(stext, strerror(errno), len);
1320 strncpy(stext, "EOF", 4);
1324 for(p = sbuf + offset; r > 0; p++, r--, offset++)
1325 if(*p == '\n' || *p == '\0') {
1327 strncpy(stext, sbuf, len);
1328 p += r - 1; /* p is sbuf + offset + r - 1 */
1329 for(r = 0; *(p - r) && *(p - r) != '\n'; r++);
1332 memmove(sbuf, p - r + 1, r);
1339 while(XPending(dpy)) {
1340 XNextEvent(dpy, &ev);
1341 if(handler[ev.type])
1342 (handler[ev.type])(&ev); /* call handler */
1349 unsigned int i, num;
1350 Window *wins, d1, d2;
1351 XWindowAttributes wa;
1354 if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1355 for(i = 0; i < num; i++) {
1356 if(!XGetWindowAttributes(dpy, wins[i], &wa)
1357 || wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1359 if(wa.map_state == IsViewable || getstate(wins[i]) == IconicState)
1360 manage(wins[i], &wa);
1362 for(i = 0; i < num; i++) { /* now the transients */
1363 if(!XGetWindowAttributes(dpy, wins[i], &wa))
1365 if(XGetTransientForHint(dpy, wins[i], &d1)
1366 && (wa.map_state == IsViewable || getstate(wins[i]) == IconicState))
1367 manage(wins[i], &wa);
1375 setclientstate(Client *c, long state) {
1376 long data[] = {state, None};
1378 XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1379 PropModeReplace, (unsigned char *)data, 2);
1383 setdefaultgeoms(void) {
1385 /* screen dimensions */
1388 sw = DisplayWidth(dpy, screen);
1389 sh = DisplayHeight(dpy, screen);
1395 bh = dc.font.height + 2;
1406 mw = ((float)sw) * 0.55;
1423 setlayout(const char *arg) {
1424 static Layout *revert = 0;
1429 for(i = 0; i < LENGTH(layouts); i++)
1430 if(!strcmp(arg, layouts[i].symbol))
1432 if(i == LENGTH(layouts))
1434 if(revert && &layouts[i] == lt)
1449 XSetWindowAttributes wa;
1452 screen = DefaultScreen(dpy);
1453 root = RootWindow(dpy, screen);
1456 /* apply default geometries */
1460 wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1461 wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1462 wmatom[WMName] = XInternAtom(dpy, "WM_NAME", False);
1463 wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1464 netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1465 netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1468 wa.cursor = cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1469 cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1470 cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1472 /* init appearance */
1473 dc.norm[ColBorder] = getcolor(NORMBORDERCOLOR);
1474 dc.norm[ColBG] = getcolor(NORMBGCOLOR);
1475 dc.norm[ColFG] = getcolor(NORMFGCOLOR);
1476 dc.sel[ColBorder] = getcolor(SELBORDERCOLOR);
1477 dc.sel[ColBG] = getcolor(SELBGCOLOR);
1478 dc.sel[ColFG] = getcolor(SELFGCOLOR);
1481 dc.drawable = XCreatePixmap(dpy, root, DisplayWidth(dpy, screen), bh, DefaultDepth(dpy, screen));
1482 dc.gc = XCreateGC(dpy, root, 0, 0);
1483 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
1485 XSetFont(dpy, dc.gc, dc.font.xfont->fid);
1488 seltags = emallocz(TAGSZ);
1489 prevtags = emallocz(TAGSZ);
1490 seltags[0] = prevtags[0] = True;
1496 for(blw = i = 0; i < LENGTH(layouts); i++) {
1497 i = textw(layouts[i].symbol);
1502 wa.override_redirect = 1;
1503 wa.background_pixmap = ParentRelative;
1504 wa.event_mask = ButtonPressMask|ExposureMask;
1506 barwin = XCreateWindow(dpy, root, bx, by, bw, bh, 0, DefaultDepth(dpy, screen),
1507 CopyFromParent, DefaultVisual(dpy, screen),
1508 CWOverrideRedirect|CWBackPixmap|CWEventMask, &wa);
1509 XDefineCursor(dpy, barwin, cursor[CurNormal]);
1510 XMapRaised(dpy, barwin);
1511 strcpy(stext, "dwm-"VERSION);
1514 /* EWMH support per view */
1515 XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1516 PropModeReplace, (unsigned char *) netatom, NetLast);
1518 /* select for events */
1519 wa.event_mask = SubstructureRedirectMask|SubstructureNotifyMask
1520 |EnterWindowMask|LeaveWindowMask|StructureNotifyMask;
1521 XChangeWindowAttributes(dpy, root, CWEventMask|CWCursor, &wa);
1522 XSelectInput(dpy, root, wa.event_mask);
1530 spawn(const char *arg) {
1531 static char *shell = NULL;
1533 if(!shell && !(shell = getenv("SHELL")))
1537 /* The double-fork construct avoids zombie processes and keeps the code
1538 * clean from stupid signal handlers. */
1542 close(ConnectionNumber(dpy));
1544 execl(shell, shell, "-c", arg, (char *)NULL);
1545 fprintf(stderr, "dwm: execl '%s -c %s'", shell, arg);
1554 tag(const char *arg) {
1559 for(i = 0; i < LENGTH(tags); i++)
1560 sel->tags[i] = (NULL == arg);
1561 sel->tags[idxoftag(arg)] = True;
1566 textnw(const char *text, unsigned int len) {
1570 XmbTextExtents(dc.font.set, text, len, NULL, &r);
1573 return XTextWidth(dc.font.xfont, text, len);
1577 textw(const char *text) {
1578 return textnw(text, strlen(text)) + dc.font.height;
1582 tileresize(Client *c, int x, int y, int w, int h) {
1583 resize(c, x, y, w, h, RESIZEHINTS);
1584 if((RESIZEHINTS) && ((c->h < bh) || (c->h > h) || (c->w < bh) || (c->w > w)))
1585 /* client doesn't accept size constraints */
1586 resize(c, x, y, w, h, False);
1591 tilehstack(tilemaster());
1595 tilehstack(unsigned int n) {
1607 for(i = 0, c = nexttiled(clients); c; c = nexttiled(c->next), i++)
1609 if(i > 1 && i == n) /* remainder */
1610 tileresize(c, x, ty, (tx + tw) - x - 2 * c->border,
1611 th - 2 * c->border);
1613 tileresize(c, x, ty, w - 2 * c->border,
1614 th - 2 * c->border);
1616 x = c->x + c->w + 2 * c->border;
1625 for(n = 0, mc = c = nexttiled(clients); c; c = nexttiled(c->next))
1630 tileresize(mc, mox, moy, mow - 2 * mc->border, moh - 2 * mc->border);
1632 tileresize(mc, mx, my, mw - 2 * mc->border, mh - 2 * mc->border);
1638 tilevstack(tilemaster());
1642 tilevstack(unsigned int n) {
1654 for(i = 0, c = nexttiled(clients); c; c = nexttiled(c->next), i++)
1656 if(i > 1 && i == n) /* remainder */
1657 tileresize(c, tx, y, tw - 2 * c->border,
1658 (ty + th) - y - 2 * c->border);
1660 tileresize(c, tx, y, tw - 2 * c->border,
1663 y = c->y + c->h + 2 * c->border;
1668 togglefloating(const char *arg) {
1671 sel->isfloating = !sel->isfloating;
1673 resize(sel, sel->x, sel->y, sel->w, sel->h, True);
1678 toggletag(const char *arg) {
1684 sel->tags[i] = !sel->tags[i];
1685 for(j = 0; j < LENGTH(tags) && !sel->tags[j]; j++);
1686 if(j == LENGTH(tags))
1687 sel->tags[i] = True; /* at least one tag must be enabled */
1692 toggleview(const char *arg) {
1696 seltags[i] = !seltags[i];
1697 for(j = 0; j < LENGTH(tags) && !seltags[j]; j++);
1698 if(j == LENGTH(tags))
1699 seltags[i] = True; /* at least one tag must be viewed */
1707 XMoveWindow(dpy, c->win, c->x, c->y);
1708 c->isbanned = False;
1712 unmanage(Client *c) {
1715 wc.border_width = c->oldborder;
1716 /* The server grab construct avoids race conditions. */
1718 XSetErrorHandler(xerrordummy);
1719 XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
1724 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1725 setclientstate(c, WithdrawnState);
1729 XSetErrorHandler(xerror);
1735 unmapnotify(XEvent *e) {
1737 XUnmapEvent *ev = &e->xunmap;
1739 if((c = getclient(ev->window)))
1744 updatebarpos(void) {
1746 if(dc.drawable != 0)
1747 XFreePixmap(dpy, dc.drawable);
1748 dc.drawable = XCreatePixmap(dpy, root, bw, bh, DefaultDepth(dpy, screen));
1749 XMoveResizeWindow(dpy, barwin, bx, by, bw, bh);
1753 updatesizehints(Client *c) {
1757 if(!XGetWMNormalHints(dpy, c->win, &size, &msize) || !size.flags)
1759 c->flags = size.flags;
1760 if(c->flags & PBaseSize) {
1761 c->basew = size.base_width;
1762 c->baseh = size.base_height;
1764 else if(c->flags & PMinSize) {
1765 c->basew = size.min_width;
1766 c->baseh = size.min_height;
1769 c->basew = c->baseh = 0;
1770 if(c->flags & PResizeInc) {
1771 c->incw = size.width_inc;
1772 c->inch = size.height_inc;
1775 c->incw = c->inch = 0;
1776 if(c->flags & PMaxSize) {
1777 c->maxw = size.max_width;
1778 c->maxh = size.max_height;
1781 c->maxw = c->maxh = 0;
1782 if(c->flags & PMinSize) {
1783 c->minw = size.min_width;
1784 c->minh = size.min_height;
1786 else if(c->flags & PBaseSize) {
1787 c->minw = size.base_width;
1788 c->minh = size.base_height;
1791 c->minw = c->minh = 0;
1792 if(c->flags & PAspect) {
1793 c->minax = size.min_aspect.x;
1794 c->maxax = size.max_aspect.x;
1795 c->minay = size.min_aspect.y;
1796 c->maxay = size.max_aspect.y;
1799 c->minax = c->maxax = c->minay = c->maxay = 0;
1800 c->isfixed = (c->maxw && c->minw && c->maxh && c->minh
1801 && c->maxw == c->minw && c->maxh == c->minh);
1805 updatetitle(Client *c) {
1806 if(!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
1807 gettextprop(c->win, wmatom[WMName], c->name, sizeof c->name);
1811 updatewmhints(Client *c) {
1814 if((wmh = XGetWMHints(dpy, c->win))) {
1816 sel->isurgent = False;
1818 c->isurgent = (wmh->flags & XUrgencyHint) ? True : False;
1825 view(const char *arg) {
1828 for(i = 0; i < LENGTH(tags); i++)
1829 tmp[i] = (NULL == arg);
1830 tmp[idxoftag(arg)] = True;
1832 if(memcmp(seltags, tmp, TAGSZ) != 0) {
1833 memcpy(prevtags, seltags, TAGSZ);
1834 memcpy(seltags, tmp, TAGSZ);
1840 viewprevtag(const char *arg) {
1842 memcpy(tmp, seltags, TAGSZ);
1843 memcpy(seltags, prevtags, TAGSZ);
1844 memcpy(prevtags, tmp, TAGSZ);
1848 /* There's no way to check accesses to destroyed windows, thus those cases are
1849 * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
1850 * default error handler, which may call exit. */
1852 xerror(Display *dpy, XErrorEvent *ee) {
1853 if(ee->error_code == BadWindow
1854 || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1855 || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1856 || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1857 || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1858 || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1859 || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1860 || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1862 fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1863 ee->request_code, ee->error_code);
1864 return xerrorxlib(dpy, ee); /* may call exit */
1868 xerrordummy(Display *dpy, XErrorEvent *ee) {
1872 /* Startup Error handler to check if another window manager
1873 * is already running. */
1875 xerrorstart(Display *dpy, XErrorEvent *ee) {
1881 zoom(const char *arg) {
1884 if(!sel || lt->isfloating || sel->isfloating)
1886 if(c == nexttiled(clients))
1887 if(!(c = nexttiled(c->next)))
1896 main(int argc, char *argv[]) {
1897 if(argc == 2 && !strcmp("-v", argv[1]))
1898 eprint("dwm-"VERSION", © 2006-2008 dwm engineers, see LICENSE for details\n");
1900 eprint("usage: dwm [-v]\n");
1902 setlocale(LC_CTYPE, "");
1903 if(!(dpy = XOpenDisplay(0)))
1904 eprint("dwm: cannot open display\n");