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 setlayout(const char *arg);
169 void setmfact(const char *arg);
171 void spawn(const char *arg);
172 void tag(const char *arg);
173 unsigned int textnw(const char *text, unsigned int len);
174 unsigned int textw(const char *text);
176 void tilehstack(unsigned int n);
177 Client *tilemaster(unsigned int n);
178 void tileresize(Client *c, int x, int y, int w, int h);
180 void tilevstack(unsigned int n);
181 void togglefloating(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)
1167 if(w * c->maxay > h * c->maxax)
1168 w = h * c->maxax / c->maxay;
1169 else if(w * c->minay < h * c->minax)
1170 h = w * c->minay / c->minax;
1173 /* adjust for increment value */
1179 /* restore base dimensions */
1183 w = MAX(w, c->minw);
1184 h = MAX(h, c->minh);
1187 w = MIN(w, c->maxw);
1190 h = MIN(h, c->maxh);
1192 if(w <= 0 || h <= 0)
1195 x = sw - w - 2 * c->bw;
1197 y = sh - h - 2 * c->bw;
1198 if(x + w + 2 * c->bw < sx)
1200 if(y + h + 2 * c->bw < sy)
1202 if(c->x != x || c->y != y || c->w != w || c->h != h) {
1205 c->w = wc.width = w;
1206 c->h = wc.height = h;
1207 wc.border_width = c->bw;
1208 XConfigureWindow(dpy, c->win,
1209 CWX|CWY|CWWidth|CWHeight|CWBorderWidth, &wc);
1216 resizemouse(Client *c) {
1223 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1224 None, cursor[CurResize], CurrentTime) != GrabSuccess)
1226 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->bw - 1, c->h + c->bw - 1);
1228 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask , &ev);
1231 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0,
1232 c->w + c->bw - 1, c->h + c->bw - 1);
1233 XUngrabPointer(dpy, CurrentTime);
1234 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1236 case ConfigureRequest:
1239 handler[ev.type](&ev);
1243 nw = MAX(ev.xmotion.x - ocx - 2 * c->bw + 1, 1);
1244 nh = MAX(ev.xmotion.y - ocy - 2 * c->bw + 1, 1);
1245 if(!c->isfloating && !lt->isfloating && (abs(nw - c->w) > SNAP || abs(nh - c->h) > SNAP)) {
1248 togglefloating(NULL);
1250 if((lt->isfloating) || c->isfloating) {
1251 resize(c, c->x, c->y, nw, nh, True);
1269 if(sel->isfloating || lt->isfloating)
1270 XRaiseWindow(dpy, sel->win);
1271 if(!lt->isfloating) {
1272 wc.stack_mode = Below;
1273 wc.sibling = barwin;
1274 for(c = stack; c; c = c->snext)
1275 if(!c->isfloating && isvisible(c, NULL)) {
1276 XConfigureWindow(dpy, c->win, CWSibling|CWStackMode, &wc);
1277 wc.sibling = c->win;
1281 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1287 char sbuf[sizeof stext];
1290 unsigned int len, offset;
1293 /* main event loop, also reads status text from stdin */
1295 xfd = ConnectionNumber(dpy);
1298 len = sizeof stext - 1;
1299 sbuf[len] = stext[len] = '\0'; /* 0-terminator is never touched */
1303 FD_SET(STDIN_FILENO, &rd);
1305 if(select(xfd + 1, &rd, NULL, NULL, NULL) == -1) {
1308 eprint("select failed\n");
1310 if(FD_ISSET(STDIN_FILENO, &rd)) {
1311 switch((r = read(STDIN_FILENO, sbuf + offset, len - offset))) {
1313 strncpy(stext, strerror(errno), len);
1317 strncpy(stext, "EOF", 4);
1321 for(p = sbuf + offset; r > 0; p++, r--, offset++)
1322 if(*p == '\n' || *p == '\0') {
1324 strncpy(stext, sbuf, len);
1325 p += r - 1; /* p is sbuf + offset + r - 1 */
1326 for(r = 0; *(p - r) && *(p - r) != '\n'; r++);
1329 memmove(sbuf, p - r + 1, r);
1336 while(XPending(dpy)) {
1337 XNextEvent(dpy, &ev);
1338 if(handler[ev.type])
1339 (handler[ev.type])(&ev); /* call handler */
1346 unsigned int i, num;
1347 Window *wins, d1, d2;
1348 XWindowAttributes wa;
1351 if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1352 for(i = 0; i < num; i++) {
1353 if(!XGetWindowAttributes(dpy, wins[i], &wa)
1354 || wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1356 if(wa.map_state == IsViewable || getstate(wins[i]) == IconicState)
1357 manage(wins[i], &wa);
1359 for(i = 0; i < num; i++) { /* now the transients */
1360 if(!XGetWindowAttributes(dpy, wins[i], &wa))
1362 if(XGetTransientForHint(dpy, wins[i], &d1)
1363 && (wa.map_state == IsViewable || getstate(wins[i]) == IconicState))
1364 manage(wins[i], &wa);
1372 setclientstate(Client *c, long state) {
1373 long data[] = {state, None};
1375 XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1376 PropModeReplace, (unsigned char *)data, 2);
1380 setlayout(const char *arg) {
1384 if(++lt == &layouts[LENGTH(layouts)])
1388 for(i = 0; i < LENGTH(layouts); i++)
1389 if(!strcmp(arg, layouts[i].symbol))
1391 if(i == LENGTH(layouts))
1402 setmfact(const char *arg) {
1410 d = strtod(arg, NULL);
1411 if(arg[0] == '-' || arg[0] == '+')
1413 if(d < 0.1 || d > 0.9)
1424 XSetWindowAttributes wa;
1427 screen = DefaultScreen(dpy);
1428 root = RootWindow(dpy, screen);
1432 sw = DisplayWidth(dpy, screen);
1433 sh = DisplayHeight(dpy, screen);
1434 bh = dc.font.height + 2;
1436 /* update geometry */
1440 wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1441 wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1442 wmatom[WMName] = XInternAtom(dpy, "WM_NAME", False);
1443 wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1444 netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1445 netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1448 wa.cursor = cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1449 cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1450 cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1452 /* init appearance */
1453 dc.norm[ColBorder] = getcolor(NORMBORDERCOLOR);
1454 dc.norm[ColBG] = getcolor(NORMBGCOLOR);
1455 dc.norm[ColFG] = getcolor(NORMFGCOLOR);
1456 dc.sel[ColBorder] = getcolor(SELBORDERCOLOR);
1457 dc.sel[ColBG] = getcolor(SELBGCOLOR);
1458 dc.sel[ColFG] = getcolor(SELFGCOLOR);
1461 dc.drawable = XCreatePixmap(dpy, root, DisplayWidth(dpy, screen), bh, DefaultDepth(dpy, screen));
1462 dc.gc = XCreateGC(dpy, root, 0, 0);
1463 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
1465 XSetFont(dpy, dc.gc, dc.font.xfont->fid);
1468 tagset[0] = emallocz(TAGSZ);
1469 tagset[1] = emallocz(TAGSZ);
1470 tagset[0][0] = tagset[1][0] = True;
1473 for(blw = i = 0; LENGTH(layouts) > 1 && i < LENGTH(layouts); i++) {
1474 w = textw(layouts[i].symbol);
1478 wa.override_redirect = 1;
1479 wa.background_pixmap = ParentRelative;
1480 wa.event_mask = ButtonPressMask|ExposureMask;
1482 barwin = XCreateWindow(dpy, root, bx, by, bw, bh, 0, DefaultDepth(dpy, screen),
1483 CopyFromParent, DefaultVisual(dpy, screen),
1484 CWOverrideRedirect|CWBackPixmap|CWEventMask, &wa);
1485 XDefineCursor(dpy, barwin, cursor[CurNormal]);
1486 XMapRaised(dpy, barwin);
1487 strcpy(stext, "dwm-"VERSION);
1490 /* EWMH support per view */
1491 XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1492 PropModeReplace, (unsigned char *) netatom, NetLast);
1494 /* select for events */
1495 wa.event_mask = SubstructureRedirectMask|SubstructureNotifyMask
1496 |EnterWindowMask|LeaveWindowMask|StructureNotifyMask;
1497 XChangeWindowAttributes(dpy, root, CWEventMask|CWCursor, &wa);
1498 XSelectInput(dpy, root, wa.event_mask);
1506 spawn(const char *arg) {
1507 static char *shell = NULL;
1509 if(!shell && !(shell = getenv("SHELL")))
1513 /* The double-fork construct avoids zombie processes and keeps the code
1514 * clean from stupid signal handlers. */
1518 close(ConnectionNumber(dpy));
1520 execl(shell, shell, "-c", arg, (char *)NULL);
1521 fprintf(stderr, "dwm: execl '%s -c %s'", shell, arg);
1530 tag(const char *arg) {
1535 for(i = 0; i < LENGTH(tags); i++)
1536 sel->tags[i] = (NULL == arg);
1537 sel->tags[idxoftag(arg)] = True;
1542 textnw(const char *text, unsigned int len) {
1546 XmbTextExtents(dc.font.set, text, len, NULL, &r);
1549 return XTextWidth(dc.font.xfont, text, len);
1553 textw(const char *text) {
1554 return textnw(text, strlen(text)) + dc.font.height;
1560 unsigned int i, n = counttiled();
1574 for(i = 0, c = nexttiled(c->next); c; c = nexttiled(c->next), i++) {
1575 if(i + 1 == n) /* remainder */
1576 tileresize(c, x, ty, (tx + tw) - x - 2 * c->bw, th - 2 * c->bw);
1578 tileresize(c, x, ty, w - 2 * c->bw, th - 2 * c->bw);
1580 x = c->x + c->w + 2 * c->bw;
1585 tilemaster(unsigned int n) {
1586 Client *c = nexttiled(clients);
1589 tileresize(c, wx, wy, ww - 2 * c->bw, wh - 2 * c->bw);
1591 tileresize(c, mx, my, mw - 2 * c->bw, mh - 2 * c->bw);
1596 tileresize(Client *c, int x, int y, int w, int h) {
1597 resize(c, x, y, w, h, RESIZEHINTS);
1598 if((RESIZEHINTS) && ((c->h < bh) || (c->h > h) || (c->w < bh) || (c->w > w)))
1599 /* client doesn't accept size constraints */
1600 resize(c, x, y, w, h, False);
1606 unsigned int i, n = counttiled();
1620 for(i = 0, c = nexttiled(c->next); c; c = nexttiled(c->next), i++) {
1621 if(i + 1 == n) /* remainder */
1622 tileresize(c, tx, y, tw - 2 * c->bw, (ty + th) - y - 2 * c->bw);
1624 tileresize(c, tx, y, tw - 2 * c->bw, h - 2 * c->bw);
1626 y = c->y + c->h + 2 * c->bw;
1631 togglefloating(const char *arg) {
1634 sel->isfloating = !sel->isfloating;
1636 resize(sel, sel->x, sel->y, sel->w, sel->h, True);
1641 toggletag(const char *arg) {
1647 sel->tags[i] = !sel->tags[i];
1648 for(j = 0; j < LENGTH(tags) && !sel->tags[j]; j++);
1649 if(j == LENGTH(tags))
1650 sel->tags[i] = True; /* at least one tag must be enabled */
1655 toggleview(const char *arg) {
1659 tagset[seltags][i] = !tagset[seltags][i];
1660 for(j = 0; j < LENGTH(tags) && !tagset[seltags][j]; j++);
1661 if(j == LENGTH(tags))
1662 tagset[seltags][i] = True; /* at least one tag must be viewed */
1670 XMoveWindow(dpy, c->win, c->x, c->y);
1671 c->isbanned = False;
1675 unmanage(Client *c) {
1678 wc.border_width = c->oldbw;
1679 /* The server grab construct avoids race conditions. */
1681 XSetErrorHandler(xerrordummy);
1682 XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
1687 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1688 setclientstate(c, WithdrawnState);
1692 XSetErrorHandler(xerror);
1698 unmapnotify(XEvent *e) {
1700 XUnmapEvent *ev = &e->xunmap;
1702 if((c = getclient(ev->window)))
1709 if(dc.drawable != 0)
1710 XFreePixmap(dpy, dc.drawable);
1711 dc.drawable = XCreatePixmap(dpy, root, bw, bh, DefaultDepth(dpy, screen));
1712 XMoveResizeWindow(dpy, barwin, bx, by, bw, bh);
1723 /* window area geometry */
1729 /* master area geometry */
1736 /* tile area geometry */
1744 updatesizehints(Client *c) {
1748 if(!XGetWMNormalHints(dpy, c->win, &size, &msize) || !size.flags)
1750 c->flags = size.flags;
1751 if(c->flags & PBaseSize) {
1752 c->basew = size.base_width;
1753 c->baseh = size.base_height;
1755 else if(c->flags & PMinSize) {
1756 c->basew = size.min_width;
1757 c->baseh = size.min_height;
1760 c->basew = c->baseh = 0;
1761 if(c->flags & PResizeInc) {
1762 c->incw = size.width_inc;
1763 c->inch = size.height_inc;
1766 c->incw = c->inch = 0;
1767 if(c->flags & PMaxSize) {
1768 c->maxw = size.max_width;
1769 c->maxh = size.max_height;
1772 c->maxw = c->maxh = 0;
1773 if(c->flags & PMinSize) {
1774 c->minw = size.min_width;
1775 c->minh = size.min_height;
1777 else if(c->flags & PBaseSize) {
1778 c->minw = size.base_width;
1779 c->minh = size.base_height;
1782 c->minw = c->minh = 0;
1783 if(c->flags & PAspect) {
1784 c->minax = size.min_aspect.x;
1785 c->maxax = size.max_aspect.x;
1786 c->minay = size.min_aspect.y;
1787 c->maxay = size.max_aspect.y;
1790 c->minax = c->maxax = c->minay = c->maxay = 0;
1791 c->isfixed = (c->maxw && c->minw && c->maxh && c->minh
1792 && c->maxw == c->minw && c->maxh == c->minh);
1796 updatetitle(Client *c) {
1797 if(!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
1798 gettextprop(c->win, wmatom[WMName], c->name, sizeof c->name);
1802 updatewmhints(Client *c) {
1805 if((wmh = XGetWMHints(dpy, c->win))) {
1807 sel->isurgent = False;
1809 c->isurgent = (wmh->flags & XUrgencyHint) ? True : False;
1815 view(const char *arg) {
1817 memset(tagset[seltags], (NULL == arg), TAGSZ);
1818 tagset[seltags][idxoftag(arg)] = True;
1823 viewprevtag(const char *arg) {
1824 seltags ^= 1; /* toggle sel tagset */
1828 /* There's no way to check accesses to destroyed windows, thus those cases are
1829 * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
1830 * default error handler, which may call exit. */
1832 xerror(Display *dpy, XErrorEvent *ee) {
1833 if(ee->error_code == BadWindow
1834 || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1835 || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1836 || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1837 || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1838 || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1839 || (ee->request_code == X_GrabButton && ee->error_code == BadAccess)
1840 || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1841 || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1843 fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1844 ee->request_code, ee->error_code);
1845 return xerrorxlib(dpy, ee); /* may call exit */
1849 xerrordummy(Display *dpy, XErrorEvent *ee) {
1853 /* Startup Error handler to check if another window manager
1854 * is already running. */
1856 xerrorstart(Display *dpy, XErrorEvent *ee) {
1862 zoom(const char *arg) {
1865 if(c == nexttiled(clients))
1866 if(!c || !(c = nexttiled(c->next)))
1868 if(!lt->isfloating && !sel->isfloating) {
1877 main(int argc, char *argv[]) {
1878 if(argc == 2 && !strcmp("-v", argv[1]))
1879 eprint("dwm-"VERSION", © 2006-2008 dwm engineers, see LICENSE for details\n");
1881 eprint("usage: dwm [-v]\n");
1883 setlocale(LC_CTYPE, "");
1884 if(!(dpy = XOpenDisplay(0)))
1885 eprint("dwm: cannot open display\n");