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 reapply(const char *arg);
162 void resize(Client *c, int x, int y, int w, int h, Bool sizehints);
163 void resizemouse(Client *c);
167 void setclientstate(Client *c, long state);
168 void setmfact(const char *arg);
170 void spawn(const char *arg);
171 void tag(const char *arg);
172 unsigned int textnw(const char *text, unsigned int len);
173 unsigned int textw(const char *text);
175 void tilehstack(unsigned int n);
176 Client *tilemaster(unsigned int n);
177 void tileresize(Client *c, int x, int y, int w, int h);
179 void tilevstack(unsigned int n);
180 void togglefloating(const char *arg);
181 void togglelayout(const char *arg);
182 void toggletag(const char *arg);
183 void toggleview(const char *arg);
184 void unban(Client *c);
185 void unmanage(Client *c);
186 void unmapnotify(XEvent *e);
187 void updatebar(void);
188 void updategeom(void);
189 void updatesizehints(Client *c);
190 void updatetitle(Client *c);
191 void updatewmhints(Client *c);
192 void view(const char *arg);
193 void viewprevtag(const char *arg); /* views previous selected tags */
194 int xerror(Display *dpy, XErrorEvent *ee);
195 int xerrordummy(Display *dpy, XErrorEvent *ee);
196 int xerrorstart(Display *dpy, XErrorEvent *ee);
197 void zoom(const char *arg);
201 int screen, sx, sy, sw, sh;
202 int (*xerrorxlib)(Display *, XErrorEvent *);
203 int bx, by, bw, bh, blw, mx, my, mw, mh, tx, ty, tw, th, wx, wy, ww, wh;
206 unsigned int numlockmask = 0;
207 void (*handler[LASTEvent]) (XEvent *) = {
208 [ButtonPress] = buttonpress,
209 [ConfigureRequest] = configurerequest,
210 [ConfigureNotify] = configurenotify,
211 [DestroyNotify] = destroynotify,
212 [EnterNotify] = enternotify,
215 [KeyPress] = keypress,
216 [MappingNotify] = mappingnotify,
217 [MapRequest] = maprequest,
218 [PropertyNotify] = propertynotify,
219 [UnmapNotify] = unmapnotify
221 Atom wmatom[WMLast], netatom[NetLast];
222 Bool otherwm, readin;
225 Client *clients = NULL;
227 Client *stack = NULL;
228 Cursor cursor[CurLast];
232 Layout *lt = layouts;
235 /* configuration, allows nested code to access above variables */
237 #define TAGSZ (LENGTH(tags) * sizeof(Bool))
239 /* function implementations */
242 applyrules(Client *c) {
244 Bool matched = False;
246 XClassHint ch = { 0 };
249 XGetClassHint(dpy, c->win, &ch);
250 for(i = 0; i < LENGTH(rules); i++) {
252 if((!r->title || strstr(c->name, r->title))
253 && (!r->class || (ch.res_class && strstr(ch.res_class, r->class)))
254 && (!r->instance || (ch.res_name && strstr(ch.res_name, r->instance)))) {
255 c->isfloating = r->isfloating;
257 c->tags[idxoftag(r->tag)] = True;
267 memcpy(c->tags, tagset[seltags], TAGSZ);
274 for(c = clients; c; c = c->next)
275 if(isvisible(c, NULL)) {
277 if(lt->isfloating || c->isfloating)
278 resize(c, c->fx, c->fy, c->fw, c->fh, True);
298 attachstack(Client *c) {
307 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
312 buttonpress(XEvent *e) {
315 XButtonPressedEvent *ev = &e->xbutton;
317 if(ev->window == barwin) {
319 for(i = 0; i < LENGTH(tags); i++) {
322 if(ev->button == Button1) {
323 if(ev->state & MODKEY)
328 else if(ev->button == Button3) {
329 if(ev->state & MODKEY)
337 if((ev->x < x + blw) && ev->button == Button1)
340 else if((c = getclient(ev->window))) {
342 if(CLEANMASK(ev->state) != MODKEY)
344 if(ev->button == Button1) {
348 else if(ev->button == Button2) {
349 if(!lt->isfloating && c->isfloating)
350 togglefloating(NULL);
354 else if(ev->button == Button3 && !c->isfixed) {
364 XSetErrorHandler(xerrorstart);
366 /* this causes an error if some other window manager is running */
367 XSelectInput(dpy, DefaultRootWindow(dpy), SubstructureRedirectMask);
370 eprint("dwm: another window manager is already running\n");
372 XSetErrorHandler(NULL);
373 xerrorxlib = XSetErrorHandler(xerror);
385 XFreeFontSet(dpy, dc.font.set);
387 XFreeFont(dpy, dc.font.xfont);
388 XUngrabKey(dpy, AnyKey, AnyModifier, root);
389 XFreePixmap(dpy, dc.drawable);
391 XFreeCursor(dpy, cursor[CurNormal]);
392 XFreeCursor(dpy, cursor[CurResize]);
393 XFreeCursor(dpy, cursor[CurMove]);
394 XDestroyWindow(dpy, barwin);
396 XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime);
400 configure(Client *c) {
403 ce.type = ConfigureNotify;
411 ce.border_width = c->bw;
413 ce.override_redirect = False;
414 XSendEvent(dpy, c->win, False, StructureNotifyMask, (XEvent *)&ce);
418 configurenotify(XEvent *e) {
419 XConfigureEvent *ev = &e->xconfigure;
421 if(ev->window == root && (ev->width != sw || ev->height != sh)) {
431 configurerequest(XEvent *e) {
433 XConfigureRequestEvent *ev = &e->xconfigurerequest;
436 if((c = getclient(ev->window))) {
437 if(ev->value_mask & CWBorderWidth)
438 c->bw = ev->border_width;
439 if(c->isfixed || c->isfloating || lt->isfloating) {
440 if(ev->value_mask & CWX)
442 if(ev->value_mask & CWY)
444 if(ev->value_mask & CWWidth)
446 if(ev->value_mask & CWHeight)
448 if((c->x - sx + c->w) > sw && c->isfloating)
449 c->x = sx + (sw / 2 - c->w / 2); /* center in x direction */
450 if((c->y - sy + c->h) > sh && c->isfloating)
451 c->y = sy + (sh / 2 - c->h / 2); /* center in y direction */
452 if((ev->value_mask & (CWX|CWY))
453 && !(ev->value_mask & (CWWidth|CWHeight)))
455 if(isvisible(c, NULL))
456 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h);
464 wc.width = ev->width;
465 wc.height = ev->height;
466 wc.border_width = ev->border_width;
467 wc.sibling = ev->above;
468 wc.stack_mode = ev->detail;
469 XConfigureWindow(dpy, ev->window, ev->value_mask, &wc);
479 for(n = 0, c = nexttiled(clients); c; c = nexttiled(c->next), n++);
484 destroynotify(XEvent *e) {
486 XDestroyWindowEvent *ev = &e->xdestroywindow;
488 if((c = getclient(ev->window)))
495 c->prev->next = c->next;
497 c->next->prev = c->prev;
500 c->next = c->prev = NULL;
504 detachstack(Client *c) {
507 for(tc = &stack; *tc && *tc != c; tc = &(*tc)->snext);
517 for(c = stack; c && !isvisible(c, NULL); c = c->snext);
518 for(i = 0; i < LENGTH(tags); i++) {
519 dc.w = textw(tags[i]);
520 if(tagset[seltags][i]) {
521 drawtext(tags[i], dc.sel, isurgent(i));
522 drawsquare(c && c->tags[i], isoccupied(i), isurgent(i), dc.sel);
525 drawtext(tags[i], dc.norm, isurgent(i));
526 drawsquare(c && c->tags[i], isoccupied(i), isurgent(i), dc.norm);
532 drawtext(lt->symbol, dc.norm, False);
543 drawtext(stext, dc.norm, False);
544 if((dc.w = dc.x - x) > bh) {
547 drawtext(c->name, dc.sel, False);
548 drawsquare(False, c->isfloating, False, dc.sel);
551 drawtext(NULL, dc.norm, False);
553 XCopyArea(dpy, dc.drawable, barwin, dc.gc, 0, 0, bw, bh, 0, 0);
558 drawsquare(Bool filled, Bool empty, Bool invert, unsigned long col[ColLast]) {
561 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
563 gcv.foreground = col[invert ? ColBG : ColFG];
564 XChangeGC(dpy, dc.gc, GCForeground, &gcv);
565 x = (dc.font.ascent + dc.font.descent + 2) / 4;
569 r.width = r.height = x + 1;
570 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
573 r.width = r.height = x;
574 XDrawRectangles(dpy, dc.drawable, dc.gc, &r, 1);
579 drawtext(const char *text, unsigned long col[ColLast], Bool invert) {
581 unsigned int len, olen;
582 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
585 XSetForeground(dpy, dc.gc, col[invert ? ColFG : ColBG]);
586 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
590 len = MIN(olen, sizeof buf);
591 memcpy(buf, text, len);
593 h = dc.font.ascent + dc.font.descent;
594 y = dc.y + (dc.h / 2) - (h / 2) + dc.font.ascent;
596 /* shorten text if necessary */
597 for(; len && (w = textnw(buf, len)) > dc.w - h; len--);
608 XSetForeground(dpy, dc.gc, col[invert ? ColBG : ColFG]);
610 XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
612 XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
616 emallocz(unsigned int size) {
617 void *res = calloc(1, size);
620 eprint("fatal: could not malloc() %u bytes\n", size);
625 enternotify(XEvent *e) {
627 XCrossingEvent *ev = &e->xcrossing;
629 if((ev->mode != NotifyNormal || ev->detail == NotifyInferior) && ev->window != root)
631 if((c = getclient(ev->window)))
638 eprint(const char *errstr, ...) {
641 va_start(ap, errstr);
642 vfprintf(stderr, errstr, ap);
649 XExposeEvent *ev = &e->xexpose;
651 if(ev->count == 0 && (ev->window == barwin))
657 if(!c || (c && !isvisible(c, NULL)))
658 for(c = stack; c && !isvisible(c, NULL); c = c->snext);
659 if(sel && sel != c) {
660 grabbuttons(sel, False);
661 XSetWindowBorder(dpy, sel->win, dc.norm[ColBorder]);
666 grabbuttons(c, True);
670 XSetWindowBorder(dpy, c->win, dc.sel[ColBorder]);
671 XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
674 XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
679 focusin(XEvent *e) { /* there are some broken focus acquiring clients */
680 XFocusChangeEvent *ev = &e->xfocus;
682 if(sel && ev->window != sel->win)
683 XSetInputFocus(dpy, sel->win, RevertToPointerRoot, CurrentTime);
687 focusnext(const char *arg) {
692 for(c = sel->next; c && !isvisible(c, arg ? sel->tags : NULL); c = c->next);
694 for(c = clients; c && !isvisible(c, arg ? sel->tags : NULL); c = c->next);
702 focusprev(const char *arg) {
707 for(c = sel->prev; c && !isvisible(c, arg ? sel->tags : NULL); c = c->prev);
709 for(c = clients; c && c->next; c = c->next);
710 for(; c && !isvisible(c, arg ? sel->tags : NULL); c = c->prev);
719 getclient(Window w) {
722 for(c = clients; c && c->win != w; c = c->next);
727 getcolor(const char *colstr) {
728 Colormap cmap = DefaultColormap(dpy, screen);
731 if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
732 eprint("error, cannot allocate color '%s'\n", colstr);
740 unsigned char *p = NULL;
741 unsigned long n, extra;
744 status = XGetWindowProperty(dpy, w, wmatom[WMState], 0L, 2L, False, wmatom[WMState],
745 &real, &format, &n, &extra, (unsigned char **)&p);
746 if(status != Success)
755 gettextprop(Window w, Atom atom, char *text, unsigned int size) {
760 if(!text || size == 0)
763 XGetTextProperty(dpy, w, &name, atom);
766 if(name.encoding == XA_STRING)
767 strncpy(text, (char *)name.value, size - 1);
769 if(XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success
771 strncpy(text, *list, size - 1);
772 XFreeStringList(list);
775 text[size - 1] = '\0';
781 grabbuttons(Client *c, Bool focused) {
783 unsigned int buttons[] = { Button1, Button2, Button3 };
784 unsigned int modifiers[] = { MODKEY, MODKEY|LockMask, MODKEY|numlockmask,
785 MODKEY|numlockmask|LockMask} ;
787 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
789 for(i = 0; i < LENGTH(buttons); i++)
790 for(j = 0; j < LENGTH(modifiers); j++)
791 XGrabButton(dpy, buttons[i], modifiers[j], c->win, False,
792 BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
794 XGrabButton(dpy, AnyButton, AnyModifier, c->win, False,
795 BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
802 XModifierKeymap *modmap;
804 /* init modifier map */
805 modmap = XGetModifierMapping(dpy);
806 for(i = 0; i < 8; i++)
807 for(j = 0; j < modmap->max_keypermod; j++) {
808 if(modmap->modifiermap[i * modmap->max_keypermod + j] == XKeysymToKeycode(dpy, XK_Num_Lock))
809 numlockmask = (1 << i);
811 XFreeModifiermap(modmap);
813 XUngrabKey(dpy, AnyKey, AnyModifier, root);
814 for(i = 0; i < LENGTH(keys); i++) {
815 code = XKeysymToKeycode(dpy, keys[i].keysym);
816 XGrabKey(dpy, code, keys[i].mod, root, True,
817 GrabModeAsync, GrabModeAsync);
818 XGrabKey(dpy, code, keys[i].mod|LockMask, root, True,
819 GrabModeAsync, GrabModeAsync);
820 XGrabKey(dpy, code, keys[i].mod|numlockmask, root, True,
821 GrabModeAsync, GrabModeAsync);
822 XGrabKey(dpy, code, keys[i].mod|numlockmask|LockMask, root, True,
823 GrabModeAsync, GrabModeAsync);
828 idxoftag(const char *t) {
831 for(i = 0; (i < LENGTH(tags)) && t && strcmp(tags[i], t); i++);
832 return (i < LENGTH(tags)) ? i : 0;
836 initfont(const char *fontstr) {
837 char *def, **missing;
842 XFreeFontSet(dpy, dc.font.set);
843 dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
846 fprintf(stderr, "dwm: missing fontset: %s\n", missing[n]);
847 XFreeStringList(missing);
850 XFontSetExtents *font_extents;
851 XFontStruct **xfonts;
853 dc.font.ascent = dc.font.descent = 0;
854 font_extents = XExtentsOfFontSet(dc.font.set);
855 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
856 for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
857 dc.font.ascent = MAX(dc.font.ascent, (*xfonts)->ascent);
858 dc.font.descent = MAX(dc.font.descent,(*xfonts)->descent);
864 XFreeFont(dpy, dc.font.xfont);
865 dc.font.xfont = NULL;
866 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr))
867 && !(dc.font.xfont = XLoadQueryFont(dpy, "fixed")))
868 eprint("error, cannot load font: '%s'\n", fontstr);
869 dc.font.ascent = dc.font.xfont->ascent;
870 dc.font.descent = dc.font.xfont->descent;
872 dc.font.height = dc.font.ascent + dc.font.descent;
876 isoccupied(unsigned int t) {
879 for(c = clients; c; c = c->next)
886 isprotodel(Client *c) {
891 if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
892 for(i = 0; !ret && i < n; i++)
893 if(protocols[i] == wmatom[WMDelete])
901 isurgent(unsigned int t) {
904 for(c = clients; c; c = c->next)
905 if(c->isurgent && c->tags[t])
911 isvisible(Client *c, Bool *cmp) {
915 cmp = tagset[seltags];
916 for(i = 0; i < LENGTH(tags); i++)
917 if(c->tags[i] && cmp[i])
923 keypress(XEvent *e) {
929 keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
930 for(i = 0; i < LENGTH(keys); i++)
931 if(keysym == keys[i].keysym
932 && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state))
935 keys[i].func(keys[i].arg);
940 killclient(const char *arg) {
945 if(isprotodel(sel)) {
946 ev.type = ClientMessage;
947 ev.xclient.window = sel->win;
948 ev.xclient.message_type = wmatom[WMProtocols];
949 ev.xclient.format = 32;
950 ev.xclient.data.l[0] = wmatom[WMDelete];
951 ev.xclient.data.l[1] = CurrentTime;
952 XSendEvent(dpy, sel->win, False, NoEventMask, &ev);
955 XKillClient(dpy, sel->win);
959 manage(Window w, XWindowAttributes *wa) {
960 Client *c, *t = NULL;
965 c = emallocz(sizeof(Client));
966 c->tags = emallocz(TAGSZ);
972 c->w = c->fw = wa->width;
973 c->h = c->fh = wa->height;
974 c->oldbw = wa->border_width;
975 if(c->w == sw && c->h == sh) {
978 c->bw = wa->border_width;
981 if(c->x + c->w + 2 * c->bw > wx + ww)
982 c->x = wx + ww - c->w - 2 * c->bw;
983 if(c->y + c->h + 2 * c->bw > wy + wh)
984 c->y = wy + wh - c->h - 2 * c->bw;
985 c->x = MAX(c->x, wx);
986 c->y = MAX(c->y, wy);
992 wc.border_width = c->bw;
993 XConfigureWindow(dpy, w, CWBorderWidth, &wc);
994 XSetWindowBorder(dpy, w, dc.norm[ColBorder]);
995 configure(c); /* propagates border_width, if size doesn't change */
997 XSelectInput(dpy, w, EnterWindowMask|FocusChangeMask|PropertyChangeMask|StructureNotifyMask);
998 grabbuttons(c, False);
1000 if((rettrans = XGetTransientForHint(dpy, w, &trans) == Success))
1001 for(t = clients; t && t->win != trans; t = t->next);
1003 memcpy(c->tags, t->tags, TAGSZ);
1007 c->isfloating = (rettrans == Success) || c->isfixed;
1010 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h); /* some windows require this */
1012 XMapWindow(dpy, c->win);
1013 setclientstate(c, NormalState);
1018 mappingnotify(XEvent *e) {
1019 XMappingEvent *ev = &e->xmapping;
1021 XRefreshKeyboardMapping(ev);
1022 if(ev->request == MappingKeyboard)
1027 maprequest(XEvent *e) {
1028 static XWindowAttributes wa;
1029 XMapRequestEvent *ev = &e->xmaprequest;
1031 if(!XGetWindowAttributes(dpy, ev->window, &wa))
1033 if(wa.override_redirect)
1035 if(!getclient(ev->window))
1036 manage(ev->window, &wa);
1043 for(c = clients; c; c = c->next)
1044 if((lt->isfloating || !c->isfloating) && isvisible(c, NULL))
1045 resize(c, wx, wy, ww - 2 * c->bw, wh - 2 * c->bw, RESIZEHINTS);
1049 movemouse(Client *c) {
1050 int x1, y1, ocx, ocy, di, nx, ny;
1057 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1058 None, cursor[CurMove], CurrentTime) != GrabSuccess)
1060 XQueryPointer(dpy, root, &dummy, &dummy, &x1, &y1, &di, &di, &dui);
1062 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
1065 XUngrabPointer(dpy, CurrentTime);
1067 case ConfigureRequest:
1070 handler[ev.type](&ev);
1074 nx = ocx + (ev.xmotion.x - x1);
1075 ny = ocy + (ev.xmotion.y - y1);
1076 if(abs(wx - nx) < SNAP)
1078 else if(abs((wx + ww) - (nx + c->w + 2 * c->bw)) < SNAP)
1079 nx = wx + ww - c->w - 2 * c->bw;
1080 if(abs(wy - ny) < SNAP)
1082 else if(abs((wy + wh) - (ny + c->h + 2 * c->bw)) < SNAP)
1083 ny = wy + wh - c->h - 2 * c->bw;
1084 if(!c->isfloating && !lt->isfloating && (abs(nx - c->x) > SNAP || abs(ny - c->y) > SNAP))
1085 togglefloating(NULL);
1086 if(lt->isfloating || c->isfloating) {
1089 resize(c, nx, ny, c->w, c->h, False);
1097 nexttiled(Client *c) {
1098 for(; c && (c->isfloating || !isvisible(c, NULL)); c = c->next);
1103 propertynotify(XEvent *e) {
1106 XPropertyEvent *ev = &e->xproperty;
1108 if(ev->state == PropertyDelete)
1109 return; /* ignore */
1110 if((c = getclient(ev->window))) {
1113 case XA_WM_TRANSIENT_FOR:
1114 XGetTransientForHint(dpy, c->win, &trans);
1115 if(!c->isfloating && (c->isfloating = (getclient(trans) != NULL)))
1118 case XA_WM_NORMAL_HINTS:
1126 if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
1135 quit(const char *arg) {
1136 readin = running = False;
1140 reapply(const char *arg) {
1143 for(c = clients; c; c = c->next) {
1144 memset(c->tags, 0, TAGSZ);
1151 resize(Client *c, int x, int y, int w, int h, Bool sizehints) {
1155 /* set minimum possible */
1159 /* temporarily remove base dimensions */
1163 /* adjust for aspect limits */
1164 if(c->minax != c->maxax && c->minay != c->maxay
1165 && c->minax > 0 && c->maxax > 0 && c->minay > 0 && c->maxay > 0) {
1166 if(w * c->maxay > h * c->maxax)
1167 w = h * c->maxax / c->maxay;
1168 else if(w * c->minay < h * c->minax)
1169 h = w * c->minay / c->minax;
1172 /* adjust for increment value */
1178 /* restore base dimensions */
1182 w = MAX(w, c->minw);
1183 h = MAX(h, c->minh);
1186 w = MIN(w, c->maxw);
1189 h = MIN(h, c->maxh);
1191 if(w <= 0 || h <= 0)
1194 x = sw - w - 2 * c->bw;
1196 y = sh - h - 2 * c->bw;
1197 if(x + w + 2 * c->bw < sx)
1199 if(y + h + 2 * c->bw < sy)
1201 if(c->x != x || c->y != y || c->w != w || c->h != h) {
1204 c->w = wc.width = w;
1205 c->h = wc.height = h;
1206 wc.border_width = c->bw;
1207 XConfigureWindow(dpy, c->win,
1208 CWX|CWY|CWWidth|CWHeight|CWBorderWidth, &wc);
1215 resizemouse(Client *c) {
1222 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1223 None, cursor[CurResize], CurrentTime) != GrabSuccess)
1225 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->bw - 1, c->h + c->bw - 1);
1227 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask , &ev);
1230 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0,
1231 c->w + c->bw - 1, c->h + c->bw - 1);
1232 XUngrabPointer(dpy, CurrentTime);
1233 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1235 case ConfigureRequest:
1238 handler[ev.type](&ev);
1242 nw = MAX(ev.xmotion.x - ocx - 2 * c->bw + 1, 1);
1243 nh = MAX(ev.xmotion.y - ocy - 2 * c->bw + 1, 1);
1244 if(!c->isfloating && !lt->isfloating && (abs(nw - c->w) > SNAP || abs(nh - c->h) > SNAP)) {
1247 togglefloating(NULL);
1249 if((lt->isfloating) || c->isfloating) {
1250 resize(c, c->x, c->y, nw, nh, True);
1268 if(sel->isfloating || lt->isfloating)
1269 XRaiseWindow(dpy, sel->win);
1270 if(!lt->isfloating) {
1271 wc.stack_mode = Below;
1272 wc.sibling = barwin;
1273 for(c = stack; c; c = c->snext)
1274 if(!c->isfloating && isvisible(c, NULL)) {
1275 XConfigureWindow(dpy, c->win, CWSibling|CWStackMode, &wc);
1276 wc.sibling = c->win;
1280 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1286 char sbuf[sizeof stext];
1289 unsigned int len, offset;
1292 /* main event loop, also reads status text from stdin */
1294 xfd = ConnectionNumber(dpy);
1297 len = sizeof stext - 1;
1298 sbuf[len] = stext[len] = '\0'; /* 0-terminator is never touched */
1302 FD_SET(STDIN_FILENO, &rd);
1304 if(select(xfd + 1, &rd, NULL, NULL, NULL) == -1) {
1307 eprint("select failed\n");
1309 if(FD_ISSET(STDIN_FILENO, &rd)) {
1310 switch((r = read(STDIN_FILENO, sbuf + offset, len - offset))) {
1312 strncpy(stext, strerror(errno), len);
1316 strncpy(stext, "EOF", 4);
1320 for(p = sbuf + offset; r > 0; p++, r--, offset++)
1321 if(*p == '\n' || *p == '\0') {
1323 strncpy(stext, sbuf, len);
1324 p += r - 1; /* p is sbuf + offset + r - 1 */
1325 for(r = 0; *(p - r) && *(p - r) != '\n'; r++);
1328 memmove(sbuf, p - r + 1, r);
1335 while(XPending(dpy)) {
1336 XNextEvent(dpy, &ev);
1337 if(handler[ev.type])
1338 (handler[ev.type])(&ev); /* call handler */
1345 unsigned int i, num;
1346 Window *wins, d1, d2;
1347 XWindowAttributes wa;
1350 if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1351 for(i = 0; i < num; i++) {
1352 if(!XGetWindowAttributes(dpy, wins[i], &wa)
1353 || wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1355 if(wa.map_state == IsViewable || getstate(wins[i]) == IconicState)
1356 manage(wins[i], &wa);
1358 for(i = 0; i < num; i++) { /* now the transients */
1359 if(!XGetWindowAttributes(dpy, wins[i], &wa))
1361 if(XGetTransientForHint(dpy, wins[i], &d1)
1362 && (wa.map_state == IsViewable || getstate(wins[i]) == IconicState))
1363 manage(wins[i], &wa);
1371 setclientstate(Client *c, long state) {
1372 long data[] = {state, None};
1374 XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1375 PropModeReplace, (unsigned char *)data, 2);
1379 setmfact(const char *arg) {
1387 d = strtod(arg, NULL);
1388 if(arg[0] == '-' || arg[0] == '+')
1390 if(d < 0.1 || d > 0.9)
1401 XSetWindowAttributes wa;
1404 screen = DefaultScreen(dpy);
1405 root = RootWindow(dpy, screen);
1409 sw = DisplayWidth(dpy, screen);
1410 sh = DisplayHeight(dpy, screen);
1411 bh = dc.font.height + 2;
1416 wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1417 wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1418 wmatom[WMName] = XInternAtom(dpy, "WM_NAME", False);
1419 wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1420 netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1421 netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1424 wa.cursor = cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1425 cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1426 cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1428 /* init appearance */
1429 dc.norm[ColBorder] = getcolor(NORMBORDERCOLOR);
1430 dc.norm[ColBG] = getcolor(NORMBGCOLOR);
1431 dc.norm[ColFG] = getcolor(NORMFGCOLOR);
1432 dc.sel[ColBorder] = getcolor(SELBORDERCOLOR);
1433 dc.sel[ColBG] = getcolor(SELBGCOLOR);
1434 dc.sel[ColFG] = getcolor(SELFGCOLOR);
1437 dc.drawable = XCreatePixmap(dpy, root, DisplayWidth(dpy, screen), bh, DefaultDepth(dpy, screen));
1438 dc.gc = XCreateGC(dpy, root, 0, 0);
1439 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
1441 XSetFont(dpy, dc.gc, dc.font.xfont->fid);
1444 tagset[0] = emallocz(TAGSZ);
1445 tagset[1] = emallocz(TAGSZ);
1446 tagset[0][0] = tagset[1][0] = True;
1449 for(blw = i = 0; LENGTH(layouts) > 1 && i < LENGTH(layouts); i++) {
1450 w = textw(layouts[i].symbol);
1454 wa.override_redirect = 1;
1455 wa.background_pixmap = ParentRelative;
1456 wa.event_mask = ButtonPressMask|ExposureMask;
1458 barwin = XCreateWindow(dpy, root, bx, by, bw, bh, 0, DefaultDepth(dpy, screen),
1459 CopyFromParent, DefaultVisual(dpy, screen),
1460 CWOverrideRedirect|CWBackPixmap|CWEventMask, &wa);
1461 XDefineCursor(dpy, barwin, cursor[CurNormal]);
1462 XMapRaised(dpy, barwin);
1463 strcpy(stext, "dwm-"VERSION);
1466 /* EWMH support per view */
1467 XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1468 PropModeReplace, (unsigned char *) netatom, NetLast);
1470 /* select for events */
1471 wa.event_mask = SubstructureRedirectMask|SubstructureNotifyMask
1472 |EnterWindowMask|LeaveWindowMask|StructureNotifyMask;
1473 XChangeWindowAttributes(dpy, root, CWEventMask|CWCursor, &wa);
1474 XSelectInput(dpy, root, wa.event_mask);
1482 spawn(const char *arg) {
1483 static char *shell = NULL;
1485 if(!shell && !(shell = getenv("SHELL")))
1489 /* The double-fork construct avoids zombie processes and keeps the code
1490 * clean from stupid signal handlers. */
1494 close(ConnectionNumber(dpy));
1496 execl(shell, shell, "-c", arg, (char *)NULL);
1497 fprintf(stderr, "dwm: execl '%s -c %s'", shell, arg);
1506 tag(const char *arg) {
1511 for(i = 0; i < LENGTH(tags); i++)
1512 sel->tags[i] = (arg == NULL);
1513 sel->tags[idxoftag(arg)] = True;
1518 textnw(const char *text, unsigned int len) {
1522 XmbTextExtents(dc.font.set, text, len, NULL, &r);
1525 return XTextWidth(dc.font.xfont, text, len);
1529 textw(const char *text) {
1530 return textnw(text, strlen(text)) + dc.font.height;
1536 unsigned int i, n = counttiled();
1550 for(i = 0, c = nexttiled(c->next); c; c = nexttiled(c->next), i++) {
1551 if(i + 1 == n) /* remainder */
1552 tileresize(c, x, ty, (tx + tw) - x - 2 * c->bw, th - 2 * c->bw);
1554 tileresize(c, x, ty, w - 2 * c->bw, th - 2 * c->bw);
1556 x = c->x + c->w + 2 * c->bw;
1561 tilemaster(unsigned int n) {
1562 Client *c = nexttiled(clients);
1565 tileresize(c, wx, wy, ww - 2 * c->bw, wh - 2 * c->bw);
1567 tileresize(c, mx, my, mw - 2 * c->bw, mh - 2 * c->bw);
1572 tileresize(Client *c, int x, int y, int w, int h) {
1573 resize(c, x, y, w, h, RESIZEHINTS);
1574 if((RESIZEHINTS) && ((c->h < bh) || (c->h > h) || (c->w < bh) || (c->w > w)))
1575 /* client doesn't accept size constraints */
1576 resize(c, x, y, w, h, False);
1582 unsigned int i, n = counttiled();
1596 for(i = 0, c = nexttiled(c->next); c; c = nexttiled(c->next), i++) {
1597 if(i + 1 == n) /* remainder */
1598 tileresize(c, tx, y, tw - 2 * c->bw, (ty + th) - y - 2 * c->bw);
1600 tileresize(c, tx, y, tw - 2 * c->bw, h - 2 * c->bw);
1602 y = c->y + c->h + 2 * c->bw;
1607 togglefloating(const char *arg) {
1610 sel->isfloating = !sel->isfloating;
1612 resize(sel, sel->x, sel->y, sel->w, sel->h, True);
1617 togglelayout(const char *arg) {
1621 if(++lt == &layouts[LENGTH(layouts)])
1625 for(i = 0; i < LENGTH(layouts); i++)
1626 if(!strcmp(arg, layouts[i].symbol))
1628 if(i == LENGTH(layouts))
1639 toggletag(const char *arg) {
1645 sel->tags[i] = !sel->tags[i];
1646 for(j = 0; j < LENGTH(tags) && !sel->tags[j]; j++);
1647 if(j == LENGTH(tags))
1648 sel->tags[i] = True; /* at least one tag must be enabled */
1653 toggleview(const char *arg) {
1657 tagset[seltags][i] = !tagset[seltags][i];
1658 for(j = 0; j < LENGTH(tags) && !tagset[seltags][j]; j++);
1659 if(j == LENGTH(tags))
1660 tagset[seltags][i] = True; /* at least one tag must be viewed */
1668 XMoveWindow(dpy, c->win, c->x, c->y);
1669 c->isbanned = False;
1673 unmanage(Client *c) {
1676 wc.border_width = c->oldbw;
1677 /* The server grab construct avoids race conditions. */
1679 XSetErrorHandler(xerrordummy);
1680 XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
1685 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1686 setclientstate(c, WithdrawnState);
1690 XSetErrorHandler(xerror);
1696 unmapnotify(XEvent *e) {
1698 XUnmapEvent *ev = &e->xunmap;
1700 if((c = getclient(ev->window)))
1706 if(dc.drawable != 0)
1707 XFreePixmap(dpy, dc.drawable);
1708 dc.drawable = XCreatePixmap(dpy, root, bw, bh, DefaultDepth(dpy, screen));
1709 XMoveResizeWindow(dpy, barwin, bx, by, bw, bh);
1720 /* window area geometry */
1726 /* master area geometry */
1732 /* tile area geometry */
1740 updatesizehints(Client *c) {
1744 if(!XGetWMNormalHints(dpy, c->win, &size, &msize) || !size.flags)
1746 c->flags = size.flags;
1747 if(c->flags & PBaseSize) {
1748 c->basew = size.base_width;
1749 c->baseh = size.base_height;
1751 else if(c->flags & PMinSize) {
1752 c->basew = size.min_width;
1753 c->baseh = size.min_height;
1756 c->basew = c->baseh = 0;
1757 if(c->flags & PResizeInc) {
1758 c->incw = size.width_inc;
1759 c->inch = size.height_inc;
1762 c->incw = c->inch = 0;
1763 if(c->flags & PMaxSize) {
1764 c->maxw = size.max_width;
1765 c->maxh = size.max_height;
1768 c->maxw = c->maxh = 0;
1769 if(c->flags & PMinSize) {
1770 c->minw = size.min_width;
1771 c->minh = size.min_height;
1773 else if(c->flags & PBaseSize) {
1774 c->minw = size.base_width;
1775 c->minh = size.base_height;
1778 c->minw = c->minh = 0;
1779 if(c->flags & PAspect) {
1780 c->minax = size.min_aspect.x;
1781 c->maxax = size.max_aspect.x;
1782 c->minay = size.min_aspect.y;
1783 c->maxay = size.max_aspect.y;
1786 c->minax = c->maxax = c->minay = c->maxay = 0;
1787 c->isfixed = (c->maxw && c->minw && c->maxh && c->minh
1788 && c->maxw == c->minw && c->maxh == c->minh);
1792 updatetitle(Client *c) {
1793 if(!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
1794 gettextprop(c->win, wmatom[WMName], c->name, sizeof c->name);
1798 updatewmhints(Client *c) {
1801 if((wmh = XGetWMHints(dpy, c->win))) {
1803 sel->isurgent = False;
1805 c->isurgent = (wmh->flags & XUrgencyHint) ? True : False;
1811 view(const char *arg) {
1812 seltags ^= 1; /* toggle sel tagset */
1813 memset(tagset[seltags], (NULL == arg), TAGSZ);
1814 tagset[seltags][idxoftag(arg)] = True;
1819 viewprevtag(const char *arg) {
1820 seltags ^= 1; /* toggle sel tagset */
1824 /* There's no way to check accesses to destroyed windows, thus those cases are
1825 * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
1826 * default error handler, which may call exit. */
1828 xerror(Display *dpy, XErrorEvent *ee) {
1829 if(ee->error_code == BadWindow
1830 || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1831 || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1832 || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1833 || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1834 || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1835 || (ee->request_code == X_GrabButton && ee->error_code == BadAccess)
1836 || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1837 || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1839 fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1840 ee->request_code, ee->error_code);
1841 return xerrorxlib(dpy, ee); /* may call exit */
1845 xerrordummy(Display *dpy, XErrorEvent *ee) {
1849 /* Startup Error handler to check if another window manager
1850 * is already running. */
1852 xerrorstart(Display *dpy, XErrorEvent *ee) {
1858 zoom(const char *arg) {
1861 if(c == nexttiled(clients))
1862 if(!c || !(c = nexttiled(c->next)))
1864 if(!lt->isfloating && !sel->isfloating) {
1873 main(int argc, char *argv[]) {
1874 if(argc == 2 && !strcmp("-v", argv[1]))
1875 eprint("dwm-"VERSION", © 2006-2008 dwm engineers, see LICENSE for details\n");
1877 eprint("usage: dwm [-v]\n");
1879 setlocale(LC_CTYPE, "");
1880 if(!(dpy = XOpenDisplay(0)))
1881 eprint("dwm: cannot open display\n");