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 a bit array to indicate the tags of a
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>
43 #include <X11/extensions/Xinerama.h>
47 #define BUTTONMASK (ButtonPressMask|ButtonReleaseMask)
48 #define CLEANMASK(mask) (mask & ~(numlockmask|LockMask))
49 #define INRECT(X,Y,RX,RY,RW,RH) ((X) >= (RX) && (X) < (RX) + (RW) && (Y) >= (RY) && (Y) < (RY) + (RH))
50 #define ISVISIBLE(x) (x->tags & tagset[seltags])
51 #define LENGTH(x) (sizeof x / sizeof x[0])
52 #define MAX(a, b) ((a) > (b) ? (a) : (b))
53 #define MIN(a, b) ((a) < (b) ? (a) : (b))
55 #define MOUSEMASK (BUTTONMASK|PointerMotionMask)
56 #define NOBORDER(x) ((x) - 2 * c->bw)
57 #define TAGMASK ((int)((1LL << LENGTH(tags)) - 1))
58 #define TEXTW(x) (textnw(x, strlen(x)) + dc.font.height)
61 enum { CurNormal, CurResize, CurMove, CurLast }; /* cursor */
62 enum { ColBorder, ColFG, ColBG, ColLast }; /* color */
63 enum { NetSupported, NetWMName, NetLast }; /* EWMH atoms */
64 enum { WMProtocols, WMDelete, WMState, WMLast }; /* default atoms */
65 enum { ClkTagBar, ClkLtSymbol, ClkStatusText, ClkWinTitle,
66 ClkClientWin, ClkRootWin, ClkLast }; /* clicks */
79 void (*func)(const Arg *arg);
83 typedef struct Client Client;
88 int basew, baseh, incw, inch, maxw, maxh, minw, minh;
91 Bool isfixed, isfloating, isurgent;
99 unsigned long norm[ColLast];
100 unsigned long sel[ColLast];
110 } DC; /* draw context */
115 void (*func)(const Arg *);
121 void (*arrange)(void);
126 const char *instance;
132 /* function declarations */
133 static void applyrules(Client *c);
134 static void arrange(void);
135 static void attach(Client *c);
136 static void attachstack(Client *c);
137 static void buttonpress(XEvent *e);
138 static void checkotherwm(void);
139 static void cleanup(void);
140 static void clearurgent(void);
141 static void configure(Client *c);
142 static void configurenotify(XEvent *e);
143 static void configurerequest(XEvent *e);
144 static void destroynotify(XEvent *e);
145 static void detach(Client *c);
146 static void detachstack(Client *c);
147 static void die(const char *errstr, ...);
148 static void drawbar(void);
149 static void drawsquare(Bool filled, Bool empty, Bool invert, unsigned long col[ColLast]);
150 static void drawtext(const char *text, unsigned long col[ColLast], Bool invert);
151 static void enternotify(XEvent *e);
152 static void expose(XEvent *e);
153 static void focus(Client *c);
154 static void focusin(XEvent *e);
155 static void focusstack(const Arg *arg);
156 static Client *getclient(Window w);
157 static unsigned long getcolor(const char *colstr);
158 static long getstate(Window w);
159 static Bool gettextprop(Window w, Atom atom, char *text, unsigned int size);
160 static void grabbuttons(Client *c, Bool focused);
161 static void grabkeys(void);
162 static void initfont(const char *fontstr);
163 static Bool isprotodel(Client *c);
164 static void keypress(XEvent *e);
165 static void killclient(const Arg *arg);
166 static void manage(Window w, XWindowAttributes *wa);
167 static void mappingnotify(XEvent *e);
168 static void maprequest(XEvent *e);
169 static void monocle(void);
170 static void movemouse(const Arg *arg);
171 static Client *nexttiled(Client *c);
172 static void propertynotify(XEvent *e);
173 static void quit(const Arg *arg);
174 static void resize(Client *c, int x, int y, int w, int h, Bool sizehints);
175 static void resizemouse(const Arg *arg);
176 static void restack(void);
177 static void run(void);
178 static void scan(void);
179 static void setclientstate(Client *c, long state);
180 static void setlayout(const Arg *arg);
181 static void setmfact(const Arg *arg);
182 static void setup(void);
183 static void showhide(Client *c);
184 static void spawn(const Arg *arg);
185 static void tag(const Arg *arg);
186 static int textnw(const char *text, unsigned int len);
187 static void tile(void);
188 static void togglebar(const Arg *arg);
189 static void togglefloating(const Arg *arg);
190 static void toggletag(const Arg *arg);
191 static void toggleview(const Arg *arg);
192 static void unmanage(Client *c);
193 static void unmapnotify(XEvent *e);
194 static void updatebar(void);
195 static void updategeom(void);
196 static void updatenumlockmask(void);
197 static void updatesizehints(Client *c);
198 static void updatetitle(Client *c);
199 static void updatewmhints(Client *c);
200 static void view(const Arg *arg);
201 static int xerror(Display *dpy, XErrorEvent *ee);
202 static int xerrordummy(Display *dpy, XErrorEvent *ee);
203 static int xerrorstart(Display *dpy, XErrorEvent *ee);
204 static void zoom(const Arg *arg);
207 static char stext[256];
209 static int sx, sy, sw, sh; /* X display screen geometry x, y, width, height */
210 static int by, bh, blw; /* bar geometry y, height and layout symbol width */
211 static int wx, wy, ww, wh; /* window area geometry x, y, width, height, bar excluded */
212 static unsigned int seltags = 0, sellt = 0;
213 static int (*xerrorxlib)(Display *, XErrorEvent *);
214 static unsigned int numlockmask = 0;
215 static void (*handler[LASTEvent]) (XEvent *) = {
216 [ButtonPress] = buttonpress,
217 [ConfigureRequest] = configurerequest,
218 [ConfigureNotify] = configurenotify,
219 [DestroyNotify] = destroynotify,
220 [EnterNotify] = enternotify,
223 [KeyPress] = keypress,
224 [MappingNotify] = mappingnotify,
225 [MapRequest] = maprequest,
226 [PropertyNotify] = propertynotify,
227 [UnmapNotify] = unmapnotify
229 static Atom wmatom[WMLast], netatom[NetLast];
231 static Bool running = True;
232 static Client *clients = NULL;
233 static Client *sel = NULL;
234 static Client *stack = NULL;
235 static Cursor cursor[CurLast];
238 static Layout *lt[] = { NULL, NULL };
239 static Window root, barwin;
240 /* configuration, allows nested code to access above variables */
243 /* compile-time check if all tags fit into an unsigned int bit array. */
244 struct NumTags { char limitexceeded[sizeof(unsigned int) * 8 < LENGTH(tags) ? -1 : 1]; };
246 /* function implementations */
248 applyrules(Client *c) {
251 XClassHint ch = { 0 };
254 if(XGetClassHint(dpy, c->win, &ch)) {
255 for(i = 0; i < LENGTH(rules); i++) {
257 if((!r->title || strstr(c->name, r->title))
258 && (!r->class || (ch.res_class && strstr(ch.res_class, r->class)))
259 && (!r->instance || (ch.res_name && strstr(ch.res_name, r->instance)))) {
260 c->isfloating = r->isfloating;
261 c->tags |= r->tags & TAGMASK;
270 c->tags = tagset[seltags];
277 if(lt[sellt]->arrange)
278 lt[sellt]->arrange();
289 attachstack(Client *c) {
295 buttonpress(XEvent *e) {
296 unsigned int i, x, click;
299 XButtonPressedEvent *ev = &e->xbutton;
302 if(ev->window == barwin) {
304 do x += TEXTW(tags[i]); while(ev->x >= x && ++i < LENGTH(tags));
305 if(i < LENGTH(tags)) {
309 else if(ev->x < x + blw)
311 else if(ev->x > wx + ww - TEXTW(stext))
312 click = ClkStatusText;
316 else if((c = getclient(ev->window))) {
318 click = ClkClientWin;
321 for(i = 0; i < LENGTH(buttons); i++)
322 if(click == buttons[i].click && buttons[i].func && buttons[i].button == ev->button
323 && CLEANMASK(buttons[i].mask) == CLEANMASK(ev->state))
324 buttons[i].func(click == ClkTagBar && buttons[i].arg.i == 0 ? &arg : &buttons[i].arg);
330 xerrorxlib = XSetErrorHandler(xerrorstart);
332 /* this causes an error if some other window manager is running */
333 XSelectInput(dpy, DefaultRootWindow(dpy), SubstructureRedirectMask);
336 die("dwm: another window manager is already running\n");
337 XSetErrorHandler(xerror);
344 Layout foo = { "", NULL };
352 XFreeFontSet(dpy, dc.font.set);
354 XFreeFont(dpy, dc.font.xfont);
355 XUngrabKey(dpy, AnyKey, AnyModifier, root);
356 XFreePixmap(dpy, dc.drawable);
358 XFreeCursor(dpy, cursor[CurNormal]);
359 XFreeCursor(dpy, cursor[CurResize]);
360 XFreeCursor(dpy, cursor[CurMove]);
361 XDestroyWindow(dpy, barwin);
363 XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime);
371 for(c = clients; c; c = c->next)
372 if(ISVISIBLE(c) && c->isurgent) {
374 if (!(wmh = XGetWMHints(dpy, c->win)))
377 wmh->flags &= ~XUrgencyHint;
378 XSetWMHints(dpy, c->win, wmh);
384 configure(Client *c) {
387 ce.type = ConfigureNotify;
395 ce.border_width = c->bw;
397 ce.override_redirect = False;
398 XSendEvent(dpy, c->win, False, StructureNotifyMask, (XEvent *)&ce);
402 configurenotify(XEvent *e) {
403 XConfigureEvent *ev = &e->xconfigure;
405 if(ev->window == root && (ev->width != sw || ev->height != sh)) {
415 configurerequest(XEvent *e) {
417 XConfigureRequestEvent *ev = &e->xconfigurerequest;
420 if((c = getclient(ev->window))) {
421 if(ev->value_mask & CWBorderWidth)
422 c->bw = ev->border_width;
423 else if(c->isfloating || !lt[sellt]->arrange) {
424 if(ev->value_mask & CWX)
426 if(ev->value_mask & CWY)
428 if(ev->value_mask & CWWidth)
430 if(ev->value_mask & CWHeight)
432 if((c->x - sx + c->w) > sw && c->isfloating)
433 c->x = sx + (sw / 2 - c->w / 2); /* center in x direction */
434 if((c->y - sy + c->h) > sh && c->isfloating)
435 c->y = sy + (sh / 2 - c->h / 2); /* center in y direction */
436 if((ev->value_mask & (CWX|CWY)) && !(ev->value_mask & (CWWidth|CWHeight)))
439 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h);
447 wc.width = ev->width;
448 wc.height = ev->height;
449 wc.border_width = ev->border_width;
450 wc.sibling = ev->above;
451 wc.stack_mode = ev->detail;
452 XConfigureWindow(dpy, ev->window, ev->value_mask, &wc);
458 destroynotify(XEvent *e) {
460 XDestroyWindowEvent *ev = &e->xdestroywindow;
462 if((c = getclient(ev->window)))
470 for(tc = &clients; *tc && *tc != c; tc = &(*tc)->next);
475 detachstack(Client *c) {
478 for(tc = &stack; *tc && *tc != c; tc = &(*tc)->snext);
483 die(const char *errstr, ...) {
486 va_start(ap, errstr);
487 vfprintf(stderr, errstr, ap);
495 unsigned int i, occ = 0, urg = 0;
499 for(c = clients; c; c = c->next) {
506 for(i = 0; i < LENGTH(tags); i++) {
507 dc.w = TEXTW(tags[i]);
508 col = tagset[seltags] & 1 << i ? dc.sel : dc.norm;
509 drawtext(tags[i], col, urg & 1 << i);
510 drawsquare(sel && sel->tags & 1 << i, occ & 1 << i, urg & 1 << i, col);
515 drawtext(lt[sellt]->symbol, dc.norm, False);
526 drawtext(stext, dc.norm, False);
527 if((dc.w = dc.x - x) > bh) {
530 drawtext(sel->name, dc.sel, False);
531 drawsquare(sel->isfixed, sel->isfloating, False, dc.sel);
534 drawtext(NULL, dc.norm, False);
536 XCopyArea(dpy, dc.drawable, barwin, dc.gc, 0, 0, ww, bh, 0, 0);
541 drawsquare(Bool filled, Bool empty, Bool invert, unsigned long col[ColLast]) {
544 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
546 gcv.foreground = col[invert ? ColBG : ColFG];
547 XChangeGC(dpy, dc.gc, GCForeground, &gcv);
548 x = (dc.font.ascent + dc.font.descent + 2) / 4;
552 r.width = r.height = x + 1;
553 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
556 r.width = r.height = x;
557 XDrawRectangles(dpy, dc.drawable, dc.gc, &r, 1);
562 drawtext(const char *text, unsigned long col[ColLast], Bool invert) {
564 int i, x, y, h, len, olen;
565 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
567 XSetForeground(dpy, dc.gc, col[invert ? ColFG : ColBG]);
568 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
572 h = dc.font.ascent + dc.font.descent;
573 y = dc.y + (dc.h / 2) - (h / 2) + dc.font.ascent;
575 /* shorten text if necessary */
576 for(len = MIN(olen, sizeof buf); len && textnw(text, len) > dc.w - h; len--);
579 memcpy(buf, text, len);
581 for(i = len; i && i > len - 3; buf[--i] = '.');
582 XSetForeground(dpy, dc.gc, col[invert ? ColBG : ColFG]);
584 XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
586 XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
590 enternotify(XEvent *e) {
592 XCrossingEvent *ev = &e->xcrossing;
594 if((ev->mode != NotifyNormal || ev->detail == NotifyInferior) && ev->window != root)
596 if((c = getclient(ev->window)))
604 XExposeEvent *ev = &e->xexpose;
606 if(ev->count == 0 && (ev->window == barwin))
612 if(!c || !ISVISIBLE(c))
613 for(c = stack; c && !ISVISIBLE(c); c = c->snext);
614 if(sel && sel != c) {
615 grabbuttons(sel, False);
616 XSetWindowBorder(dpy, sel->win, dc.norm[ColBorder]);
621 grabbuttons(c, True);
622 XSetWindowBorder(dpy, c->win, dc.sel[ColBorder]);
623 XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
626 XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
632 focusin(XEvent *e) { /* there are some broken focus acquiring clients */
633 XFocusChangeEvent *ev = &e->xfocus;
635 if(sel && ev->window != sel->win)
636 XSetInputFocus(dpy, sel->win, RevertToPointerRoot, CurrentTime);
640 focusstack(const Arg *arg) {
641 Client *c = NULL, *i;
646 for(c = sel->next; c && !ISVISIBLE(c); c = c->next);
648 for(c = clients; c && !ISVISIBLE(c); c = c->next);
651 for(i = clients; i != sel; i = i->next)
655 for(; i; i = i->next)
666 getclient(Window w) {
669 for(c = clients; c && c->win != w; c = c->next);
674 getcolor(const char *colstr) {
675 Colormap cmap = DefaultColormap(dpy, screen);
678 if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
679 die("error, cannot allocate color '%s'\n", colstr);
687 unsigned char *p = NULL;
688 unsigned long n, extra;
691 status = XGetWindowProperty(dpy, w, wmatom[WMState], 0L, 2L, False, wmatom[WMState],
692 &real, &format, &n, &extra, (unsigned char **)&p);
693 if(status != Success)
702 gettextprop(Window w, Atom atom, char *text, unsigned int size) {
707 if(!text || size == 0)
710 XGetTextProperty(dpy, w, &name, atom);
713 if(name.encoding == XA_STRING)
714 strncpy(text, (char *)name.value, size - 1);
716 if(XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success
718 strncpy(text, *list, size - 1);
719 XFreeStringList(list);
722 text[size - 1] = '\0';
728 grabbuttons(Client *c, Bool focused) {
732 unsigned int modifiers[] = { 0, LockMask, numlockmask, numlockmask|LockMask };
733 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
735 for(i = 0; i < LENGTH(buttons); i++)
736 if(buttons[i].click == ClkClientWin)
737 for(j = 0; j < LENGTH(modifiers); j++)
738 XGrabButton(dpy, buttons[i].button, buttons[i].mask | modifiers[j], c->win, False, BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
740 XGrabButton(dpy, AnyButton, AnyModifier, c->win, False,
741 BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
750 unsigned int modifiers[] = { 0, LockMask, numlockmask, numlockmask|LockMask };
753 XUngrabKey(dpy, AnyKey, AnyModifier, root);
754 for(i = 0; i < LENGTH(keys); i++) {
755 if((code = XKeysymToKeycode(dpy, keys[i].keysym)))
756 for(j = 0; j < LENGTH(modifiers); j++)
757 XGrabKey(dpy, code, keys[i].mod | modifiers[j], root,
758 True, GrabModeAsync, GrabModeAsync);
764 initfont(const char *fontstr) {
765 char *def, **missing;
769 dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
772 fprintf(stderr, "dwm: missing fontset: %s\n", missing[n]);
773 XFreeStringList(missing);
776 XFontSetExtents *font_extents;
777 XFontStruct **xfonts;
779 dc.font.ascent = dc.font.descent = 0;
780 font_extents = XExtentsOfFontSet(dc.font.set);
781 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
782 for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
783 dc.font.ascent = MAX(dc.font.ascent, (*xfonts)->ascent);
784 dc.font.descent = MAX(dc.font.descent,(*xfonts)->descent);
789 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr))
790 && !(dc.font.xfont = XLoadQueryFont(dpy, "fixed")))
791 die("error, cannot load font: '%s'\n", fontstr);
792 dc.font.ascent = dc.font.xfont->ascent;
793 dc.font.descent = dc.font.xfont->descent;
795 dc.font.height = dc.font.ascent + dc.font.descent;
799 isprotodel(Client *c) {
804 if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
805 for(i = 0; !ret && i < n; i++)
806 if(protocols[i] == wmatom[WMDelete])
814 keypress(XEvent *e) {
820 keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
821 for(i = 0; i < LENGTH(keys); i++)
822 if(keysym == keys[i].keysym
823 && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state)
825 keys[i].func(&(keys[i].arg));
829 killclient(const Arg *arg) {
834 if(isprotodel(sel)) {
835 ev.type = ClientMessage;
836 ev.xclient.window = sel->win;
837 ev.xclient.message_type = wmatom[WMProtocols];
838 ev.xclient.format = 32;
839 ev.xclient.data.l[0] = wmatom[WMDelete];
840 ev.xclient.data.l[1] = CurrentTime;
841 XSendEvent(dpy, sel->win, False, NoEventMask, &ev);
844 XKillClient(dpy, sel->win);
848 manage(Window w, XWindowAttributes *wa) {
849 Client *c, *t = NULL;
853 if(!(c = calloc(1, sizeof(Client))))
854 die("fatal: could not calloc() %u bytes\n", sizeof(Client));
862 c->oldbw = wa->border_width;
863 if(c->w == sw && c->h == sh) {
869 if(c->x + c->w + 2 * c->bw > sx + sw)
870 c->x = sx + sw - NOBORDER(c->w);
871 if(c->y + c->h + 2 * c->bw > sy + sh)
872 c->y = sy + sh - NOBORDER(c->h);
873 c->x = MAX(c->x, sx);
874 /* only fix client y-offset, if the client center might cover the bar */
875 c->y = MAX(c->y, ((by == 0) && (c->x + (c->w / 2) >= wx) && (c->x + (c->w / 2) < wx + ww)) ? bh : sy);
879 wc.border_width = c->bw;
880 XConfigureWindow(dpy, w, CWBorderWidth, &wc);
881 XSetWindowBorder(dpy, w, dc.norm[ColBorder]);
882 configure(c); /* propagates border_width, if size doesn't change */
884 XSelectInput(dpy, w, EnterWindowMask|FocusChangeMask|PropertyChangeMask|StructureNotifyMask);
885 grabbuttons(c, False);
887 if(XGetTransientForHint(dpy, w, &trans))
888 t = getclient(trans);
894 c->isfloating = trans != None || c->isfixed;
896 XRaiseWindow(dpy, c->win);
899 XMoveResizeWindow(dpy, c->win, c->x + 2 * sw, c->y, c->w, c->h); /* some windows require this */
900 XMapWindow(dpy, c->win);
901 setclientstate(c, NormalState);
906 mappingnotify(XEvent *e) {
907 XMappingEvent *ev = &e->xmapping;
909 XRefreshKeyboardMapping(ev);
910 if(ev->request == MappingKeyboard)
915 maprequest(XEvent *e) {
916 static XWindowAttributes wa;
917 XMapRequestEvent *ev = &e->xmaprequest;
919 if(!XGetWindowAttributes(dpy, ev->window, &wa))
921 if(wa.override_redirect)
923 if(!getclient(ev->window))
924 manage(ev->window, &wa);
931 for(c = nexttiled(clients); c; c = nexttiled(c->next))
932 resize(c, wx, wy, NOBORDER(ww), NOBORDER(wh), resizehints);
936 movemouse(const Arg *arg) {
937 int x, y, ocx, ocy, di, nx, ny;
948 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
949 None, cursor[CurMove], CurrentTime) != GrabSuccess)
951 XQueryPointer(dpy, root, &dummy, &dummy, &x, &y, &di, &di, &dui);
953 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
955 case ConfigureRequest:
958 handler[ev.type](&ev);
962 nx = ocx + (ev.xmotion.x - x);
963 ny = ocy + (ev.xmotion.y - y);
964 if(snap && nx >= wx && nx <= wx + ww
965 && ny >= wy && ny <= wy + wh) {
966 if(abs(wx - nx) < snap)
968 else if(abs((wx + ww) - (nx + c->w + 2 * c->bw)) < snap)
969 nx = wx + ww - NOBORDER(c->w);
970 if(abs(wy - ny) < snap)
972 else if(abs((wy + wh) - (ny + c->h + 2 * c->bw)) < snap)
973 ny = wy + wh - NOBORDER(c->h);
974 if(!c->isfloating && lt[sellt]->arrange && (abs(nx - c->x) > snap || abs(ny - c->y) > snap))
975 togglefloating(NULL);
977 if(!lt[sellt]->arrange || c->isfloating)
978 resize(c, nx, ny, c->w, c->h, False);
982 while(ev.type != ButtonRelease);
983 XUngrabPointer(dpy, CurrentTime);
987 nexttiled(Client *c) {
988 for(; c && (c->isfloating || !ISVISIBLE(c)); c = c->next);
993 propertynotify(XEvent *e) {
996 XPropertyEvent *ev = &e->xproperty;
998 if(ev->state == PropertyDelete)
1000 if((c = getclient(ev->window))) {
1003 case XA_WM_TRANSIENT_FOR:
1004 XGetTransientForHint(dpy, c->win, &trans);
1005 if(!c->isfloating && (c->isfloating = (getclient(trans) != NULL)))
1008 case XA_WM_NORMAL_HINTS:
1016 if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
1025 quit(const Arg *arg) {
1026 readin = running = False;
1030 resize(Client *c, int x, int y, int w, int h, Bool sizehints) {
1034 /* see last two sentences in ICCCM 4.1.2.3 */
1035 Bool baseismin = c->basew == c->minw && c->baseh == c->minh;
1037 /* set minimum possible */
1041 if(!baseismin) { /* temporarily remove base dimensions */
1046 /* adjust for aspect limits */
1047 if(c->mina > 0 && c->maxa > 0) {
1048 if(c->maxa < (float)w / h)
1050 else if(c->mina < (float)h / w)
1054 if(baseismin) { /* increment calculation requires this */
1059 /* adjust for increment value */
1065 /* restore base dimensions */
1069 w = MAX(w, c->minw);
1070 h = MAX(h, c->minh);
1073 w = MIN(w, c->maxw);
1076 h = MIN(h, c->maxh);
1078 if(w <= 0 || h <= 0)
1081 x = sw - NOBORDER(w);
1083 y = sh - NOBORDER(h);
1084 if(x + w + 2 * c->bw < sx)
1086 if(y + h + 2 * c->bw < sy)
1092 if(c->x != x || c->y != y || c->w != w || c->h != h) {
1095 c->w = wc.width = w;
1096 c->h = wc.height = h;
1097 wc.border_width = c->bw;
1098 XConfigureWindow(dpy, c->win,
1099 CWX|CWY|CWWidth|CWHeight|CWBorderWidth, &wc);
1106 resizemouse(const Arg *arg) {
1117 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1118 None, cursor[CurResize], CurrentTime) != GrabSuccess)
1120 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->bw - 1, c->h + c->bw - 1);
1122 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
1124 case ConfigureRequest:
1127 handler[ev.type](&ev);
1131 nw = MAX(ev.xmotion.x - NOBORDER(ocx) + 1, 1);
1132 nh = MAX(ev.xmotion.y - NOBORDER(ocy) + 1, 1);
1134 if(snap && nw >= wx && nw <= wx + ww
1135 && nh >= wy && nh <= wy + wh) {
1136 if(!c->isfloating && lt[sellt]->arrange
1137 && (abs(nw - c->w) > snap || abs(nh - c->h) > snap))
1138 togglefloating(NULL);
1140 if(!lt[sellt]->arrange || c->isfloating)
1141 resize(c, c->x, c->y, nw, nh, True);
1145 while(ev.type != ButtonRelease);
1146 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->bw - 1, c->h + c->bw - 1);
1147 XUngrabPointer(dpy, CurrentTime);
1148 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1160 if(sel->isfloating || !lt[sellt]->arrange)
1161 XRaiseWindow(dpy, sel->win);
1162 if(lt[sellt]->arrange) {
1163 wc.stack_mode = Below;
1164 wc.sibling = barwin;
1165 for(c = stack; c; c = c->snext)
1166 if(!c->isfloating && ISVISIBLE(c)) {
1167 XConfigureWindow(dpy, c->win, CWSibling|CWStackMode, &wc);
1168 wc.sibling = c->win;
1172 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1178 char sbuf[sizeof stext];
1181 unsigned int len, offset;
1184 /* main event loop, also reads status text from stdin */
1186 xfd = ConnectionNumber(dpy);
1188 len = sizeof stext - 1;
1189 sbuf[len] = stext[len] = '\0'; /* 0-terminator is never touched */
1193 FD_SET(STDIN_FILENO, &rd);
1195 if(select(xfd + 1, &rd, NULL, NULL, NULL) == -1) {
1198 die("select failed\n");
1200 if(FD_ISSET(STDIN_FILENO, &rd)) {
1201 switch((r = read(STDIN_FILENO, sbuf + offset, len - offset))) {
1203 strncpy(stext, strerror(errno), len);
1207 strncpy(stext, "EOF", 4);
1211 for(p = sbuf + offset; r > 0; p++, r--, offset++)
1212 if(*p == '\n' || *p == '\0') {
1214 strncpy(stext, sbuf, len);
1215 p += r - 1; /* p is sbuf + offset + r - 1 */
1216 for(r = 0; *(p - r) && *(p - r) != '\n'; r++);
1219 memmove(sbuf, p - r + 1, r);
1226 while(XPending(dpy)) {
1227 XNextEvent(dpy, &ev);
1228 if(handler[ev.type])
1229 (handler[ev.type])(&ev); /* call handler */
1236 unsigned int i, num;
1237 Window d1, d2, *wins = NULL;
1238 XWindowAttributes wa;
1240 if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1241 for(i = 0; i < num; i++) {
1242 if(!XGetWindowAttributes(dpy, wins[i], &wa)
1243 || wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1245 if(wa.map_state == IsViewable || getstate(wins[i]) == IconicState)
1246 manage(wins[i], &wa);
1248 for(i = 0; i < num; i++) { /* now the transients */
1249 if(!XGetWindowAttributes(dpy, wins[i], &wa))
1251 if(XGetTransientForHint(dpy, wins[i], &d1)
1252 && (wa.map_state == IsViewable || getstate(wins[i]) == IconicState))
1253 manage(wins[i], &wa);
1261 setclientstate(Client *c, long state) {
1262 long data[] = {state, None};
1264 XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1265 PropModeReplace, (unsigned char *)data, 2);
1269 setlayout(const Arg *arg) {
1270 if(!arg || !arg->v || arg->v != lt[sellt])
1273 lt[sellt] = (Layout *)arg->v;
1280 /* arg > 1.0 will set mfact absolutly */
1282 setmfact(const Arg *arg) {
1285 if(!arg || !lt[sellt]->arrange)
1287 f = arg->f < 1.0 ? arg->f + mfact : arg->f - 1.0;
1288 if(f < 0.1 || f > 0.9)
1298 XSetWindowAttributes wa;
1301 screen = DefaultScreen(dpy);
1302 root = RootWindow(dpy, screen);
1306 sw = DisplayWidth(dpy, screen);
1307 sh = DisplayHeight(dpy, screen);
1308 bh = dc.h = dc.font.height + 2;
1309 lt[0] = &layouts[0];
1310 lt[1] = &layouts[1 % LENGTH(layouts)];
1314 wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1315 wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1316 wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1317 netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1318 netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1321 wa.cursor = cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1322 cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1323 cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1325 /* init appearance */
1326 dc.norm[ColBorder] = getcolor(normbordercolor);
1327 dc.norm[ColBG] = getcolor(normbgcolor);
1328 dc.norm[ColFG] = getcolor(normfgcolor);
1329 dc.sel[ColBorder] = getcolor(selbordercolor);
1330 dc.sel[ColBG] = getcolor(selbgcolor);
1331 dc.sel[ColFG] = getcolor(selfgcolor);
1332 dc.drawable = XCreatePixmap(dpy, root, DisplayWidth(dpy, screen), bh, DefaultDepth(dpy, screen));
1333 dc.gc = XCreateGC(dpy, root, 0, 0);
1334 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
1336 XSetFont(dpy, dc.gc, dc.font.xfont->fid);
1339 for(blw = i = 0; LENGTH(layouts) > 1 && i < LENGTH(layouts); i++) {
1340 w = TEXTW(layouts[i].symbol);
1344 wa.override_redirect = 1;
1345 wa.background_pixmap = ParentRelative;
1346 wa.event_mask = ButtonPressMask|ExposureMask;
1348 barwin = XCreateWindow(dpy, root, wx, by, ww, bh, 0, DefaultDepth(dpy, screen),
1349 CopyFromParent, DefaultVisual(dpy, screen),
1350 CWOverrideRedirect|CWBackPixmap|CWEventMask, &wa);
1351 XDefineCursor(dpy, barwin, cursor[CurNormal]);
1352 XMapRaised(dpy, barwin);
1353 strcpy(stext, "dwm-"VERSION);
1356 /* EWMH support per view */
1357 XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1358 PropModeReplace, (unsigned char *) netatom, NetLast);
1360 /* select for events */
1361 wa.event_mask = SubstructureRedirectMask|SubstructureNotifyMask|ButtonPressMask
1362 |EnterWindowMask|LeaveWindowMask|StructureNotifyMask;
1363 XChangeWindowAttributes(dpy, root, CWEventMask|CWCursor, &wa);
1364 XSelectInput(dpy, root, wa.event_mask);
1370 showhide(Client *c) {
1373 if(ISVISIBLE(c)) { /* show clients top down */
1374 XMoveWindow(dpy, c->win, c->x, c->y);
1375 if(!lt[sellt]->arrange || c->isfloating)
1376 resize(c, c->x, c->y, c->w, c->h, True);
1379 else { /* hide clients bottom up */
1381 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
1386 spawn(const Arg *arg) {
1387 /* The double-fork construct avoids zombie processes and keeps the code
1388 * clean from stupid signal handlers. */
1392 close(ConnectionNumber(dpy));
1394 execvp(((char **)arg->v)[0], (char **)arg->v);
1395 fprintf(stderr, "dwm: execvp %s", ((char **)arg->v)[0]);
1404 tag(const Arg *arg) {
1405 if(sel && arg->ui & TAGMASK) {
1406 sel->tags = arg->ui & TAGMASK;
1412 textnw(const char *text, unsigned int len) {
1416 XmbTextExtents(dc.font.set, text, len, NULL, &r);
1419 return XTextWidth(dc.font.xfont, text, len);
1428 for(n = 0, c = nexttiled(clients); c; c = nexttiled(c->next), n++);
1433 c = nexttiled(clients);
1435 resize(c, wx, wy, NOBORDER(n == 1 ? ww : mw), NOBORDER(wh), resizehints);
1441 x = (wx + mw > c->x + c->w) ? c->x + c->w + 2 * c->bw : wx + mw;
1443 w = (wx + mw > c->x + c->w) ? wx + ww - x : ww - mw;
1448 for(i = 0, c = nexttiled(c->next); c; c = nexttiled(c->next), i++) {
1449 resize(c, x, y, NOBORDER(w), /* remainder */ ((i + 1 == n)
1450 ? NOBORDER(wy + wh) - y : h), resizehints);
1452 y = c->y + c->h + 2 * c->bw;
1457 togglebar(const Arg *arg) {
1465 togglefloating(const Arg *arg) {
1468 sel->isfloating = !sel->isfloating || sel->isfixed;
1470 resize(sel, sel->x, sel->y, sel->w, sel->h, True);
1475 toggletag(const Arg *arg) {
1481 mask = sel->tags ^ (arg->ui & TAGMASK);
1489 toggleview(const Arg *arg) {
1490 unsigned int mask = tagset[seltags] ^ (arg->ui & TAGMASK);
1493 tagset[seltags] = mask;
1500 unmanage(Client *c) {
1503 wc.border_width = c->oldbw;
1504 /* The server grab construct avoids race conditions. */
1506 XSetErrorHandler(xerrordummy);
1507 XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
1512 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1513 setclientstate(c, WithdrawnState);
1516 XSetErrorHandler(xerror);
1522 unmapnotify(XEvent *e) {
1524 XUnmapEvent *ev = &e->xunmap;
1526 if((c = getclient(ev->window)))
1532 if(dc.drawable != 0)
1533 XFreePixmap(dpy, dc.drawable);
1534 dc.drawable = XCreatePixmap(dpy, root, ww, bh, DefaultDepth(dpy, screen));
1535 XMoveResizeWindow(dpy, barwin, wx, by, ww, bh);
1542 XineramaScreenInfo *info = NULL;
1544 /* window area geometry */
1545 if(XineramaIsActive(dpy) && (info = XineramaQueryScreens(dpy, &n))) {
1550 if(XQueryPointer(dpy, root, &dummy, &dummy, &x, &y, &di, &di, &dui))
1551 for(i = 0; i < n; i++)
1552 if(INRECT(x, y, info[i].x_org, info[i].y_org, info[i].width, info[i].height))
1556 wy = showbar && topbar ? info[i].y_org + bh : info[i].y_org;
1558 wh = showbar ? info[i].height - bh : info[i].height;
1565 wy = showbar && topbar ? sy + bh : sy;
1567 wh = showbar ? sh - bh : sh;
1571 by = showbar ? (topbar ? wy - bh : wy + wh) : -bh;
1575 updatenumlockmask(void) {
1577 XModifierKeymap *modmap;
1580 modmap = XGetModifierMapping(dpy);
1581 for(i = 0; i < 8; i++)
1582 for(j = 0; j < modmap->max_keypermod; j++)
1583 if(modmap->modifiermap[i * modmap->max_keypermod + j] == XKeysymToKeycode(dpy, XK_Num_Lock))
1584 numlockmask = (1 << i);
1585 XFreeModifiermap(modmap);
1589 updatesizehints(Client *c) {
1593 if(!XGetWMNormalHints(dpy, c->win, &size, &msize))
1594 /* size is uninitialized, ensure that size.flags aren't used */
1596 if(size.flags & PBaseSize) {
1597 c->basew = size.base_width;
1598 c->baseh = size.base_height;
1600 else if(size.flags & PMinSize) {
1601 c->basew = size.min_width;
1602 c->baseh = size.min_height;
1605 c->basew = c->baseh = 0;
1606 if(size.flags & PResizeInc) {
1607 c->incw = size.width_inc;
1608 c->inch = size.height_inc;
1611 c->incw = c->inch = 0;
1612 if(size.flags & PMaxSize) {
1613 c->maxw = size.max_width;
1614 c->maxh = size.max_height;
1617 c->maxw = c->maxh = 0;
1618 if(size.flags & PMinSize) {
1619 c->minw = size.min_width;
1620 c->minh = size.min_height;
1622 else if(size.flags & PBaseSize) {
1623 c->minw = size.base_width;
1624 c->minh = size.base_height;
1627 c->minw = c->minh = 0;
1628 if(size.flags & PAspect) {
1629 c->mina = (float)size.min_aspect.y / (float)size.min_aspect.x;
1630 c->maxa = (float)size.max_aspect.x / (float)size.max_aspect.y;
1633 c->maxa = c->mina = 0.0;
1634 c->isfixed = (c->maxw && c->minw && c->maxh && c->minh
1635 && c->maxw == c->minw && c->maxh == c->minh);
1639 updatetitle(Client *c) {
1640 if(!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
1641 gettextprop(c->win, XA_WM_NAME, c->name, sizeof c->name);
1645 updatewmhints(Client *c) {
1648 if((wmh = XGetWMHints(dpy, c->win))) {
1649 if(ISVISIBLE(c) && wmh->flags & XUrgencyHint) {
1650 wmh->flags &= ~XUrgencyHint;
1651 XSetWMHints(dpy, c->win, wmh);
1654 c->isurgent = (wmh->flags & XUrgencyHint) ? True : False;
1661 view(const Arg *arg) {
1662 if((arg->ui & TAGMASK) == tagset[seltags])
1664 seltags ^= 1; /* toggle sel tagset */
1665 if(arg->ui & TAGMASK)
1666 tagset[seltags] = arg->ui & TAGMASK;
1671 /* There's no way to check accesses to destroyed windows, thus those cases are
1672 * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
1673 * default error handler, which may call exit. */
1675 xerror(Display *dpy, XErrorEvent *ee) {
1676 if(ee->error_code == BadWindow
1677 || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1678 || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1679 || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1680 || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1681 || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1682 || (ee->request_code == X_GrabButton && ee->error_code == BadAccess)
1683 || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1684 || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1686 fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1687 ee->request_code, ee->error_code);
1688 return xerrorxlib(dpy, ee); /* may call exit */
1692 xerrordummy(Display *dpy, XErrorEvent *ee) {
1696 /* Startup Error handler to check if another window manager
1697 * is already running. */
1699 xerrorstart(Display *dpy, XErrorEvent *ee) {
1705 zoom(const Arg *arg) {
1708 if(!lt[sellt]->arrange || lt[sellt]->arrange == monocle || (sel && sel->isfloating))
1710 if(c == nexttiled(clients))
1711 if(!c || !(c = nexttiled(c->next)))
1720 main(int argc, char *argv[]) {
1721 if(argc == 2 && !strcmp("-v", argv[1]))
1722 die("dwm-"VERSION", © 2006-2008 dwm engineers, see LICENSE for details\n");
1724 die("usage: dwm [-v]\n");
1726 if(!setlocale(LC_CTYPE, "") || !XSupportsLocale())
1727 fprintf(stderr, "warning: no locale support\n");
1729 if(!(dpy = XOpenDisplay(0)))
1730 die("dwm: cannot open display\n");