1 /* See LICENSE file for copyright and license details.
3 * dynamic window manager is designed like any other X client as well. It is
4 * driven through handling X events. In contrast to other X clients, a window
5 * manager selects for SubstructureRedirectMask on the root window, to receive
6 * events about window (dis-)appearance. Only one X connection at a time is
7 * allowed to select for this event mask.
9 * Calls to fetch an X event from the event queue are blocking. Due reading
10 * status text from standard input, a select()-driven main loop has been
11 * implemented which selects for reads on the X connection and STDIN_FILENO to
12 * handle all data smoothly. The event handlers of dwm are organized in an
13 * array which is accessed whenever a new event has been fetched. This allows
14 * event dispatching in O(1) time.
16 * Each child of the root window is called a client, except windows which have
17 * set the override_redirect flag. Clients are organized in a global
18 * doubly-linked client list, the focus history is remembered through a global
19 * stack list. Each client contains an array of Bools of the same size as the
20 * global tags array to indicate the tags of a client.
22 * Keys and tagging rules are organized as arrays and defined in config.h.
24 * To understand everything else, start reading main().
33 #include <sys/select.h>
34 #include <sys/types.h>
36 #include <X11/cursorfont.h>
37 #include <X11/keysym.h>
38 #include <X11/Xatom.h>
40 #include <X11/Xproto.h>
41 #include <X11/Xutil.h>
44 #define BUTTONMASK (ButtonPressMask|ButtonReleaseMask)
45 #define CLEANMASK(mask) (mask & ~(numlockmask|LockMask))
46 #define LENGTH(x) (sizeof x / sizeof x[0])
48 #define MOUSEMASK (BUTTONMASK|PointerMotionMask)
51 enum { CurNormal, CurResize, CurMove, CurLast }; /* cursor */
52 enum { ColBorder, ColFG, ColBG, ColLast }; /* color */
53 enum { NetSupported, NetWMName, NetLast }; /* EWMH atoms */
54 enum { WMProtocols, WMDelete, WMName, WMState, WMLast };/* default atoms */
57 typedef struct Client Client;
61 int basew, baseh, incw, inch, maxw, maxh, minw, minh;
62 int minax, maxax, minay, maxay;
64 unsigned int border, oldborder;
65 Bool isbanned, isfixed, isfloating, isurgent;
75 unsigned long norm[ColLast];
76 unsigned long sel[ColLast];
86 } DC; /* draw context */
91 void (*func)(const char *arg);
97 void (*arrange)(void);
103 const char *instance;
109 /* function declarations */
110 void applygeom(const char *arg);
111 void applyrules(Client *c);
113 void attach(Client *c);
114 void attachstack(Client *c);
116 void buttonpress(XEvent *e);
117 void checkotherwm(void);
119 void configure(Client *c);
120 void configurenotify(XEvent *e);
121 void configurerequest(XEvent *e);
122 unsigned int counttiled(void);
123 void destroynotify(XEvent *e);
124 void detach(Client *c);
125 void detachstack(Client *c);
127 void drawsquare(Bool filled, Bool empty, Bool invert, unsigned long col[ColLast]);
128 void drawtext(const char *text, unsigned long col[ColLast], Bool invert);
129 void *emallocz(unsigned int size);
130 void enternotify(XEvent *e);
131 void eprint(const char *errstr, ...);
132 void expose(XEvent *e);
133 void floating(void); /* default floating layout */
134 void focus(Client *c);
135 void focusin(XEvent *e);
136 void focusnext(const char *arg);
137 void focusprev(const char *arg);
138 Client *getclient(Window w);
139 unsigned long getcolor(const char *colstr);
140 double getdouble(const char *s);
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);
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 setgeom(const char *arg);
169 void setlayout(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 updatebarpos(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);
199 char stext[256], buf[256];
200 int screen, sx, sy, sw, sh;
201 int (*xerrorxlib)(Display *, XErrorEvent *);
202 int bx, by, bw, bh, blw, mx, my, mw, mh, mox, moy, mow, moh, tx, ty, tw, th, wx, wy, ww, wh;
203 unsigned int numlockmask = 0;
204 void (*handler[LASTEvent]) (XEvent *) = {
205 [ButtonPress] = buttonpress,
206 [ConfigureRequest] = configurerequest,
207 [ConfigureNotify] = configurenotify,
208 [DestroyNotify] = destroynotify,
209 [EnterNotify] = enternotify,
212 [KeyPress] = keypress,
213 [MappingNotify] = mappingnotify,
214 [MapRequest] = maprequest,
215 [PropertyNotify] = propertynotify,
216 [UnmapNotify] = unmapnotify
218 Atom wmatom[WMLast], netatom[NetLast];
219 Bool otherwm, readin;
223 Client *clients = NULL;
225 Client *stack = NULL;
226 Cursor cursor[CurLast];
232 /* configuration, allows nested code to access above variables */
234 #define TAGSZ (LENGTH(tags) * sizeof(Bool))
235 static Bool tmp[LENGTH(tags)];
237 /* function implementations */
240 applygeometry(const char *arg) {
241 static const char *lastArg = NULL;
242 char delim, op, *s, *e, *p;
244 int i, *map[] = { &bx, &by, &bw, &bh,
248 &mox, &moy, &mow, &moh };
256 strncpy(buf, arg, sizeof buf);
257 for(i = 0, e = s = buf; i < LENGTH(map) && e; e++)
258 if(*e == ' ' || *e == 0) {
262 /* check if there is an operator */
263 for(p = s; p < e && *p != '-' && *p != '+' && *p != '*'; p++);
269 if(op && p > s) { /* intermediate operand, e.g. H-B */
270 *(map[i]) = (int)val;
275 default: *(map[i]) = (int)val; break;
276 case '-': *(map[i]) -= (int)val; break;
277 case '+': *(map[i]) += (int)val; break;
278 case '*': *(map[i]) = (int)(((double)*(map[i])) * val); break;
289 applyrules(Client *c) {
291 Bool matched = False;
293 XClassHint ch = { 0 };
296 XGetClassHint(dpy, c->win, &ch);
297 for(i = 0; i < LENGTH(rules); i++) {
299 if(strstr(c->name, r->title)
300 || (ch.res_class && r->class && strstr(ch.res_class, r->class))
301 || (ch.res_name && r->instance && strstr(ch.res_name, r->instance)))
303 c->isfloating = r->isfloating;
305 c->tags[idxoftag(r->tag)] = True;
315 memcpy(c->tags, seltags, TAGSZ);
322 for(c = clients; c; c = c->next)
342 attachstack(Client *c) {
351 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
356 buttonpress(XEvent *e) {
359 XButtonPressedEvent *ev = &e->xbutton;
361 if(ev->window == barwin) {
363 for(i = 0; i < LENGTH(tags); i++) {
366 if(ev->button == Button1) {
367 if(ev->state & MODKEY)
372 else if(ev->button == Button3) {
373 if(ev->state & MODKEY)
382 else if((c = getclient(ev->window))) {
384 if(CLEANMASK(ev->state) != MODKEY)
386 if(ev->button == Button1) {
390 else if(ev->button == Button2) {
391 if((floating != lt->arrange) && c->isfloating)
392 togglefloating(NULL);
396 else if(ev->button == Button3 && !c->isfixed) {
406 XSetErrorHandler(xerrorstart);
408 /* this causes an error if some other window manager is running */
409 XSelectInput(dpy, DefaultRootWindow(dpy), SubstructureRedirectMask);
412 eprint("dwm: another window manager is already running\n");
414 XSetErrorHandler(NULL);
415 xerrorxlib = XSetErrorHandler(xerror);
427 XFreeFontSet(dpy, dc.font.set);
429 XFreeFont(dpy, dc.font.xfont);
430 XUngrabKey(dpy, AnyKey, AnyModifier, root);
431 XFreePixmap(dpy, dc.drawable);
433 XFreeCursor(dpy, cursor[CurNormal]);
434 XFreeCursor(dpy, cursor[CurResize]);
435 XFreeCursor(dpy, cursor[CurMove]);
436 XDestroyWindow(dpy, barwin);
438 XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime);
442 configure(Client *c) {
445 ce.type = ConfigureNotify;
453 ce.border_width = c->border;
455 ce.override_redirect = False;
456 XSendEvent(dpy, c->win, False, StructureNotifyMask, (XEvent *)&ce);
460 configurenotify(XEvent *e) {
461 XConfigureEvent *ev = &e->xconfigure;
463 if(ev->window == root && (ev->width != sw || ev->height != sh))
468 configurerequest(XEvent *e) {
470 XConfigureRequestEvent *ev = &e->xconfigurerequest;
473 if((c = getclient(ev->window))) {
474 if(ev->value_mask & CWBorderWidth)
475 c->border = ev->border_width;
476 if(c->isfixed || c->isfloating || lt->isfloating) {
477 if(ev->value_mask & CWX)
479 if(ev->value_mask & CWY)
481 if(ev->value_mask & CWWidth)
483 if(ev->value_mask & CWHeight)
485 if((c->x - sx + c->w) > sw && c->isfloating)
486 c->x = sx + (sw / 2 - c->w / 2); /* center in x direction */
487 if((c->y - sy + c->h) > sh && c->isfloating)
488 c->y = sy + (sh / 2 - c->h / 2); /* center in y direction */
489 if((ev->value_mask & (CWX|CWY))
490 && !(ev->value_mask & (CWWidth|CWHeight)))
493 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h);
501 wc.width = ev->width;
502 wc.height = ev->height;
503 wc.border_width = ev->border_width;
504 wc.sibling = ev->above;
505 wc.stack_mode = ev->detail;
506 XConfigureWindow(dpy, ev->window, ev->value_mask, &wc);
516 for(n = 0, c = nexttiled(clients); c; c = nexttiled(c->next), n++);
521 destroynotify(XEvent *e) {
523 XDestroyWindowEvent *ev = &e->xdestroywindow;
525 if((c = getclient(ev->window)))
532 c->prev->next = c->next;
534 c->next->prev = c->prev;
537 c->next = c->prev = NULL;
541 detachstack(Client *c) {
544 for(tc=&stack; *tc && *tc != c; tc=&(*tc)->snext);
554 for(c = stack; c && !isvisible(c); c = c->snext);
555 for(i = 0; i < LENGTH(tags); i++) {
556 dc.w = textw(tags[i]);
558 drawtext(tags[i], dc.sel, isurgent(i));
559 drawsquare(c && c->tags[i], isoccupied(i), isurgent(i), dc.sel);
562 drawtext(tags[i], dc.norm, isurgent(i));
563 drawsquare(c && c->tags[i], isoccupied(i), isurgent(i), dc.norm);
568 drawtext(lt->symbol, dc.norm, False);
576 drawtext(stext, dc.norm, False);
577 if((dc.w = dc.x - x) > bh) {
580 drawtext(c->name, dc.sel, False);
581 drawsquare(False, c->isfloating, False, dc.sel);
584 drawtext(NULL, dc.norm, False);
586 XCopyArea(dpy, dc.drawable, barwin, dc.gc, 0, 0, bw, bh, 0, 0);
591 drawsquare(Bool filled, Bool empty, Bool invert, unsigned long col[ColLast]) {
594 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
596 gcv.foreground = col[invert ? ColBG : ColFG];
597 XChangeGC(dpy, dc.gc, GCForeground, &gcv);
598 x = (dc.font.ascent + dc.font.descent + 2) / 4;
602 r.width = r.height = x + 1;
603 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
606 r.width = r.height = x;
607 XDrawRectangles(dpy, dc.drawable, dc.gc, &r, 1);
612 drawtext(const char *text, unsigned long col[ColLast], Bool invert) {
614 unsigned int len, olen;
615 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
617 XSetForeground(dpy, dc.gc, col[invert ? ColFG : ColBG]);
618 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
622 olen = len = strlen(text);
623 if(len >= sizeof buf)
624 len = sizeof buf - 1;
625 memcpy(buf, text, len);
627 h = dc.font.ascent + dc.font.descent;
628 y = dc.y + (dc.h / 2) - (h / 2) + dc.font.ascent;
630 /* shorten text if necessary */
631 while(len && (w = textnw(buf, len)) > dc.w - h)
642 return; /* too long */
643 XSetForeground(dpy, dc.gc, col[invert ? ColBG : ColFG]);
645 XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
647 XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
651 emallocz(unsigned int size) {
652 void *res = calloc(1, size);
655 eprint("fatal: could not malloc() %u bytes\n", size);
660 enternotify(XEvent *e) {
662 XCrossingEvent *ev = &e->xcrossing;
664 if((ev->mode != NotifyNormal || ev->detail == NotifyInferior) && ev->window != root)
666 if((c = getclient(ev->window)))
673 eprint(const char *errstr, ...) {
676 va_start(ap, errstr);
677 vfprintf(stderr, errstr, ap);
684 XExposeEvent *ev = &e->xexpose;
686 if(ev->count == 0 && (ev->window == barwin))
691 floating(void) { /* default floating layout */
694 for(c = clients; c; c = c->next)
696 resize(c, c->x, c->y, c->w, c->h, True);
701 if(!c || (c && !isvisible(c)))
702 for(c = stack; c && !isvisible(c); c = c->snext);
703 if(sel && sel != c) {
704 grabbuttons(sel, False);
705 XSetWindowBorder(dpy, sel->win, dc.norm[ColBorder]);
710 grabbuttons(c, True);
714 XSetWindowBorder(dpy, c->win, dc.sel[ColBorder]);
715 XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
718 XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
723 focusin(XEvent *e) { /* there are some broken focus acquiring clients */
724 XFocusChangeEvent *ev = &e->xfocus;
726 if(sel && ev->window != sel->win)
727 XSetInputFocus(dpy, sel->win, RevertToPointerRoot, CurrentTime);
731 focusnext(const char *arg) {
736 for(c = sel->next; c && !isvisible(c); c = c->next);
738 for(c = clients; c && !isvisible(c); c = c->next);
746 focusprev(const char *arg) {
751 for(c = sel->prev; c && !isvisible(c); c = c->prev);
753 for(c = clients; c && c->next; c = c->next);
754 for(; c && !isvisible(c); c = c->prev);
763 getclient(Window w) {
766 for(c = clients; c && c->win != w; c = c->next);
771 getcolor(const char *colstr) {
772 Colormap cmap = DefaultColormap(dpy, screen);
775 if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
776 eprint("error, cannot allocate color '%s'\n", colstr);
784 unsigned char *p = NULL;
785 unsigned long n, extra;
788 status = XGetWindowProperty(dpy, w, wmatom[WMState], 0L, 2L, False, wmatom[WMState],
789 &real, &format, &n, &extra, (unsigned char **)&p);
790 if(status != Success)
799 gettextprop(Window w, Atom atom, char *text, unsigned int size) {
804 if(!text || size == 0)
807 XGetTextProperty(dpy, w, &name, atom);
810 if(name.encoding == XA_STRING)
811 strncpy(text, (char *)name.value, size - 1);
813 if(XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success
815 strncpy(text, *list, size - 1);
816 XFreeStringList(list);
819 text[size - 1] = '\0';
825 grabbuttons(Client *c, Bool focused) {
826 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
829 XGrabButton(dpy, Button1, MODKEY, c->win, False, BUTTONMASK,
830 GrabModeAsync, GrabModeSync, None, None);
831 XGrabButton(dpy, Button1, MODKEY|LockMask, c->win, False, BUTTONMASK,
832 GrabModeAsync, GrabModeSync, None, None);
833 XGrabButton(dpy, Button1, MODKEY|numlockmask, c->win, False, BUTTONMASK,
834 GrabModeAsync, GrabModeSync, None, None);
835 XGrabButton(dpy, Button1, MODKEY|numlockmask|LockMask, c->win, False, BUTTONMASK,
836 GrabModeAsync, GrabModeSync, None, None);
838 XGrabButton(dpy, Button2, MODKEY, c->win, False, BUTTONMASK,
839 GrabModeAsync, GrabModeSync, None, None);
840 XGrabButton(dpy, Button2, MODKEY|LockMask, c->win, False, BUTTONMASK,
841 GrabModeAsync, GrabModeSync, None, None);
842 XGrabButton(dpy, Button2, MODKEY|numlockmask, c->win, False, BUTTONMASK,
843 GrabModeAsync, GrabModeSync, None, None);
844 XGrabButton(dpy, Button2, MODKEY|numlockmask|LockMask, c->win, False, BUTTONMASK,
845 GrabModeAsync, GrabModeSync, None, None);
847 XGrabButton(dpy, Button3, MODKEY, c->win, False, BUTTONMASK,
848 GrabModeAsync, GrabModeSync, None, None);
849 XGrabButton(dpy, Button3, MODKEY|LockMask, c->win, False, BUTTONMASK,
850 GrabModeAsync, GrabModeSync, None, None);
851 XGrabButton(dpy, Button3, MODKEY|numlockmask, c->win, False, BUTTONMASK,
852 GrabModeAsync, GrabModeSync, None, None);
853 XGrabButton(dpy, Button3, MODKEY|numlockmask|LockMask, c->win, False, BUTTONMASK,
854 GrabModeAsync, GrabModeSync, None, None);
857 XGrabButton(dpy, AnyButton, AnyModifier, c->win, False, BUTTONMASK,
858 GrabModeAsync, GrabModeSync, None, None);
865 XModifierKeymap *modmap;
867 /* init modifier map */
868 modmap = XGetModifierMapping(dpy);
869 for(i = 0; i < 8; i++)
870 for(j = 0; j < modmap->max_keypermod; j++) {
871 if(modmap->modifiermap[i * modmap->max_keypermod + j] == XKeysymToKeycode(dpy, XK_Num_Lock))
872 numlockmask = (1 << i);
874 XFreeModifiermap(modmap);
876 XUngrabKey(dpy, AnyKey, AnyModifier, root);
877 for(i = 0; i < LENGTH(keys); i++) {
878 code = XKeysymToKeycode(dpy, keys[i].keysym);
879 XGrabKey(dpy, code, keys[i].mod, root, True,
880 GrabModeAsync, GrabModeAsync);
881 XGrabKey(dpy, code, keys[i].mod|LockMask, root, True,
882 GrabModeAsync, GrabModeAsync);
883 XGrabKey(dpy, code, keys[i].mod|numlockmask, root, True,
884 GrabModeAsync, GrabModeAsync);
885 XGrabKey(dpy, code, keys[i].mod|numlockmask|LockMask, root, True,
886 GrabModeAsync, GrabModeAsync);
891 idxoftag(const char *t) {
894 for(i = 0; (i < LENGTH(tags)) && (tags[i] != t); i++);
895 return (i < LENGTH(tags)) ? i : 0;
899 initfont(const char *fontstr) {
900 char *def, **missing;
905 XFreeFontSet(dpy, dc.font.set);
906 dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
909 fprintf(stderr, "dwm: missing fontset: %s\n", missing[n]);
910 XFreeStringList(missing);
913 XFontSetExtents *font_extents;
914 XFontStruct **xfonts;
916 dc.font.ascent = dc.font.descent = 0;
917 font_extents = XExtentsOfFontSet(dc.font.set);
918 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
919 for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
920 if(dc.font.ascent < (*xfonts)->ascent)
921 dc.font.ascent = (*xfonts)->ascent;
922 if(dc.font.descent < (*xfonts)->descent)
923 dc.font.descent = (*xfonts)->descent;
929 XFreeFont(dpy, dc.font.xfont);
930 dc.font.xfont = NULL;
931 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr))
932 && !(dc.font.xfont = XLoadQueryFont(dpy, "fixed")))
933 eprint("error, cannot load font: '%s'\n", fontstr);
934 dc.font.ascent = dc.font.xfont->ascent;
935 dc.font.descent = dc.font.xfont->descent;
937 dc.font.height = dc.font.ascent + dc.font.descent;
941 isoccupied(unsigned int t) {
944 for(c = clients; c; c = c->next)
951 isprotodel(Client *c) {
956 if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
957 for(i = 0; !ret && i < n; i++)
958 if(protocols[i] == wmatom[WMDelete])
966 isurgent(unsigned int t) {
969 for(c = clients; c; c = c->next)
970 if(c->isurgent && c->tags[t])
976 isvisible(Client *c) {
979 for(i = 0; i < LENGTH(tags); i++)
980 if(c->tags[i] && seltags[i])
986 keypress(XEvent *e) {
992 keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
993 for(i = 0; i < LENGTH(keys); i++)
994 if(keysym == keys[i].keysym
995 && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state))
998 keys[i].func(keys[i].arg);
1003 killclient(const char *arg) {
1008 if(isprotodel(sel)) {
1009 ev.type = ClientMessage;
1010 ev.xclient.window = sel->win;
1011 ev.xclient.message_type = wmatom[WMProtocols];
1012 ev.xclient.format = 32;
1013 ev.xclient.data.l[0] = wmatom[WMDelete];
1014 ev.xclient.data.l[1] = CurrentTime;
1015 XSendEvent(dpy, sel->win, False, NoEventMask, &ev);
1018 XKillClient(dpy, sel->win);
1022 manage(Window w, XWindowAttributes *wa) {
1023 Client *c, *t = NULL;
1028 c = emallocz(sizeof(Client));
1029 c->tags = emallocz(TAGSZ);
1037 c->oldborder = wa->border_width;
1038 if(c->w == sw && c->h == sh) {
1041 c->border = wa->border_width;
1044 if(c->x + c->w + 2 * c->border > wx + ww)
1045 c->x = wx + ww - c->w - 2 * c->border;
1046 if(c->y + c->h + 2 * c->border > wy + wh)
1047 c->y = wy + wh - c->h - 2 * c->border;
1052 c->border = BORDERPX;
1055 wc.border_width = c->border;
1056 XConfigureWindow(dpy, w, CWBorderWidth, &wc);
1057 XSetWindowBorder(dpy, w, dc.norm[ColBorder]);
1058 configure(c); /* propagates border_width, if size doesn't change */
1060 XSelectInput(dpy, w, EnterWindowMask|FocusChangeMask|PropertyChangeMask|StructureNotifyMask);
1061 grabbuttons(c, False);
1063 if((rettrans = XGetTransientForHint(dpy, w, &trans) == Success))
1064 for(t = clients; t && t->win != trans; t = t->next);
1066 memcpy(c->tags, t->tags, TAGSZ);
1070 c->isfloating = (rettrans == Success) || c->isfixed;
1073 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h); /* some windows require this */
1075 XMapWindow(dpy, c->win);
1076 setclientstate(c, NormalState);
1081 mappingnotify(XEvent *e) {
1082 XMappingEvent *ev = &e->xmapping;
1084 XRefreshKeyboardMapping(ev);
1085 if(ev->request == MappingKeyboard)
1090 maprequest(XEvent *e) {
1091 static XWindowAttributes wa;
1092 XMapRequestEvent *ev = &e->xmaprequest;
1094 if(!XGetWindowAttributes(dpy, ev->window, &wa))
1096 if(wa.override_redirect)
1098 if(!getclient(ev->window))
1099 manage(ev->window, &wa);
1106 for(c = clients; c; c = c->next)
1108 resize(c, mox, moy, mow, moh, RESIZEHINTS);
1112 movemouse(Client *c) {
1113 int x1, y1, ocx, ocy, di, nx, ny;
1120 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1121 None, cursor[CurMove], CurrentTime) != GrabSuccess)
1123 XQueryPointer(dpy, root, &dummy, &dummy, &x1, &y1, &di, &di, &dui);
1125 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
1128 XUngrabPointer(dpy, CurrentTime);
1130 case ConfigureRequest:
1133 handler[ev.type](&ev);
1137 nx = ocx + (ev.xmotion.x - x1);
1138 ny = ocy + (ev.xmotion.y - y1);
1139 if(abs(wx - nx) < SNAP)
1141 else if(abs((wx + ww) - (nx + c->w + 2 * c->border)) < SNAP)
1142 nx = wx + ww - c->w - 2 * c->border;
1143 if(abs(wy - ny) < SNAP)
1145 else if(abs((wy + wh) - (ny + c->h + 2 * c->border)) < SNAP)
1146 ny = wy + wh - c->h - 2 * c->border;
1147 if(!c->isfloating && !lt->isfloating && (abs(nx - c->x) > SNAP || abs(ny - c->y) > SNAP))
1148 togglefloating(NULL);
1149 if((lt->isfloating) || c->isfloating)
1150 resize(c, nx, ny, c->w, c->h, False);
1157 nexttiled(Client *c) {
1158 for(; c && (c->isfloating || !isvisible(c)); c = c->next);
1163 propertynotify(XEvent *e) {
1166 XPropertyEvent *ev = &e->xproperty;
1168 if(ev->state == PropertyDelete)
1169 return; /* ignore */
1170 if((c = getclient(ev->window))) {
1173 case XA_WM_TRANSIENT_FOR:
1174 XGetTransientForHint(dpy, c->win, &trans);
1175 if(!c->isfloating && (c->isfloating = (getclient(trans) != NULL)))
1178 case XA_WM_NORMAL_HINTS:
1186 if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
1195 quit(const char *arg) {
1196 readin = running = False;
1200 reapply(const char *arg) {
1201 static Bool zerotags[LENGTH(tags)] = { 0 };
1204 for(c = clients; c; c = c->next) {
1205 memcpy(c->tags, zerotags, sizeof zerotags);
1212 resize(Client *c, int x, int y, int w, int h, Bool sizehints) {
1216 /* set minimum possible */
1222 /* temporarily remove base dimensions */
1226 /* adjust for aspect limits */
1227 if (c->minay > 0 && c->maxay > 0 && c->minax > 0 && c->maxax > 0) {
1228 if (w * c->maxay > h * c->maxax)
1229 w = h * c->maxax / c->maxay;
1230 else if (w * c->minay < h * c->minax)
1231 h = w * c->minay / c->minax;
1234 /* adjust for increment value */
1240 /* restore base dimensions */
1244 if(c->minw > 0 && w < c->minw)
1246 if(c->minh > 0 && h < c->minh)
1248 if(c->maxw > 0 && w > c->maxw)
1250 if(c->maxh > 0 && h > c->maxh)
1253 if(w <= 0 || h <= 0)
1256 x = sw - w - 2 * c->border;
1258 y = sh - h - 2 * c->border;
1259 if(x + w + 2 * c->border < sx)
1261 if(y + h + 2 * c->border < sy)
1263 if(c->x != x || c->y != y || c->w != w || c->h != h) {
1266 c->w = wc.width = w;
1267 c->h = wc.height = h;
1268 wc.border_width = c->border;
1269 XConfigureWindow(dpy, c->win,
1270 CWX|CWY|CWWidth|CWHeight|CWBorderWidth, &wc);
1277 resizemouse(Client *c) {
1284 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1285 None, cursor[CurResize], CurrentTime) != GrabSuccess)
1287 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->border - 1, c->h + c->border - 1);
1289 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask , &ev);
1292 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0,
1293 c->w + c->border - 1, c->h + c->border - 1);
1294 XUngrabPointer(dpy, CurrentTime);
1295 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1297 case ConfigureRequest:
1300 handler[ev.type](&ev);
1304 if((nw = ev.xmotion.x - ocx - 2 * c->border + 1) <= 0)
1306 if((nh = ev.xmotion.y - ocy - 2 * c->border + 1) <= 0)
1308 if(!c->isfloating && !lt->isfloating && (abs(nw - c->w) > SNAP || abs(nh - c->h) > SNAP))
1309 togglefloating(NULL);
1310 if((lt->isfloating) || c->isfloating)
1311 resize(c, c->x, c->y, nw, nh, True);
1326 if(sel->isfloating || lt->isfloating)
1327 XRaiseWindow(dpy, sel->win);
1328 if(!lt->isfloating) {
1329 wc.stack_mode = Below;
1330 wc.sibling = barwin;
1331 if(!sel->isfloating) {
1332 XConfigureWindow(dpy, sel->win, CWSibling|CWStackMode, &wc);
1333 wc.sibling = sel->win;
1335 for(c = nexttiled(clients); c; c = nexttiled(c->next)) {
1338 XConfigureWindow(dpy, c->win, CWSibling|CWStackMode, &wc);
1339 wc.sibling = c->win;
1343 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1349 char sbuf[sizeof stext];
1352 unsigned int len, offset;
1355 /* main event loop, also reads status text from stdin */
1357 xfd = ConnectionNumber(dpy);
1360 len = sizeof stext - 1;
1361 sbuf[len] = stext[len] = '\0'; /* 0-terminator is never touched */
1365 FD_SET(STDIN_FILENO, &rd);
1367 if(select(xfd + 1, &rd, NULL, NULL, NULL) == -1) {
1370 eprint("select failed\n");
1372 if(FD_ISSET(STDIN_FILENO, &rd)) {
1373 switch((r = read(STDIN_FILENO, sbuf + offset, len - offset))) {
1375 strncpy(stext, strerror(errno), len);
1379 strncpy(stext, "EOF", 4);
1383 for(p = sbuf + offset; r > 0; p++, r--, offset++)
1384 if(*p == '\n' || *p == '\0') {
1386 strncpy(stext, sbuf, len);
1387 p += r - 1; /* p is sbuf + offset + r - 1 */
1388 for(r = 0; *(p - r) && *(p - r) != '\n'; r++);
1391 memmove(sbuf, p - r + 1, r);
1398 while(XPending(dpy)) {
1399 XNextEvent(dpy, &ev);
1400 if(handler[ev.type])
1401 (handler[ev.type])(&ev); /* call handler */
1408 unsigned int i, num;
1409 Window *wins, d1, d2;
1410 XWindowAttributes wa;
1413 if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1414 for(i = 0; i < num; i++) {
1415 if(!XGetWindowAttributes(dpy, wins[i], &wa)
1416 || wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1418 if(wa.map_state == IsViewable || getstate(wins[i]) == IconicState)
1419 manage(wins[i], &wa);
1421 for(i = 0; i < num; i++) { /* now the transients */
1422 if(!XGetWindowAttributes(dpy, wins[i], &wa))
1424 if(XGetTransientForHint(dpy, wins[i], &d1)
1425 && (wa.map_state == IsViewable || getstate(wins[i]) == IconicState))
1426 manage(wins[i], &wa);
1434 setclientstate(Client *c, long state) {
1435 long data[] = {state, None};
1437 XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1438 PropModeReplace, (unsigned char *)data, 2);
1442 getdouble(const char *s) {
1448 result = strtod(s, &endp);
1449 if(s == endp || *endp != 0)
1450 result = strtol(s, &endp, 0);
1452 case 'B': result = dc.font.height + 2; break;
1453 case 'W': result = sw; break;
1454 case 'H': result = sh; break;
1460 setgeom(const char *arg) {
1467 setlayout(const char *arg) {
1468 static Layout *revert = 0;
1473 for(i = 0; i < LENGTH(layouts); i++)
1474 if(!strcmp(arg, layouts[i].symbol))
1476 if(i == LENGTH(layouts))
1478 if(revert && &layouts[i] == lt)
1493 XSetWindowAttributes wa;
1496 screen = DefaultScreen(dpy);
1497 root = RootWindow(dpy, screen);
1500 /* apply default dimensions */
1503 sw = DisplayWidth(dpy, screen);
1504 sh = DisplayHeight(dpy, screen);
1505 applygeometry(GEOMETRY);
1508 wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1509 wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1510 wmatom[WMName] = XInternAtom(dpy, "WM_NAME", False);
1511 wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1512 netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1513 netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1516 wa.cursor = cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1517 cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1518 cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1520 /* init appearance */
1521 dc.norm[ColBorder] = getcolor(NORMBORDERCOLOR);
1522 dc.norm[ColBG] = getcolor(NORMBGCOLOR);
1523 dc.norm[ColFG] = getcolor(NORMFGCOLOR);
1524 dc.sel[ColBorder] = getcolor(SELBORDERCOLOR);
1525 dc.sel[ColBG] = getcolor(SELBGCOLOR);
1526 dc.sel[ColFG] = getcolor(SELFGCOLOR);
1529 dc.drawable = XCreatePixmap(dpy, root, DisplayWidth(dpy, screen), bh, DefaultDepth(dpy, screen));
1530 dc.gc = XCreateGC(dpy, root, 0, 0);
1531 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
1533 XSetFont(dpy, dc.gc, dc.font.xfont->fid);
1536 seltags = emallocz(TAGSZ);
1537 prevtags = emallocz(TAGSZ);
1538 seltags[0] = prevtags[0] = True;
1544 for(blw = i = 0; i < LENGTH(layouts); i++) {
1545 i = textw(layouts[i].symbol);
1550 wa.override_redirect = 1;
1551 wa.background_pixmap = ParentRelative;
1552 wa.event_mask = ButtonPressMask|ExposureMask;
1554 barwin = XCreateWindow(dpy, root, bx, by, bw, bh, 0, DefaultDepth(dpy, screen),
1555 CopyFromParent, DefaultVisual(dpy, screen),
1556 CWOverrideRedirect|CWBackPixmap|CWEventMask, &wa);
1557 XDefineCursor(dpy, barwin, cursor[CurNormal]);
1558 XMapRaised(dpy, barwin);
1559 strcpy(stext, "dwm-"VERSION);
1562 /* EWMH support per view */
1563 XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1564 PropModeReplace, (unsigned char *) netatom, NetLast);
1566 /* select for events */
1567 wa.event_mask = SubstructureRedirectMask|SubstructureNotifyMask
1568 |EnterWindowMask|LeaveWindowMask|StructureNotifyMask;
1569 XChangeWindowAttributes(dpy, root, CWEventMask|CWCursor, &wa);
1570 XSelectInput(dpy, root, wa.event_mask);
1578 spawn(const char *arg) {
1579 static char *shell = NULL;
1581 if(!shell && !(shell = getenv("SHELL")))
1585 /* The double-fork construct avoids zombie processes and keeps the code
1586 * clean from stupid signal handlers. */
1590 close(ConnectionNumber(dpy));
1592 execl(shell, shell, "-c", arg, (char *)NULL);
1593 fprintf(stderr, "dwm: execl '%s -c %s'", shell, arg);
1602 tag(const char *arg) {
1607 for(i = 0; i < LENGTH(tags); i++)
1608 sel->tags[i] = (NULL == arg);
1609 sel->tags[idxoftag(arg)] = True;
1614 textnw(const char *text, unsigned int len) {
1618 XmbTextExtents(dc.font.set, text, len, NULL, &r);
1621 return XTextWidth(dc.font.xfont, text, len);
1625 textw(const char *text) {
1626 return textnw(text, strlen(text)) + dc.font.height;
1632 unsigned int i, n = counttiled();
1646 for(i = 0, c = nexttiled(c->next); c; c = nexttiled(c->next), i++) {
1647 if(i + 1 == n) /* remainder */
1648 tileresize(c, x, ty, (tx + tw) - x - 2 * c->border, th - 2 * c->border);
1650 tileresize(c, x, ty, w - 2 * c->border, th - 2 * c->border);
1652 x = c->x + c->w + 2 * c->border;
1657 tilemaster(unsigned int n) {
1658 Client *c = nexttiled(clients);
1661 tileresize(c, mox, moy, mow - 2 * c->border, moh - 2 * c->border);
1663 tileresize(c, mx, my, mw - 2 * c->border, mh - 2 * c->border);
1668 tileresize(Client *c, int x, int y, int w, int h) {
1669 resize(c, x, y, w, h, RESIZEHINTS);
1670 if((RESIZEHINTS) && ((c->h < bh) || (c->h > h) || (c->w < bh) || (c->w > w)))
1671 /* client doesn't accept size constraints */
1672 resize(c, x, y, w, h, False);
1678 unsigned int i, n = counttiled();
1692 for(i = 0, c = nexttiled(c->next); c; c = nexttiled(c->next), i++) {
1693 if(i + 1 == n) /* remainder */
1694 tileresize(c, tx, y, tw - 2 * c->border, (ty + th) - y - 2 * c->border);
1696 tileresize(c, tx, y, tw - 2 * c->border, h - 2 * c->border);
1698 y = c->y + c->h + 2 * c->border;
1703 togglefloating(const char *arg) {
1706 sel->isfloating = !sel->isfloating;
1708 resize(sel, sel->x, sel->y, sel->w, sel->h, True);
1713 toggletag(const char *arg) {
1719 sel->tags[i] = !sel->tags[i];
1720 for(j = 0; j < LENGTH(tags) && !sel->tags[j]; j++);
1721 if(j == LENGTH(tags))
1722 sel->tags[i] = True; /* at least one tag must be enabled */
1727 toggleview(const char *arg) {
1731 seltags[i] = !seltags[i];
1732 for(j = 0; j < LENGTH(tags) && !seltags[j]; j++);
1733 if(j == LENGTH(tags))
1734 seltags[i] = True; /* at least one tag must be viewed */
1742 XMoveWindow(dpy, c->win, c->x, c->y);
1743 c->isbanned = False;
1747 unmanage(Client *c) {
1750 wc.border_width = c->oldborder;
1751 /* The server grab construct avoids race conditions. */
1753 XSetErrorHandler(xerrordummy);
1754 XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
1759 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1760 setclientstate(c, WithdrawnState);
1764 XSetErrorHandler(xerror);
1770 unmapnotify(XEvent *e) {
1772 XUnmapEvent *ev = &e->xunmap;
1774 if((c = getclient(ev->window)))
1779 updatebarpos(void) {
1781 if(dc.drawable != 0)
1782 XFreePixmap(dpy, dc.drawable);
1783 dc.drawable = XCreatePixmap(dpy, root, bw, bh, DefaultDepth(dpy, screen));
1784 XMoveResizeWindow(dpy, barwin, bx, by, bw, bh);
1788 updatesizehints(Client *c) {
1792 if(!XGetWMNormalHints(dpy, c->win, &size, &msize) || !size.flags)
1794 c->flags = size.flags;
1795 if(c->flags & PBaseSize) {
1796 c->basew = size.base_width;
1797 c->baseh = size.base_height;
1799 else if(c->flags & PMinSize) {
1800 c->basew = size.min_width;
1801 c->baseh = size.min_height;
1804 c->basew = c->baseh = 0;
1805 if(c->flags & PResizeInc) {
1806 c->incw = size.width_inc;
1807 c->inch = size.height_inc;
1810 c->incw = c->inch = 0;
1811 if(c->flags & PMaxSize) {
1812 c->maxw = size.max_width;
1813 c->maxh = size.max_height;
1816 c->maxw = c->maxh = 0;
1817 if(c->flags & PMinSize) {
1818 c->minw = size.min_width;
1819 c->minh = size.min_height;
1821 else if(c->flags & PBaseSize) {
1822 c->minw = size.base_width;
1823 c->minh = size.base_height;
1826 c->minw = c->minh = 0;
1827 if(c->flags & PAspect) {
1828 c->minax = size.min_aspect.x;
1829 c->maxax = size.max_aspect.x;
1830 c->minay = size.min_aspect.y;
1831 c->maxay = size.max_aspect.y;
1834 c->minax = c->maxax = c->minay = c->maxay = 0;
1835 c->isfixed = (c->maxw && c->minw && c->maxh && c->minh
1836 && c->maxw == c->minw && c->maxh == c->minh);
1840 updatetitle(Client *c) {
1841 if(!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
1842 gettextprop(c->win, wmatom[WMName], c->name, sizeof c->name);
1846 updatewmhints(Client *c) {
1849 if((wmh = XGetWMHints(dpy, c->win))) {
1851 sel->isurgent = False;
1853 c->isurgent = (wmh->flags & XUrgencyHint) ? True : False;
1860 view(const char *arg) {
1863 for(i = 0; i < LENGTH(tags); i++)
1864 tmp[i] = (NULL == arg);
1865 tmp[idxoftag(arg)] = True;
1867 if(memcmp(seltags, tmp, TAGSZ) != 0) {
1868 memcpy(prevtags, seltags, TAGSZ);
1869 memcpy(seltags, tmp, TAGSZ);
1875 viewprevtag(const char *arg) {
1877 memcpy(tmp, seltags, TAGSZ);
1878 memcpy(seltags, prevtags, TAGSZ);
1879 memcpy(prevtags, tmp, TAGSZ);
1883 /* There's no way to check accesses to destroyed windows, thus those cases are
1884 * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
1885 * default error handler, which may call exit. */
1887 xerror(Display *dpy, XErrorEvent *ee) {
1888 if(ee->error_code == BadWindow
1889 || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1890 || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1891 || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1892 || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1893 || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1894 || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1895 || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1897 fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1898 ee->request_code, ee->error_code);
1899 return xerrorxlib(dpy, ee); /* may call exit */
1903 xerrordummy(Display *dpy, XErrorEvent *ee) {
1907 /* Startup Error handler to check if another window manager
1908 * is already running. */
1910 xerrorstart(Display *dpy, XErrorEvent *ee) {
1916 zoom(const char *arg) {
1919 if(!sel || lt->isfloating || sel->isfloating)
1921 if(c == nexttiled(clients))
1922 if(!(c = nexttiled(c->next)))
1931 main(int argc, char *argv[]) {
1932 if(argc == 2 && !strcmp("-v", argv[1]))
1933 eprint("dwm-"VERSION", © 2006-2008 dwm engineers, see LICENSE for details\n");
1935 eprint("usage: dwm [-v]\n");
1937 setlocale(LC_CTYPE, "");
1938 if(!(dpy = XOpenDisplay(0)))
1939 eprint("dwm: cannot open display\n");