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 MAX(a, b) ((a) > (b) ? (a) : (b))
45 #define MIN(a, b) ((a) < (b) ? (a) : (b))
46 #define BUTTONMASK (ButtonPressMask|ButtonReleaseMask)
47 #define CLEANMASK(mask) (mask & ~(numlockmask|LockMask))
48 #define LENGTH(x) (sizeof x / sizeof x[0])
50 #define MOUSEMASK (BUTTONMASK|PointerMotionMask)
53 enum { CurNormal, CurResize, CurMove, CurLast }; /* cursor */
54 enum { ColBorder, ColFG, ColBG, ColLast }; /* color */
55 enum { NetSupported, NetWMName, NetLast }; /* EWMH atoms */
56 enum { WMProtocols, WMDelete, WMName, WMState, WMLast };/* default atoms */
59 typedef struct Client Client;
64 int basew, baseh, incw, inch, maxw, maxh, minw, minh;
65 int minax, maxax, minay, maxay;
67 unsigned int bw, oldbw;
68 Bool isbanned, isfixed, isfloating, isurgent;
78 unsigned long norm[ColLast];
79 unsigned long sel[ColLast];
89 } DC; /* draw context */
94 void (*func)(const char *arg);
100 void (*arrange)(void);
106 const char *instance;
112 /* function declarations */
113 void applyrules(Client *c);
115 void attach(Client *c);
116 void attachstack(Client *c);
118 void buttonpress(XEvent *e);
119 void checkotherwm(void);
121 void configure(Client *c);
122 void configurenotify(XEvent *e);
123 void configurerequest(XEvent *e);
124 unsigned int counttiled(void);
125 void destroynotify(XEvent *e);
126 void detach(Client *c);
127 void detachstack(Client *c);
129 void drawsquare(Bool filled, Bool empty, Bool invert, unsigned long col[ColLast]);
130 void drawtext(const char *text, unsigned long col[ColLast], Bool invert);
131 void *emallocz(unsigned int size);
132 void enternotify(XEvent *e);
133 void eprint(const char *errstr, ...);
134 void expose(XEvent *e);
135 void focus(Client *c);
136 void focusin(XEvent *e);
137 void focusnext(const char *arg);
138 void focusprev(const char *arg);
139 Client *getclient(Window w);
140 unsigned long getcolor(const char *colstr);
141 long getstate(Window w);
142 Bool gettextprop(Window w, Atom atom, char *text, unsigned int size);
143 void grabbuttons(Client *c, Bool focused);
145 unsigned int idxoftag(const char *t);
146 void initfont(const char *fontstr);
147 Bool isoccupied(unsigned int t);
148 Bool isprotodel(Client *c);
149 Bool isurgent(unsigned int t);
150 Bool isvisible(Client *c, Bool *cmp);
151 void keypress(XEvent *e);
152 void killclient(const char *arg);
153 void manage(Window w, XWindowAttributes *wa);
154 void mappingnotify(XEvent *e);
155 void maprequest(XEvent *e);
157 void movemouse(Client *c);
158 Client *nexttiled(Client *c);
159 void propertynotify(XEvent *e);
160 void quit(const char *arg);
161 void resize(Client *c, int x, int y, int w, int h, Bool sizehints);
162 void resizemouse(Client *c);
166 void setclientstate(Client *c, long state);
167 void setmfact(const char *arg);
169 void spawn(const char *arg);
170 void tag(const char *arg);
171 unsigned int textnw(const char *text, unsigned int len);
172 unsigned int textw(const char *text);
174 void tilehstack(unsigned int n);
175 Client *tilemaster(unsigned int n);
176 void tileresize(Client *c, int x, int y, int w, int h);
178 void tilevstack(unsigned int n);
179 void togglefloating(const char *arg);
180 void togglelayout(const char *arg);
181 void toggletag(const char *arg);
182 void toggleview(const char *arg);
183 void unban(Client *c);
184 void unmanage(Client *c);
185 void unmapnotify(XEvent *e);
186 void updatebar(void);
187 void updategeom(void);
188 void updatesizehints(Client *c);
189 void updatetitle(Client *c);
190 void updatewmhints(Client *c);
191 void view(const char *arg);
192 void viewprevtag(const char *arg); /* views previous selected tags */
193 int xerror(Display *dpy, XErrorEvent *ee);
194 int xerrordummy(Display *dpy, XErrorEvent *ee);
195 int xerrorstart(Display *dpy, XErrorEvent *ee);
196 void zoom(const char *arg);
200 int screen, sx, sy, sw, sh;
201 int (*xerrorxlib)(Display *, XErrorEvent *);
202 int bx, by, bw, bh, blw, mx, my, mw, mh, tx, ty, tw, th, wx, wy, ww, wh;
205 unsigned int numlockmask = 0;
206 void (*handler[LASTEvent]) (XEvent *) = {
207 [ButtonPress] = buttonpress,
208 [ConfigureRequest] = configurerequest,
209 [ConfigureNotify] = configurenotify,
210 [DestroyNotify] = destroynotify,
211 [EnterNotify] = enternotify,
214 [KeyPress] = keypress,
215 [MappingNotify] = mappingnotify,
216 [MapRequest] = maprequest,
217 [PropertyNotify] = propertynotify,
218 [UnmapNotify] = unmapnotify
220 Atom wmatom[WMLast], netatom[NetLast];
221 Bool otherwm, readin;
224 Client *clients = NULL;
226 Client *stack = NULL;
227 Cursor cursor[CurLast];
231 Layout *lt = layouts;
234 /* configuration, allows nested code to access above variables */
236 #define TAGSZ (LENGTH(tags) * sizeof(Bool))
238 /* function implementations */
241 applyrules(Client *c) {
243 Bool matched = False;
245 XClassHint ch = { 0 };
248 XGetClassHint(dpy, c->win, &ch);
249 for(i = 0; i < LENGTH(rules); i++) {
251 if((!r->title || strstr(c->name, r->title))
252 && (!r->class || (ch.res_class && strstr(ch.res_class, r->class)))
253 && (!r->instance || (ch.res_name && strstr(ch.res_name, r->instance)))) {
254 c->isfloating = r->isfloating;
256 c->tags[idxoftag(r->tag)] = True;
266 memcpy(c->tags, tagset[seltags], TAGSZ);
273 for(c = clients; c; c = c->next)
274 if(isvisible(c, NULL)) {
276 if(lt->isfloating || c->isfloating)
277 resize(c, c->fx, c->fy, c->fw, c->fh, True);
297 attachstack(Client *c) {
306 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
311 buttonpress(XEvent *e) {
314 XButtonPressedEvent *ev = &e->xbutton;
316 if(ev->window == barwin) {
318 for(i = 0; i < LENGTH(tags); i++) {
321 if(ev->button == Button1) {
322 if(ev->state & MODKEY)
327 else if(ev->button == Button3) {
328 if(ev->state & MODKEY)
336 if((ev->x < x + blw) && ev->button == Button1)
339 else if((c = getclient(ev->window))) {
341 if(CLEANMASK(ev->state) != MODKEY)
343 if(ev->button == Button1) {
347 else if(ev->button == Button2) {
348 if(!lt->isfloating && c->isfloating)
349 togglefloating(NULL);
353 else if(ev->button == Button3 && !c->isfixed) {
363 XSetErrorHandler(xerrorstart);
365 /* this causes an error if some other window manager is running */
366 XSelectInput(dpy, DefaultRootWindow(dpy), SubstructureRedirectMask);
369 eprint("dwm: another window manager is already running\n");
371 XSetErrorHandler(NULL);
372 xerrorxlib = XSetErrorHandler(xerror);
384 XFreeFontSet(dpy, dc.font.set);
386 XFreeFont(dpy, dc.font.xfont);
387 XUngrabKey(dpy, AnyKey, AnyModifier, root);
388 XFreePixmap(dpy, dc.drawable);
390 XFreeCursor(dpy, cursor[CurNormal]);
391 XFreeCursor(dpy, cursor[CurResize]);
392 XFreeCursor(dpy, cursor[CurMove]);
393 XDestroyWindow(dpy, barwin);
395 XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime);
399 configure(Client *c) {
402 ce.type = ConfigureNotify;
410 ce.border_width = c->bw;
412 ce.override_redirect = False;
413 XSendEvent(dpy, c->win, False, StructureNotifyMask, (XEvent *)&ce);
417 configurenotify(XEvent *e) {
418 XConfigureEvent *ev = &e->xconfigure;
420 if(ev->window == root && (ev->width != sw || ev->height != sh)) {
430 configurerequest(XEvent *e) {
432 XConfigureRequestEvent *ev = &e->xconfigurerequest;
435 if((c = getclient(ev->window))) {
436 if(ev->value_mask & CWBorderWidth)
437 c->bw = ev->border_width;
438 if(c->isfixed || c->isfloating || lt->isfloating) {
439 if(ev->value_mask & CWX)
441 if(ev->value_mask & CWY)
443 if(ev->value_mask & CWWidth)
445 if(ev->value_mask & CWHeight)
447 if((c->x - sx + c->w) > sw && c->isfloating)
448 c->x = sx + (sw / 2 - c->w / 2); /* center in x direction */
449 if((c->y - sy + c->h) > sh && c->isfloating)
450 c->y = sy + (sh / 2 - c->h / 2); /* center in y direction */
451 if((ev->value_mask & (CWX|CWY))
452 && !(ev->value_mask & (CWWidth|CWHeight)))
454 if(isvisible(c, NULL))
455 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h);
463 wc.width = ev->width;
464 wc.height = ev->height;
465 wc.border_width = ev->border_width;
466 wc.sibling = ev->above;
467 wc.stack_mode = ev->detail;
468 XConfigureWindow(dpy, ev->window, ev->value_mask, &wc);
478 for(n = 0, c = nexttiled(clients); c; c = nexttiled(c->next), n++);
483 destroynotify(XEvent *e) {
485 XDestroyWindowEvent *ev = &e->xdestroywindow;
487 if((c = getclient(ev->window)))
494 c->prev->next = c->next;
496 c->next->prev = c->prev;
499 c->next = c->prev = NULL;
503 detachstack(Client *c) {
506 for(tc = &stack; *tc && *tc != c; tc = &(*tc)->snext);
516 for(c = stack; c && !isvisible(c, NULL); c = c->snext);
517 for(i = 0; i < LENGTH(tags); i++) {
518 dc.w = textw(tags[i]);
519 if(tagset[seltags][i]) {
520 drawtext(tags[i], dc.sel, isurgent(i));
521 drawsquare(c && c->tags[i], isoccupied(i), isurgent(i), dc.sel);
524 drawtext(tags[i], dc.norm, isurgent(i));
525 drawsquare(c && c->tags[i], isoccupied(i), isurgent(i), dc.norm);
531 drawtext(lt->symbol, dc.norm, False);
542 drawtext(stext, dc.norm, False);
543 if((dc.w = dc.x - x) > bh) {
546 drawtext(c->name, dc.sel, False);
547 drawsquare(False, c->isfloating, False, dc.sel);
550 drawtext(NULL, dc.norm, False);
552 XCopyArea(dpy, dc.drawable, barwin, dc.gc, 0, 0, bw, bh, 0, 0);
557 drawsquare(Bool filled, Bool empty, Bool invert, unsigned long col[ColLast]) {
560 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
562 gcv.foreground = col[invert ? ColBG : ColFG];
563 XChangeGC(dpy, dc.gc, GCForeground, &gcv);
564 x = (dc.font.ascent + dc.font.descent + 2) / 4;
568 r.width = r.height = x + 1;
569 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
572 r.width = r.height = x;
573 XDrawRectangles(dpy, dc.drawable, dc.gc, &r, 1);
578 drawtext(const char *text, unsigned long col[ColLast], Bool invert) {
580 unsigned int len, olen;
581 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
584 XSetForeground(dpy, dc.gc, col[invert ? ColFG : ColBG]);
585 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
589 len = MIN(olen, sizeof buf);
590 memcpy(buf, text, len);
592 h = dc.font.ascent + dc.font.descent;
593 y = dc.y + (dc.h / 2) - (h / 2) + dc.font.ascent;
595 /* shorten text if necessary */
596 for(; len && (w = textnw(buf, len)) > dc.w - h; len--);
607 XSetForeground(dpy, dc.gc, col[invert ? ColBG : ColFG]);
609 XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
611 XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
615 emallocz(unsigned int size) {
616 void *res = calloc(1, size);
619 eprint("fatal: could not malloc() %u bytes\n", size);
624 enternotify(XEvent *e) {
626 XCrossingEvent *ev = &e->xcrossing;
628 if((ev->mode != NotifyNormal || ev->detail == NotifyInferior) && ev->window != root)
630 if((c = getclient(ev->window)))
637 eprint(const char *errstr, ...) {
640 va_start(ap, errstr);
641 vfprintf(stderr, errstr, ap);
648 XExposeEvent *ev = &e->xexpose;
650 if(ev->count == 0 && (ev->window == barwin))
656 if(!c || (c && !isvisible(c, NULL)))
657 for(c = stack; c && !isvisible(c, NULL); c = c->snext);
658 if(sel && sel != c) {
659 grabbuttons(sel, False);
660 XSetWindowBorder(dpy, sel->win, dc.norm[ColBorder]);
665 grabbuttons(c, True);
669 XSetWindowBorder(dpy, c->win, dc.sel[ColBorder]);
670 XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
673 XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
678 focusin(XEvent *e) { /* there are some broken focus acquiring clients */
679 XFocusChangeEvent *ev = &e->xfocus;
681 if(sel && ev->window != sel->win)
682 XSetInputFocus(dpy, sel->win, RevertToPointerRoot, CurrentTime);
686 focusnext(const char *arg) {
691 for(c = sel->next; c && !isvisible(c, arg ? sel->tags : NULL); c = c->next);
693 for(c = clients; c && !isvisible(c, arg ? sel->tags : NULL); c = c->next);
701 focusprev(const char *arg) {
706 for(c = sel->prev; c && !isvisible(c, arg ? sel->tags : NULL); c = c->prev);
708 for(c = clients; c && c->next; c = c->next);
709 for(; c && !isvisible(c, arg ? sel->tags : NULL); c = c->prev);
718 getclient(Window w) {
721 for(c = clients; c && c->win != w; c = c->next);
726 getcolor(const char *colstr) {
727 Colormap cmap = DefaultColormap(dpy, screen);
730 if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
731 eprint("error, cannot allocate color '%s'\n", colstr);
739 unsigned char *p = NULL;
740 unsigned long n, extra;
743 status = XGetWindowProperty(dpy, w, wmatom[WMState], 0L, 2L, False, wmatom[WMState],
744 &real, &format, &n, &extra, (unsigned char **)&p);
745 if(status != Success)
754 gettextprop(Window w, Atom atom, char *text, unsigned int size) {
759 if(!text || size == 0)
762 XGetTextProperty(dpy, w, &name, atom);
765 if(name.encoding == XA_STRING)
766 strncpy(text, (char *)name.value, size - 1);
768 if(XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success
770 strncpy(text, *list, size - 1);
771 XFreeStringList(list);
774 text[size - 1] = '\0';
780 grabbuttons(Client *c, Bool focused) {
782 unsigned int buttons[] = { Button1, Button2, Button3 };
783 unsigned int modifiers[] = { MODKEY, MODKEY|LockMask, MODKEY|numlockmask,
784 MODKEY|numlockmask|LockMask} ;
786 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
788 for(i = 0; i < LENGTH(buttons); i++)
789 for(j = 0; j < LENGTH(modifiers); j++)
790 XGrabButton(dpy, buttons[i], modifiers[j], c->win, False,
791 BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
793 XGrabButton(dpy, AnyButton, AnyModifier, c->win, False,
794 BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
801 XModifierKeymap *modmap;
803 /* init modifier map */
804 modmap = XGetModifierMapping(dpy);
805 for(i = 0; i < 8; i++)
806 for(j = 0; j < modmap->max_keypermod; j++) {
807 if(modmap->modifiermap[i * modmap->max_keypermod + j] == XKeysymToKeycode(dpy, XK_Num_Lock))
808 numlockmask = (1 << i);
810 XFreeModifiermap(modmap);
812 XUngrabKey(dpy, AnyKey, AnyModifier, root);
813 for(i = 0; i < LENGTH(keys); i++) {
814 code = XKeysymToKeycode(dpy, keys[i].keysym);
815 XGrabKey(dpy, code, keys[i].mod, root, True,
816 GrabModeAsync, GrabModeAsync);
817 XGrabKey(dpy, code, keys[i].mod|LockMask, root, True,
818 GrabModeAsync, GrabModeAsync);
819 XGrabKey(dpy, code, keys[i].mod|numlockmask, root, True,
820 GrabModeAsync, GrabModeAsync);
821 XGrabKey(dpy, code, keys[i].mod|numlockmask|LockMask, root, True,
822 GrabModeAsync, GrabModeAsync);
827 idxoftag(const char *t) {
830 for(i = 0; (i < LENGTH(tags)) && t && strcmp(tags[i], t); i++);
831 return (i < LENGTH(tags)) ? i : 0;
835 initfont(const char *fontstr) {
836 char *def, **missing;
841 XFreeFontSet(dpy, dc.font.set);
842 dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
845 fprintf(stderr, "dwm: missing fontset: %s\n", missing[n]);
846 XFreeStringList(missing);
849 XFontSetExtents *font_extents;
850 XFontStruct **xfonts;
852 dc.font.ascent = dc.font.descent = 0;
853 font_extents = XExtentsOfFontSet(dc.font.set);
854 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
855 for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
856 dc.font.ascent = MAX(dc.font.ascent, (*xfonts)->ascent);
857 dc.font.descent = MAX(dc.font.descent,(*xfonts)->descent);
863 XFreeFont(dpy, dc.font.xfont);
864 dc.font.xfont = NULL;
865 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr))
866 && !(dc.font.xfont = XLoadQueryFont(dpy, "fixed")))
867 eprint("error, cannot load font: '%s'\n", fontstr);
868 dc.font.ascent = dc.font.xfont->ascent;
869 dc.font.descent = dc.font.xfont->descent;
871 dc.font.height = dc.font.ascent + dc.font.descent;
875 isoccupied(unsigned int t) {
878 for(c = clients; c; c = c->next)
885 isprotodel(Client *c) {
890 if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
891 for(i = 0; !ret && i < n; i++)
892 if(protocols[i] == wmatom[WMDelete])
900 isurgent(unsigned int t) {
903 for(c = clients; c; c = c->next)
904 if(c->isurgent && c->tags[t])
910 isvisible(Client *c, Bool *cmp) {
914 cmp = tagset[seltags];
915 for(i = 0; i < LENGTH(tags); i++)
916 if(c->tags[i] && cmp[i])
922 keypress(XEvent *e) {
928 keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
929 for(i = 0; i < LENGTH(keys); i++)
930 if(keysym == keys[i].keysym
931 && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state))
934 keys[i].func(keys[i].arg);
939 killclient(const char *arg) {
944 if(isprotodel(sel)) {
945 ev.type = ClientMessage;
946 ev.xclient.window = sel->win;
947 ev.xclient.message_type = wmatom[WMProtocols];
948 ev.xclient.format = 32;
949 ev.xclient.data.l[0] = wmatom[WMDelete];
950 ev.xclient.data.l[1] = CurrentTime;
951 XSendEvent(dpy, sel->win, False, NoEventMask, &ev);
954 XKillClient(dpy, sel->win);
958 manage(Window w, XWindowAttributes *wa) {
959 Client *c, *t = NULL;
964 c = emallocz(sizeof(Client));
965 c->tags = emallocz(TAGSZ);
971 c->w = c->fw = wa->width;
972 c->h = c->fh = wa->height;
973 c->oldbw = wa->border_width;
974 if(c->w == sw && c->h == sh) {
977 c->bw = wa->border_width;
980 if(c->x + c->w + 2 * c->bw > wx + ww)
981 c->x = wx + ww - c->w - 2 * c->bw;
982 if(c->y + c->h + 2 * c->bw > wy + wh)
983 c->y = wy + wh - c->h - 2 * c->bw;
984 c->x = MAX(c->x, wx);
985 c->y = MAX(c->y, wy);
991 wc.border_width = c->bw;
992 XConfigureWindow(dpy, w, CWBorderWidth, &wc);
993 XSetWindowBorder(dpy, w, dc.norm[ColBorder]);
994 configure(c); /* propagates border_width, if size doesn't change */
996 XSelectInput(dpy, w, EnterWindowMask|FocusChangeMask|PropertyChangeMask|StructureNotifyMask);
997 grabbuttons(c, False);
999 if((rettrans = XGetTransientForHint(dpy, w, &trans) == Success))
1000 for(t = clients; t && t->win != trans; t = t->next);
1002 memcpy(c->tags, t->tags, TAGSZ);
1006 c->isfloating = (rettrans == Success) || c->isfixed;
1009 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h); /* some windows require this */
1011 XMapWindow(dpy, c->win);
1012 setclientstate(c, NormalState);
1017 mappingnotify(XEvent *e) {
1018 XMappingEvent *ev = &e->xmapping;
1020 XRefreshKeyboardMapping(ev);
1021 if(ev->request == MappingKeyboard)
1026 maprequest(XEvent *e) {
1027 static XWindowAttributes wa;
1028 XMapRequestEvent *ev = &e->xmaprequest;
1030 if(!XGetWindowAttributes(dpy, ev->window, &wa))
1032 if(wa.override_redirect)
1034 if(!getclient(ev->window))
1035 manage(ev->window, &wa);
1042 for(c = clients; c; c = c->next)
1043 if((lt->isfloating || !c->isfloating) && isvisible(c, NULL))
1044 resize(c, wx, wy, ww - 2 * c->bw, wh - 2 * c->bw, RESIZEHINTS);
1048 movemouse(Client *c) {
1049 int x1, y1, ocx, ocy, di, nx, ny;
1056 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1057 None, cursor[CurMove], CurrentTime) != GrabSuccess)
1059 XQueryPointer(dpy, root, &dummy, &dummy, &x1, &y1, &di, &di, &dui);
1061 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
1064 XUngrabPointer(dpy, CurrentTime);
1066 case ConfigureRequest:
1069 handler[ev.type](&ev);
1073 nx = ocx + (ev.xmotion.x - x1);
1074 ny = ocy + (ev.xmotion.y - y1);
1075 if(abs(wx - nx) < SNAP)
1077 else if(abs((wx + ww) - (nx + c->w + 2 * c->bw)) < SNAP)
1078 nx = wx + ww - c->w - 2 * c->bw;
1079 if(abs(wy - ny) < SNAP)
1081 else if(abs((wy + wh) - (ny + c->h + 2 * c->bw)) < SNAP)
1082 ny = wy + wh - c->h - 2 * c->bw;
1083 if(!c->isfloating && !lt->isfloating && (abs(nx - c->x) > SNAP || abs(ny - c->y) > SNAP))
1084 togglefloating(NULL);
1085 if(lt->isfloating || c->isfloating) {
1088 resize(c, nx, ny, c->w, c->h, False);
1096 nexttiled(Client *c) {
1097 for(; c && (c->isfloating || !isvisible(c, NULL)); c = c->next);
1102 propertynotify(XEvent *e) {
1105 XPropertyEvent *ev = &e->xproperty;
1107 if(ev->state == PropertyDelete)
1108 return; /* ignore */
1109 if((c = getclient(ev->window))) {
1112 case XA_WM_TRANSIENT_FOR:
1113 XGetTransientForHint(dpy, c->win, &trans);
1114 if(!c->isfloating && (c->isfloating = (getclient(trans) != NULL)))
1117 case XA_WM_NORMAL_HINTS:
1125 if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
1134 quit(const char *arg) {
1135 readin = running = False;
1139 resize(Client *c, int x, int y, int w, int h, Bool sizehints) {
1143 /* set minimum possible */
1147 /* temporarily remove base dimensions */
1151 /* adjust for aspect limits */
1152 if(c->minax != c->maxax && c->minay != c->maxay
1153 && c->minax > 0 && c->maxax > 0 && c->minay > 0 && c->maxay > 0) {
1154 if(w * c->maxay > h * c->maxax)
1155 w = h * c->maxax / c->maxay;
1156 else if(w * c->minay < h * c->minax)
1157 h = w * c->minay / c->minax;
1160 /* adjust for increment value */
1166 /* restore base dimensions */
1170 w = MAX(w, c->minw);
1171 h = MAX(h, c->minh);
1174 w = MIN(w, c->maxw);
1177 h = MIN(h, c->maxh);
1179 if(w <= 0 || h <= 0)
1182 x = sw - w - 2 * c->bw;
1184 y = sh - h - 2 * c->bw;
1185 if(x + w + 2 * c->bw < sx)
1187 if(y + h + 2 * c->bw < sy)
1189 if(c->x != x || c->y != y || c->w != w || c->h != h) {
1192 c->w = wc.width = w;
1193 c->h = wc.height = h;
1194 wc.border_width = c->bw;
1195 XConfigureWindow(dpy, c->win,
1196 CWX|CWY|CWWidth|CWHeight|CWBorderWidth, &wc);
1203 resizemouse(Client *c) {
1210 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1211 None, cursor[CurResize], CurrentTime) != GrabSuccess)
1213 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->bw - 1, c->h + c->bw - 1);
1215 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask , &ev);
1218 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0,
1219 c->w + c->bw - 1, c->h + c->bw - 1);
1220 XUngrabPointer(dpy, CurrentTime);
1221 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1223 case ConfigureRequest:
1226 handler[ev.type](&ev);
1230 nw = MAX(ev.xmotion.x - ocx - 2 * c->bw + 1, 1);
1231 nh = MAX(ev.xmotion.y - ocy - 2 * c->bw + 1, 1);
1232 if(!c->isfloating && !lt->isfloating && (abs(nw - c->w) > SNAP || abs(nh - c->h) > SNAP)) {
1235 togglefloating(NULL);
1237 if((lt->isfloating) || c->isfloating) {
1238 resize(c, c->x, c->y, nw, nh, True);
1256 if(sel->isfloating || lt->isfloating)
1257 XRaiseWindow(dpy, sel->win);
1258 if(!lt->isfloating) {
1259 wc.stack_mode = Below;
1260 wc.sibling = barwin;
1261 for(c = stack; c; c = c->snext)
1262 if(!c->isfloating && isvisible(c, NULL)) {
1263 XConfigureWindow(dpy, c->win, CWSibling|CWStackMode, &wc);
1264 wc.sibling = c->win;
1268 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1274 char sbuf[sizeof stext];
1277 unsigned int len, offset;
1280 /* main event loop, also reads status text from stdin */
1282 xfd = ConnectionNumber(dpy);
1285 len = sizeof stext - 1;
1286 sbuf[len] = stext[len] = '\0'; /* 0-terminator is never touched */
1290 FD_SET(STDIN_FILENO, &rd);
1292 if(select(xfd + 1, &rd, NULL, NULL, NULL) == -1) {
1295 eprint("select failed\n");
1297 if(FD_ISSET(STDIN_FILENO, &rd)) {
1298 switch((r = read(STDIN_FILENO, sbuf + offset, len - offset))) {
1300 strncpy(stext, strerror(errno), len);
1304 strncpy(stext, "EOF", 4);
1308 for(p = sbuf + offset; r > 0; p++, r--, offset++)
1309 if(*p == '\n' || *p == '\0') {
1311 strncpy(stext, sbuf, len);
1312 p += r - 1; /* p is sbuf + offset + r - 1 */
1313 for(r = 0; *(p - r) && *(p - r) != '\n'; r++);
1316 memmove(sbuf, p - r + 1, r);
1323 while(XPending(dpy)) {
1324 XNextEvent(dpy, &ev);
1325 if(handler[ev.type])
1326 (handler[ev.type])(&ev); /* call handler */
1333 unsigned int i, num;
1334 Window *wins, d1, d2;
1335 XWindowAttributes wa;
1338 if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1339 for(i = 0; i < num; i++) {
1340 if(!XGetWindowAttributes(dpy, wins[i], &wa)
1341 || wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1343 if(wa.map_state == IsViewable || getstate(wins[i]) == IconicState)
1344 manage(wins[i], &wa);
1346 for(i = 0; i < num; i++) { /* now the transients */
1347 if(!XGetWindowAttributes(dpy, wins[i], &wa))
1349 if(XGetTransientForHint(dpy, wins[i], &d1)
1350 && (wa.map_state == IsViewable || getstate(wins[i]) == IconicState))
1351 manage(wins[i], &wa);
1359 setclientstate(Client *c, long state) {
1360 long data[] = {state, None};
1362 XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1363 PropModeReplace, (unsigned char *)data, 2);
1367 setmfact(const char *arg) {
1375 d = strtod(arg, NULL);
1376 if(arg[0] == '-' || arg[0] == '+')
1378 if(d < 0.1 || d > 0.9)
1389 XSetWindowAttributes wa;
1392 screen = DefaultScreen(dpy);
1393 root = RootWindow(dpy, screen);
1397 sw = DisplayWidth(dpy, screen);
1398 sh = DisplayHeight(dpy, screen);
1399 bh = dc.font.height + 2;
1404 wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1405 wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1406 wmatom[WMName] = XInternAtom(dpy, "WM_NAME", False);
1407 wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1408 netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1409 netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1412 wa.cursor = cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1413 cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1414 cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1416 /* init appearance */
1417 dc.norm[ColBorder] = getcolor(NORMBORDERCOLOR);
1418 dc.norm[ColBG] = getcolor(NORMBGCOLOR);
1419 dc.norm[ColFG] = getcolor(NORMFGCOLOR);
1420 dc.sel[ColBorder] = getcolor(SELBORDERCOLOR);
1421 dc.sel[ColBG] = getcolor(SELBGCOLOR);
1422 dc.sel[ColFG] = getcolor(SELFGCOLOR);
1425 dc.drawable = XCreatePixmap(dpy, root, DisplayWidth(dpy, screen), bh, DefaultDepth(dpy, screen));
1426 dc.gc = XCreateGC(dpy, root, 0, 0);
1427 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
1429 XSetFont(dpy, dc.gc, dc.font.xfont->fid);
1432 tagset[0] = emallocz(TAGSZ);
1433 tagset[1] = emallocz(TAGSZ);
1434 tagset[0][0] = tagset[1][0] = True;
1437 for(blw = i = 0; LENGTH(layouts) > 1 && i < LENGTH(layouts); i++) {
1438 w = textw(layouts[i].symbol);
1442 wa.override_redirect = 1;
1443 wa.background_pixmap = ParentRelative;
1444 wa.event_mask = ButtonPressMask|ExposureMask;
1446 barwin = XCreateWindow(dpy, root, bx, by, bw, bh, 0, DefaultDepth(dpy, screen),
1447 CopyFromParent, DefaultVisual(dpy, screen),
1448 CWOverrideRedirect|CWBackPixmap|CWEventMask, &wa);
1449 XDefineCursor(dpy, barwin, cursor[CurNormal]);
1450 XMapRaised(dpy, barwin);
1451 strcpy(stext, "dwm-"VERSION);
1454 /* EWMH support per view */
1455 XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1456 PropModeReplace, (unsigned char *) netatom, NetLast);
1458 /* select for events */
1459 wa.event_mask = SubstructureRedirectMask|SubstructureNotifyMask
1460 |EnterWindowMask|LeaveWindowMask|StructureNotifyMask;
1461 XChangeWindowAttributes(dpy, root, CWEventMask|CWCursor, &wa);
1462 XSelectInput(dpy, root, wa.event_mask);
1470 spawn(const char *arg) {
1471 static char *shell = NULL;
1473 if(!shell && !(shell = getenv("SHELL")))
1477 /* The double-fork construct avoids zombie processes and keeps the code
1478 * clean from stupid signal handlers. */
1482 close(ConnectionNumber(dpy));
1484 execl(shell, shell, "-c", arg, (char *)NULL);
1485 fprintf(stderr, "dwm: execl '%s -c %s'", shell, arg);
1494 tag(const char *arg) {
1499 for(i = 0; i < LENGTH(tags); i++)
1500 sel->tags[i] = (arg == NULL);
1501 sel->tags[idxoftag(arg)] = True;
1506 textnw(const char *text, unsigned int len) {
1510 XmbTextExtents(dc.font.set, text, len, NULL, &r);
1513 return XTextWidth(dc.font.xfont, text, len);
1517 textw(const char *text) {
1518 return textnw(text, strlen(text)) + dc.font.height;
1524 unsigned int i, n = counttiled();
1538 for(i = 0, c = nexttiled(c->next); c; c = nexttiled(c->next), i++) {
1539 if(i + 1 == n) /* remainder */
1540 tileresize(c, x, ty, (tx + tw) - x - 2 * c->bw, th - 2 * c->bw);
1542 tileresize(c, x, ty, w - 2 * c->bw, th - 2 * c->bw);
1544 x = c->x + c->w + 2 * c->bw;
1549 tilemaster(unsigned int n) {
1550 Client *c = nexttiled(clients);
1553 tileresize(c, wx, wy, ww - 2 * c->bw, wh - 2 * c->bw);
1555 tileresize(c, mx, my, mw - 2 * c->bw, mh - 2 * c->bw);
1560 tileresize(Client *c, int x, int y, int w, int h) {
1561 resize(c, x, y, w, h, RESIZEHINTS);
1562 if((RESIZEHINTS) && ((c->h < bh) || (c->h > h) || (c->w < bh) || (c->w > w)))
1563 /* client doesn't accept size constraints */
1564 resize(c, x, y, w, h, False);
1570 unsigned int i, n = counttiled();
1584 for(i = 0, c = nexttiled(c->next); c; c = nexttiled(c->next), i++) {
1585 if(i + 1 == n) /* remainder */
1586 tileresize(c, tx, y, tw - 2 * c->bw, (ty + th) - y - 2 * c->bw);
1588 tileresize(c, tx, y, tw - 2 * c->bw, h - 2 * c->bw);
1590 y = c->y + c->h + 2 * c->bw;
1595 togglefloating(const char *arg) {
1598 sel->isfloating = !sel->isfloating;
1600 resize(sel, sel->x, sel->y, sel->w, sel->h, True);
1605 togglelayout(const char *arg) {
1609 if(++lt == &layouts[LENGTH(layouts)])
1613 for(i = 0; i < LENGTH(layouts); i++)
1614 if(!strcmp(arg, layouts[i].symbol))
1616 if(i == LENGTH(layouts))
1627 toggletag(const char *arg) {
1633 sel->tags[i] = !sel->tags[i];
1634 for(j = 0; j < LENGTH(tags) && !sel->tags[j]; j++);
1635 if(j == LENGTH(tags))
1636 sel->tags[i] = True; /* at least one tag must be enabled */
1641 toggleview(const char *arg) {
1645 tagset[seltags][i] = !tagset[seltags][i];
1646 for(j = 0; j < LENGTH(tags) && !tagset[seltags][j]; j++);
1647 if(j == LENGTH(tags))
1648 tagset[seltags][i] = True; /* at least one tag must be viewed */
1656 XMoveWindow(dpy, c->win, c->x, c->y);
1657 c->isbanned = False;
1661 unmanage(Client *c) {
1664 wc.border_width = c->oldbw;
1665 /* The server grab construct avoids race conditions. */
1667 XSetErrorHandler(xerrordummy);
1668 XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
1673 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1674 setclientstate(c, WithdrawnState);
1678 XSetErrorHandler(xerror);
1684 unmapnotify(XEvent *e) {
1686 XUnmapEvent *ev = &e->xunmap;
1688 if((c = getclient(ev->window)))
1694 if(dc.drawable != 0)
1695 XFreePixmap(dpy, dc.drawable);
1696 dc.drawable = XCreatePixmap(dpy, root, bw, bh, DefaultDepth(dpy, screen));
1697 XMoveResizeWindow(dpy, barwin, bx, by, bw, bh);
1708 /* window area geometry */
1714 /* master area geometry */
1720 /* tile area geometry */
1728 updatesizehints(Client *c) {
1732 if(!XGetWMNormalHints(dpy, c->win, &size, &msize) || !size.flags)
1734 c->flags = size.flags;
1735 if(c->flags & PBaseSize) {
1736 c->basew = size.base_width;
1737 c->baseh = size.base_height;
1739 else if(c->flags & PMinSize) {
1740 c->basew = size.min_width;
1741 c->baseh = size.min_height;
1744 c->basew = c->baseh = 0;
1745 if(c->flags & PResizeInc) {
1746 c->incw = size.width_inc;
1747 c->inch = size.height_inc;
1750 c->incw = c->inch = 0;
1751 if(c->flags & PMaxSize) {
1752 c->maxw = size.max_width;
1753 c->maxh = size.max_height;
1756 c->maxw = c->maxh = 0;
1757 if(c->flags & PMinSize) {
1758 c->minw = size.min_width;
1759 c->minh = size.min_height;
1761 else if(c->flags & PBaseSize) {
1762 c->minw = size.base_width;
1763 c->minh = size.base_height;
1766 c->minw = c->minh = 0;
1767 if(c->flags & PAspect) {
1768 c->minax = size.min_aspect.x;
1769 c->maxax = size.max_aspect.x;
1770 c->minay = size.min_aspect.y;
1771 c->maxay = size.max_aspect.y;
1774 c->minax = c->maxax = c->minay = c->maxay = 0;
1775 c->isfixed = (c->maxw && c->minw && c->maxh && c->minh
1776 && c->maxw == c->minw && c->maxh == c->minh);
1780 updatetitle(Client *c) {
1781 if(!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
1782 gettextprop(c->win, wmatom[WMName], c->name, sizeof c->name);
1786 updatewmhints(Client *c) {
1789 if((wmh = XGetWMHints(dpy, c->win))) {
1791 sel->isurgent = False;
1793 c->isurgent = (wmh->flags & XUrgencyHint) ? True : False;
1799 view(const char *arg) {
1800 seltags ^= 1; /* toggle sel tagset */
1801 memset(tagset[seltags], (NULL == arg), TAGSZ);
1802 tagset[seltags][idxoftag(arg)] = True;
1807 viewprevtag(const char *arg) {
1808 seltags ^= 1; /* toggle sel tagset */
1812 /* There's no way to check accesses to destroyed windows, thus those cases are
1813 * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
1814 * default error handler, which may call exit. */
1816 xerror(Display *dpy, XErrorEvent *ee) {
1817 if(ee->error_code == BadWindow
1818 || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1819 || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1820 || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1821 || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1822 || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1823 || (ee->request_code == X_GrabButton && ee->error_code == BadAccess)
1824 || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1825 || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1827 fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1828 ee->request_code, ee->error_code);
1829 return xerrorxlib(dpy, ee); /* may call exit */
1833 xerrordummy(Display *dpy, XErrorEvent *ee) {
1837 /* Startup Error handler to check if another window manager
1838 * is already running. */
1840 xerrorstart(Display *dpy, XErrorEvent *ee) {
1846 zoom(const char *arg) {
1849 if(c == nexttiled(clients))
1850 if(!c || !(c = nexttiled(c->next)))
1852 if(!lt->isfloating && !sel->isfloating) {
1861 main(int argc, char *argv[]) {
1862 if(argc == 2 && !strcmp("-v", argv[1]))
1863 eprint("dwm-"VERSION", © 2006-2008 dwm engineers, see LICENSE for details\n");
1865 eprint("usage: dwm [-v]\n");
1867 setlocale(LC_CTYPE, "");
1868 if(!(dpy = XOpenDisplay(0)))
1869 eprint("dwm: cannot open display\n");