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 TAGMASK ((int)((1LL << LENGTH(tags)) - 1))
57 #define TEXTW(x) (textnw(x, strlen(x)) + dc.font.height)
60 enum { CurNormal, CurResize, CurMove, CurLast }; /* cursor */
61 enum { ColBorder, ColFG, ColBG, ColLast }; /* color */
62 enum { NetSupported, NetWMName, NetLast }; /* EWMH atoms */
63 enum { WMProtocols, WMDelete, WMName, WMState, WMLast };/* default atoms */
64 enum { ClkTagBar, ClkLtSymbol, ClkStatusText, ClkWinTitle,
65 ClkClientWin, ClkRootWin, ClkLast }; /* clicks */
78 void (*func)(const Arg *arg);
82 typedef struct Client Client;
87 int basew, baseh, incw, inch, maxw, maxh, minw, minh;
90 Bool isfixed, isfloating, isurgent;
98 unsigned long norm[ColLast];
99 unsigned long sel[ColLast];
109 } DC; /* draw context */
114 void (*func)(const Arg *);
120 void (*arrange)(void);
125 const char *instance;
131 /* function declarations */
132 static void applyrules(Client *c);
133 static void arrange(void);
134 static void attach(Client *c);
135 static void attachstack(Client *c);
136 static void buttonpress(XEvent *e);
137 static void checkotherwm(void);
138 static void cleanup(void);
139 static void clearurgent(void);
140 static void configure(Client *c);
141 static void configurenotify(XEvent *e);
142 static void configurerequest(XEvent *e);
143 static void destroynotify(XEvent *e);
144 static void detach(Client *c);
145 static void detachstack(Client *c);
146 static void die(const char *errstr, ...);
147 static void drawbar(void);
148 static void drawsquare(Bool filled, Bool empty, Bool invert, unsigned long col[ColLast]);
149 static void drawtext(const char *text, unsigned long col[ColLast], Bool invert);
150 static void enternotify(XEvent *e);
151 static void expose(XEvent *e);
152 static void focus(Client *c);
153 static void focusin(XEvent *e);
154 static void focusstack(const Arg *arg);
155 static Client *getclient(Window w);
156 static unsigned long getcolor(const char *colstr);
157 static long getstate(Window w);
158 static Bool gettextprop(Window w, Atom atom, char *text, unsigned int size);
159 static void grabbuttons(Client *c, Bool focused);
160 static void grabkeys(void);
161 static void initfont(const char *fontstr);
162 static Bool isprotodel(Client *c);
163 static void keypress(XEvent *e);
164 static void killclient(const Arg *arg);
165 static void manage(Window w, XWindowAttributes *wa);
166 static void mappingnotify(XEvent *e);
167 static void maprequest(XEvent *e);
168 static void monocle(void);
169 static void movemouse(const Arg *arg);
170 static Client *nexttiled(Client *c);
171 static void propertynotify(XEvent *e);
172 static void quit(const Arg *arg);
173 static void resize(Client *c, int x, int y, int w, int h, Bool sizehints);
174 static void resizemouse(const Arg *arg);
175 static void restack(void);
176 static void run(void);
177 static void scan(void);
178 static void setclientstate(Client *c, long state);
179 static void setlayout(const Arg *arg);
180 static void setmfact(const Arg *arg);
181 static void setup(void);
182 static void spawn(const Arg *arg);
183 static void tag(const Arg *arg);
184 static int textnw(const char *text, unsigned int len);
185 static void tile(void);
186 static void togglebar(const Arg *arg);
187 static void togglefloating(const Arg *arg);
188 static void toggletag(const Arg *arg);
189 static void toggleview(const Arg *arg);
190 static void unmanage(Client *c);
191 static void unmapnotify(XEvent *e);
192 static void updatebar(void);
193 static void updategeom(void);
194 static void updatenumlockmask(void);
195 static void updatesizehints(Client *c);
196 static void updatetitle(Client *c);
197 static void updatewmhints(Client *c);
198 static void view(const Arg *arg);
199 static int xerror(Display *dpy, XErrorEvent *ee);
200 static int xerrordummy(Display *dpy, XErrorEvent *ee);
201 static int xerrorstart(Display *dpy, XErrorEvent *ee);
202 static void zoom(const Arg *arg);
205 static char stext[256];
207 static int sx, sy, sw, sh; /* X display screen geometry x, y, width, height */
208 static int by, bh, blw; /* bar geometry y, height and layout symbol width */
209 static int wx, wy, ww, wh; /* window area geometry x, y, width, height, bar excluded */
210 static unsigned int seltags = 0, sellt = 0;
211 static int (*xerrorxlib)(Display *, XErrorEvent *);
212 static unsigned int numlockmask = 0;
213 static void (*handler[LASTEvent]) (XEvent *) = {
214 [ButtonPress] = buttonpress,
215 [ConfigureRequest] = configurerequest,
216 [ConfigureNotify] = configurenotify,
217 [DestroyNotify] = destroynotify,
218 [EnterNotify] = enternotify,
221 [KeyPress] = keypress,
222 [MappingNotify] = mappingnotify,
223 [MapRequest] = maprequest,
224 [PropertyNotify] = propertynotify,
225 [UnmapNotify] = unmapnotify
227 static Atom wmatom[WMLast], netatom[NetLast];
229 static Bool running = True;
230 static unsigned int tagset[] = {1, 1}; /* after start, first tag is selected */
231 static Client *clients = NULL;
232 static Client *sel = NULL;
233 static Client *stack = NULL;
234 static Cursor cursor[CurLast];
237 static Layout *lt[] = { NULL, NULL };
238 static Window root, barwin;
239 /* configuration, allows nested code to access above variables */
242 /* compile-time check if all tags fit into an unsigned int bit array. */
243 struct NumTags { char limitexceeded[sizeof(unsigned int) * 8 < LENGTH(tags) ? -1 : 1]; };
245 /* function implementations */
247 applyrules(Client *c) {
250 XClassHint ch = { 0 };
253 XGetClassHint(dpy, c->win, &ch);
254 for(i = 0; i < LENGTH(rules); i++) {
256 if((!r->title || strstr(c->name, r->title))
257 && (!r->class || (ch.res_class && strstr(ch.res_class, r->class)))
258 && (!r->instance || (ch.res_name && strstr(ch.res_name, r->instance)))) {
259 c->isfloating = r->isfloating;
260 c->tags |= r->tags & TAGMASK;
268 c->tags = tagset[seltags];
275 for(c = clients; c; c = c->next)
277 XMoveWindow(dpy, c->win, c->x, c->y);
278 if(!lt[sellt]->arrange || c->isfloating)
279 resize(c, c->x, c->y, c->w, c->h, True);
282 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
286 if(lt[sellt]->arrange)
287 lt[sellt]->arrange();
298 attachstack(Client *c) {
304 buttonpress(XEvent *e) {
305 unsigned int i, x, click;
308 XButtonPressedEvent *ev = &e->xbutton;
311 if(ev->window == barwin) {
313 do x += TEXTW(tags[i]); while(ev->x >= x && ++i < LENGTH(tags));
314 if(i < LENGTH(tags)) {
318 else if(ev->x < x + blw)
320 else if(ev->x > wx + ww - TEXTW(stext))
321 click = ClkStatusText;
325 else if((c = getclient(ev->window))) {
327 click = ClkClientWin;
330 for(i = 0; i < LENGTH(buttons); i++)
331 if(click == buttons[i].click && buttons[i].func && buttons[i].button == ev->button
332 && CLEANMASK(buttons[i].mask) == CLEANMASK(ev->state))
333 buttons[i].func(click == ClkTagBar ? &arg : &buttons[i].arg);
339 XSetErrorHandler(xerrorstart);
341 /* this causes an error if some other window manager is running */
342 XSelectInput(dpy, DefaultRootWindow(dpy), SubstructureRedirectMask);
345 die("dwm: another window manager is already running\n");
346 XSetErrorHandler(NULL);
347 xerrorxlib = XSetErrorHandler(xerror);
354 Layout foo = { "", NULL };
362 XFreeFontSet(dpy, dc.font.set);
364 XFreeFont(dpy, dc.font.xfont);
365 XUngrabKey(dpy, AnyKey, AnyModifier, root);
366 XFreePixmap(dpy, dc.drawable);
368 XFreeCursor(dpy, cursor[CurNormal]);
369 XFreeCursor(dpy, cursor[CurResize]);
370 XFreeCursor(dpy, cursor[CurMove]);
371 XDestroyWindow(dpy, barwin);
373 XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime);
381 for(c = clients; c; c = c->next)
382 if(ISVISIBLE(c) && c->isurgent) {
384 if (!(wmh = XGetWMHints(dpy, c->win)))
387 wmh->flags &= ~XUrgencyHint;
388 XSetWMHints(dpy, c->win, wmh);
394 configure(Client *c) {
397 ce.type = ConfigureNotify;
405 ce.border_width = c->bw;
407 ce.override_redirect = False;
408 XSendEvent(dpy, c->win, False, StructureNotifyMask, (XEvent *)&ce);
412 configurenotify(XEvent *e) {
413 XConfigureEvent *ev = &e->xconfigure;
415 if(ev->window == root && (ev->width != sw || ev->height != sh)) {
425 configurerequest(XEvent *e) {
427 XConfigureRequestEvent *ev = &e->xconfigurerequest;
430 if((c = getclient(ev->window))) {
431 if(ev->value_mask & CWBorderWidth)
432 c->bw = ev->border_width;
433 else if(c->isfloating || !lt[sellt]->arrange) {
434 if(ev->value_mask & CWX)
436 if(ev->value_mask & CWY)
438 if(ev->value_mask & CWWidth)
440 if(ev->value_mask & CWHeight)
442 if((c->x - sx + c->w) > sw && c->isfloating)
443 c->x = sx + (sw / 2 - c->w / 2); /* center in x direction */
444 if((c->y - sy + c->h) > sh && c->isfloating)
445 c->y = sy + (sh / 2 - c->h / 2); /* center in y direction */
446 if((ev->value_mask & (CWX|CWY)) && !(ev->value_mask & (CWWidth|CWHeight)))
449 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h);
457 wc.width = ev->width;
458 wc.height = ev->height;
459 wc.border_width = ev->border_width;
460 wc.sibling = ev->above;
461 wc.stack_mode = ev->detail;
462 XConfigureWindow(dpy, ev->window, ev->value_mask, &wc);
468 destroynotify(XEvent *e) {
470 XDestroyWindowEvent *ev = &e->xdestroywindow;
472 if((c = getclient(ev->window)))
480 for(tc = &clients; *tc && *tc != c; tc = &(*tc)->next);
485 detachstack(Client *c) {
488 for(tc = &stack; *tc && *tc != c; tc = &(*tc)->snext);
493 die(const char *errstr, ...) {
496 va_start(ap, errstr);
497 vfprintf(stderr, errstr, ap);
505 unsigned int i, occ = 0, urg = 0;
509 for(c = clients; c; c = c->next) {
516 for(i = 0; i < LENGTH(tags); i++) {
517 dc.w = TEXTW(tags[i]);
518 col = tagset[seltags] & 1 << i ? dc.sel : dc.norm;
519 drawtext(tags[i], col, urg & 1 << i);
520 drawsquare(sel && sel->tags & 1 << i, occ & 1 << i, urg & 1 << i, col);
525 drawtext(lt[sellt]->symbol, dc.norm, False);
536 drawtext(stext, dc.norm, False);
537 if((dc.w = dc.x - x) > bh) {
540 drawtext(sel->name, dc.sel, False);
541 drawsquare(sel->isfixed, sel->isfloating, False, dc.sel);
544 drawtext(NULL, dc.norm, False);
546 XCopyArea(dpy, dc.drawable, barwin, dc.gc, 0, 0, ww, bh, 0, 0);
551 drawsquare(Bool filled, Bool empty, Bool invert, unsigned long col[ColLast]) {
554 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
556 gcv.foreground = col[invert ? ColBG : ColFG];
557 XChangeGC(dpy, dc.gc, GCForeground, &gcv);
558 x = (dc.font.ascent + dc.font.descent + 2) / 4;
562 r.width = r.height = x + 1;
563 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
566 r.width = r.height = x;
567 XDrawRectangles(dpy, dc.drawable, dc.gc, &r, 1);
572 drawtext(const char *text, unsigned long col[ColLast], Bool invert) {
574 int i, x, y, h, len, olen;
575 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
577 XSetForeground(dpy, dc.gc, col[invert ? ColFG : ColBG]);
578 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
582 h = dc.font.ascent + dc.font.descent;
583 y = dc.y + (dc.h / 2) - (h / 2) + dc.font.ascent;
585 /* shorten text if necessary */
586 for(len = MIN(olen, sizeof buf); len && textnw(text, len) > dc.w - h; len--);
589 memcpy(buf, text, len);
591 for(i = len; i && i > len - 3; buf[--i] = '.');
592 XSetForeground(dpy, dc.gc, col[invert ? ColBG : ColFG]);
594 XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
596 XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
600 enternotify(XEvent *e) {
602 XCrossingEvent *ev = &e->xcrossing;
604 if((ev->mode != NotifyNormal || ev->detail == NotifyInferior) && ev->window != root)
606 if((c = getclient(ev->window)))
614 XExposeEvent *ev = &e->xexpose;
616 if(ev->count == 0 && (ev->window == barwin))
622 if(!c || !ISVISIBLE(c))
623 for(c = stack; c && !ISVISIBLE(c); c = c->snext);
624 if(sel && sel != c) {
625 grabbuttons(sel, False);
626 XSetWindowBorder(dpy, sel->win, dc.norm[ColBorder]);
631 grabbuttons(c, True);
632 XSetWindowBorder(dpy, c->win, dc.sel[ColBorder]);
633 XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
636 XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
642 focusin(XEvent *e) { /* there are some broken focus acquiring clients */
643 XFocusChangeEvent *ev = &e->xfocus;
645 if(sel && ev->window != sel->win)
646 XSetInputFocus(dpy, sel->win, RevertToPointerRoot, CurrentTime);
650 focusstack(const Arg *arg) {
651 Client *c = NULL, *i;
656 for(c = sel->next; c && !ISVISIBLE(c); c = c->next);
658 for(c = clients; c && !ISVISIBLE(c); c = c->next);
661 for(i = clients; i != sel; i = i->next)
665 for(; i; i = i->next)
676 getclient(Window w) {
679 for(c = clients; c && c->win != w; c = c->next);
684 getcolor(const char *colstr) {
685 Colormap cmap = DefaultColormap(dpy, screen);
688 if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
689 die("error, cannot allocate color '%s'\n", colstr);
697 unsigned char *p = NULL;
698 unsigned long n, extra;
701 status = XGetWindowProperty(dpy, w, wmatom[WMState], 0L, 2L, False, wmatom[WMState],
702 &real, &format, &n, &extra, (unsigned char **)&p);
703 if(status != Success)
712 gettextprop(Window w, Atom atom, char *text, unsigned int size) {
717 if(!text || size == 0)
720 XGetTextProperty(dpy, w, &name, atom);
723 if(name.encoding == XA_STRING)
724 strncpy(text, (char *)name.value, size - 1);
726 if(XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success
728 strncpy(text, *list, size - 1);
729 XFreeStringList(list);
732 text[size - 1] = '\0';
738 grabbuttons(Client *c, Bool focused) {
742 unsigned int modifiers[] = { 0, LockMask, numlockmask, numlockmask|LockMask };
743 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
745 for(i = 0; i < LENGTH(buttons); i++)
746 if(buttons[i].click == ClkClientWin)
747 for(j = 0; j < LENGTH(modifiers); j++)
748 XGrabButton(dpy, buttons[i].button, buttons[i].mask | modifiers[j], c->win, False, BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
750 XGrabButton(dpy, AnyButton, AnyModifier, c->win, False,
751 BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
760 unsigned int modifiers[] = { 0, LockMask, numlockmask, numlockmask|LockMask };
763 XUngrabKey(dpy, AnyKey, AnyModifier, root);
764 for(i = 0; i < LENGTH(keys); i++) {
765 code = XKeysymToKeycode(dpy, keys[i].keysym);
766 for(j = 0; j < LENGTH(modifiers); j++)
767 XGrabKey(dpy, code, keys[i].mod | modifiers[j], root, True,
768 GrabModeAsync, GrabModeAsync);
774 initfont(const char *fontstr) {
775 char *def, **missing;
779 dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
782 fprintf(stderr, "dwm: missing fontset: %s\n", missing[n]);
783 XFreeStringList(missing);
786 XFontSetExtents *font_extents;
787 XFontStruct **xfonts;
789 dc.font.ascent = dc.font.descent = 0;
790 font_extents = XExtentsOfFontSet(dc.font.set);
791 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
792 for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
793 dc.font.ascent = MAX(dc.font.ascent, (*xfonts)->ascent);
794 dc.font.descent = MAX(dc.font.descent,(*xfonts)->descent);
800 XFreeFont(dpy, dc.font.xfont);
801 dc.font.xfont = NULL;
802 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr))
803 && !(dc.font.xfont = XLoadQueryFont(dpy, "fixed")))
804 die("error, cannot load font: '%s'\n", fontstr);
805 dc.font.ascent = dc.font.xfont->ascent;
806 dc.font.descent = dc.font.xfont->descent;
808 dc.font.height = dc.font.ascent + dc.font.descent;
812 isprotodel(Client *c) {
817 if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
818 for(i = 0; !ret && i < n; i++)
819 if(protocols[i] == wmatom[WMDelete])
827 keypress(XEvent *e) {
833 keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
834 for(i = 0; i < LENGTH(keys); i++)
835 if(keysym == keys[i].keysym
836 && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state)
838 keys[i].func(&(keys[i].arg));
842 killclient(const Arg *arg) {
847 if(isprotodel(sel)) {
848 ev.type = ClientMessage;
849 ev.xclient.window = sel->win;
850 ev.xclient.message_type = wmatom[WMProtocols];
851 ev.xclient.format = 32;
852 ev.xclient.data.l[0] = wmatom[WMDelete];
853 ev.xclient.data.l[1] = CurrentTime;
854 XSendEvent(dpy, sel->win, False, NoEventMask, &ev);
857 XKillClient(dpy, sel->win);
861 manage(Window w, XWindowAttributes *wa) {
862 Client *c, *t = NULL;
866 if(!(c = calloc(1, sizeof(Client))))
867 die("fatal: could not calloc() %u bytes\n", sizeof(Client));
875 c->oldbw = wa->border_width;
876 if(c->w == sw && c->h == sh) {
882 if(c->x + c->w + 2 * c->bw > sx + sw)
883 c->x = sx + sw - c->w - 2 * c->bw;
884 if(c->y + c->h + 2 * c->bw > sy + sh)
885 c->y = sy + sh - c->h - 2 * c->bw;
886 c->x = MAX(c->x, sx);
887 /* only fix client y-offset, if the client center might cover the bar */
888 c->y = MAX(c->y, ((by == 0) && (c->x + (c->w / 2) >= wx) && (c->x + (c->w / 2) < wx + ww)) ? bh : sy);
892 wc.border_width = c->bw;
893 XConfigureWindow(dpy, w, CWBorderWidth, &wc);
894 XSetWindowBorder(dpy, w, dc.norm[ColBorder]);
895 configure(c); /* propagates border_width, if size doesn't change */
897 XSelectInput(dpy, w, EnterWindowMask|FocusChangeMask|PropertyChangeMask|StructureNotifyMask);
898 grabbuttons(c, False);
900 if(XGetTransientForHint(dpy, w, &trans))
901 t = getclient(trans);
907 c->isfloating = trans != None || c->isfixed;
909 XRaiseWindow(dpy, c->win);
912 XMoveResizeWindow(dpy, c->win, c->x + 2 * sw, c->y, c->w, c->h); /* some windows require this */
913 XMapWindow(dpy, c->win);
914 setclientstate(c, NormalState);
919 mappingnotify(XEvent *e) {
920 XMappingEvent *ev = &e->xmapping;
922 XRefreshKeyboardMapping(ev);
923 if(ev->request == MappingKeyboard)
928 maprequest(XEvent *e) {
929 static XWindowAttributes wa;
930 XMapRequestEvent *ev = &e->xmaprequest;
932 if(!XGetWindowAttributes(dpy, ev->window, &wa))
934 if(wa.override_redirect)
936 if(!getclient(ev->window))
937 manage(ev->window, &wa);
944 for(c = nexttiled(clients); c; c = nexttiled(c->next))
945 resize(c, wx, wy, ww - 2 * c->bw, wh - 2 * c->bw, resizehints);
949 movemouse(const Arg *arg) {
950 int x, y, ocx, ocy, di, nx, ny;
961 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
962 None, cursor[CurMove], CurrentTime) != GrabSuccess)
964 XQueryPointer(dpy, root, &dummy, &dummy, &x, &y, &di, &di, &dui);
966 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
968 case ConfigureRequest:
971 handler[ev.type](&ev);
975 nx = ocx + (ev.xmotion.x - x);
976 ny = ocy + (ev.xmotion.y - y);
977 if(snap && nx >= wx && nx <= wx + ww
978 && ny >= wy && ny <= wy + wh) {
979 if(abs(wx - nx) < snap)
981 else if(abs((wx + ww) - (nx + c->w + 2 * c->bw)) < snap)
982 nx = wx + ww - c->w - 2 * c->bw;
983 if(abs(wy - ny) < snap)
985 else if(abs((wy + wh) - (ny + c->h + 2 * c->bw)) < snap)
986 ny = wy + wh - c->h - 2 * c->bw;
987 if(!c->isfloating && lt[sellt]->arrange && (abs(nx - c->x) > snap || abs(ny - c->y) > snap))
988 togglefloating(NULL);
990 if(!lt[sellt]->arrange || c->isfloating)
991 resize(c, nx, ny, c->w, c->h, False);
995 while(ev.type != ButtonRelease);
996 XUngrabPointer(dpy, CurrentTime);
1000 nexttiled(Client *c) {
1001 for(; c && (c->isfloating || !ISVISIBLE(c)); c = c->next);
1006 propertynotify(XEvent *e) {
1009 XPropertyEvent *ev = &e->xproperty;
1011 if(ev->state == PropertyDelete)
1012 return; /* ignore */
1013 if((c = getclient(ev->window))) {
1016 case XA_WM_TRANSIENT_FOR:
1017 XGetTransientForHint(dpy, c->win, &trans);
1018 if(!c->isfloating && (c->isfloating = (getclient(trans) != NULL)))
1021 case XA_WM_NORMAL_HINTS:
1029 if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
1038 quit(const Arg *arg) {
1039 readin = running = False;
1043 resize(Client *c, int x, int y, int w, int h, Bool sizehints) {
1047 /* see last two sentences in ICCCM 4.1.2.3 */
1048 Bool baseismin = c->basew == c->minw && c->baseh == c->minh;
1050 /* set minimum possible */
1054 if(!baseismin) { /* temporarily remove base dimensions */
1059 /* adjust for aspect limits */
1060 if(c->mina > 0 && c->maxa > 0) {
1061 if(c->maxa < (float)(w / h))
1063 else if(c->mina < (float)(h / w))
1067 if(baseismin) { /* increment calculation requires this */
1072 /* adjust for increment value */
1078 /* restore base dimensions */
1082 w = MAX(w, c->minw);
1083 h = MAX(h, c->minh);
1086 w = MIN(w, c->maxw);
1089 h = MIN(h, c->maxh);
1091 if(w <= 0 || h <= 0)
1094 x = sw - w - 2 * c->bw;
1096 y = sh - h - 2 * c->bw;
1097 if(x + w + 2 * c->bw < sx)
1099 if(y + h + 2 * c->bw < sy)
1105 if(c->x != x || c->y != y || c->w != w || c->h != h) {
1108 c->w = wc.width = w;
1109 c->h = wc.height = h;
1110 wc.border_width = c->bw;
1111 XConfigureWindow(dpy, c->win,
1112 CWX|CWY|CWWidth|CWHeight|CWBorderWidth, &wc);
1119 resizemouse(const Arg *arg) {
1130 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1131 None, cursor[CurResize], CurrentTime) != GrabSuccess)
1133 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->bw - 1, c->h + c->bw - 1);
1135 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
1137 case ConfigureRequest:
1140 handler[ev.type](&ev);
1144 nw = MAX(ev.xmotion.x - ocx - 2 * c->bw + 1, 1);
1145 nh = MAX(ev.xmotion.y - ocy - 2 * c->bw + 1, 1);
1147 if(snap && nw >= wx && nw <= wx + ww
1148 && nh >= wy && nh <= wy + wh) {
1149 if(!c->isfloating && lt[sellt]->arrange
1150 && (abs(nw - c->w) > snap || abs(nh - c->h) > snap))
1151 togglefloating(NULL);
1153 if(!lt[sellt]->arrange || c->isfloating)
1154 resize(c, c->x, c->y, nw, nh, True);
1158 while(ev.type != ButtonRelease);
1159 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->bw - 1, c->h + c->bw - 1);
1160 XUngrabPointer(dpy, CurrentTime);
1161 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1173 if(sel->isfloating || !lt[sellt]->arrange)
1174 XRaiseWindow(dpy, sel->win);
1175 if(lt[sellt]->arrange) {
1176 wc.stack_mode = Below;
1177 wc.sibling = barwin;
1178 for(c = stack; c; c = c->snext)
1179 if(!c->isfloating && ISVISIBLE(c)) {
1180 XConfigureWindow(dpy, c->win, CWSibling|CWStackMode, &wc);
1181 wc.sibling = c->win;
1185 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1191 char sbuf[sizeof stext];
1194 unsigned int len, offset;
1197 /* main event loop, also reads status text from stdin */
1199 xfd = ConnectionNumber(dpy);
1201 len = sizeof stext - 1;
1202 sbuf[len] = stext[len] = '\0'; /* 0-terminator is never touched */
1206 FD_SET(STDIN_FILENO, &rd);
1208 if(select(xfd + 1, &rd, NULL, NULL, NULL) == -1) {
1211 die("select failed\n");
1213 if(FD_ISSET(STDIN_FILENO, &rd)) {
1214 switch((r = read(STDIN_FILENO, sbuf + offset, len - offset))) {
1216 strncpy(stext, strerror(errno), len);
1220 strncpy(stext, "EOF", 4);
1224 for(p = sbuf + offset; r > 0; p++, r--, offset++)
1225 if(*p == '\n' || *p == '\0') {
1227 strncpy(stext, sbuf, len);
1228 p += r - 1; /* p is sbuf + offset + r - 1 */
1229 for(r = 0; *(p - r) && *(p - r) != '\n'; r++);
1232 memmove(sbuf, p - r + 1, r);
1239 while(XPending(dpy)) {
1240 XNextEvent(dpy, &ev);
1241 if(handler[ev.type])
1242 (handler[ev.type])(&ev); /* call handler */
1249 unsigned int i, num;
1250 Window d1, d2, *wins = NULL;
1251 XWindowAttributes wa;
1253 if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1254 for(i = 0; i < num; i++) {
1255 if(!XGetWindowAttributes(dpy, wins[i], &wa)
1256 || wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1258 if(wa.map_state == IsViewable || getstate(wins[i]) == IconicState)
1259 manage(wins[i], &wa);
1261 for(i = 0; i < num; i++) { /* now the transients */
1262 if(!XGetWindowAttributes(dpy, wins[i], &wa))
1264 if(XGetTransientForHint(dpy, wins[i], &d1)
1265 && (wa.map_state == IsViewable || getstate(wins[i]) == IconicState))
1266 manage(wins[i], &wa);
1274 setclientstate(Client *c, long state) {
1275 long data[] = {state, None};
1277 XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1278 PropModeReplace, (unsigned char *)data, 2);
1282 setlayout(const Arg *arg) {
1283 if(!arg || !arg->v || arg->v != lt[sellt])
1286 lt[sellt] = (Layout *)arg->v;
1293 /* arg > 1.0 will set mfact absolutly */
1295 setmfact(const Arg *arg) {
1298 if(!arg || !lt[sellt]->arrange)
1300 f = arg->f < 1.0 ? arg->f + mfact : arg->f - 1.0;
1301 if(f < 0.1 || f > 0.9)
1311 XSetWindowAttributes wa;
1314 screen = DefaultScreen(dpy);
1315 root = RootWindow(dpy, screen);
1319 sw = DisplayWidth(dpy, screen);
1320 sh = DisplayHeight(dpy, screen);
1321 bh = dc.h = dc.font.height + 2;
1322 lt[0] = &layouts[0];
1323 lt[1] = &layouts[1 % LENGTH(layouts)];
1327 wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1328 wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1329 wmatom[WMName] = XInternAtom(dpy, "WM_NAME", False);
1330 wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1331 netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1332 netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1335 wa.cursor = cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1336 cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1337 cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1339 /* init appearance */
1340 dc.norm[ColBorder] = getcolor(normbordercolor);
1341 dc.norm[ColBG] = getcolor(normbgcolor);
1342 dc.norm[ColFG] = getcolor(normfgcolor);
1343 dc.sel[ColBorder] = getcolor(selbordercolor);
1344 dc.sel[ColBG] = getcolor(selbgcolor);
1345 dc.sel[ColFG] = getcolor(selfgcolor);
1346 dc.drawable = XCreatePixmap(dpy, root, DisplayWidth(dpy, screen), bh, DefaultDepth(dpy, screen));
1347 dc.gc = XCreateGC(dpy, root, 0, 0);
1348 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
1350 XSetFont(dpy, dc.gc, dc.font.xfont->fid);
1353 for(blw = i = 0; LENGTH(layouts) > 1 && i < LENGTH(layouts); i++) {
1354 w = TEXTW(layouts[i].symbol);
1358 wa.override_redirect = 1;
1359 wa.background_pixmap = ParentRelative;
1360 wa.event_mask = ButtonPressMask|ExposureMask;
1362 barwin = XCreateWindow(dpy, root, wx, by, ww, bh, 0, DefaultDepth(dpy, screen),
1363 CopyFromParent, DefaultVisual(dpy, screen),
1364 CWOverrideRedirect|CWBackPixmap|CWEventMask, &wa);
1365 XDefineCursor(dpy, barwin, cursor[CurNormal]);
1366 XMapRaised(dpy, barwin);
1367 strcpy(stext, "dwm-"VERSION);
1370 /* EWMH support per view */
1371 XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1372 PropModeReplace, (unsigned char *) netatom, NetLast);
1374 /* select for events */
1375 wa.event_mask = SubstructureRedirectMask|SubstructureNotifyMask|ButtonPressMask
1376 |EnterWindowMask|LeaveWindowMask|StructureNotifyMask;
1377 XChangeWindowAttributes(dpy, root, CWEventMask|CWCursor, &wa);
1378 XSelectInput(dpy, root, wa.event_mask);
1384 spawn(const Arg *arg) {
1385 /* The double-fork construct avoids zombie processes and keeps the code
1386 * clean from stupid signal handlers. */
1390 close(ConnectionNumber(dpy));
1392 execvp(((char **)arg->v)[0], (char **)arg->v);
1393 fprintf(stderr, "dwm: execvp %s", ((char **)arg->v)[0]);
1402 tag(const Arg *arg) {
1403 if(sel && arg->ui & TAGMASK) {
1404 sel->tags = arg->ui & TAGMASK;
1410 textnw(const char *text, unsigned int len) {
1414 XmbTextExtents(dc.font.set, text, len, NULL, &r);
1417 return XTextWidth(dc.font.xfont, text, len);
1426 for(n = 0, c = nexttiled(clients); c; c = nexttiled(c->next), n++);
1431 c = nexttiled(clients);
1433 resize(c, wx, wy, (n == 1 ? ww : mw) - 2 * c->bw, wh - 2 * c->bw, resizehints);
1439 x = (wx + mw > c->x + c->w) ? c->x + c->w + 2 * c->bw : wx + mw;
1441 w = (wx + mw > c->x + c->w) ? wx + ww - x : ww - mw;
1446 for(i = 0, c = nexttiled(c->next); c; c = nexttiled(c->next), i++) {
1447 resize(c, x, y, w - 2 * c->bw, /* remainder */ ((i + 1 == n)
1448 ? (wy + wh) - y : h) - 2 * c->bw, resizehints);
1450 y = c->y + c->h + 2 * c->bw;
1455 togglebar(const Arg *arg) {
1463 togglefloating(const Arg *arg) {
1466 sel->isfloating = !sel->isfloating || sel->isfixed;
1468 resize(sel, sel->x, sel->y, sel->w, sel->h, True);
1473 toggletag(const Arg *arg) {
1479 mask = sel->tags ^ (arg->ui & TAGMASK);
1487 toggleview(const Arg *arg) {
1488 unsigned int mask = tagset[seltags] ^ (arg->ui & TAGMASK);
1491 tagset[seltags] = mask;
1498 unmanage(Client *c) {
1501 wc.border_width = c->oldbw;
1502 /* The server grab construct avoids race conditions. */
1504 XSetErrorHandler(xerrordummy);
1505 XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
1510 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1511 setclientstate(c, WithdrawnState);
1514 XSetErrorHandler(xerror);
1520 unmapnotify(XEvent *e) {
1522 XUnmapEvent *ev = &e->xunmap;
1524 if((c = getclient(ev->window)))
1530 if(dc.drawable != 0)
1531 XFreePixmap(dpy, dc.drawable);
1532 dc.drawable = XCreatePixmap(dpy, root, ww, bh, DefaultDepth(dpy, screen));
1533 XMoveResizeWindow(dpy, barwin, wx, by, ww, bh);
1540 XineramaScreenInfo *info = NULL;
1542 /* window area geometry */
1543 if(XineramaIsActive(dpy) && (info = XineramaQueryScreens(dpy, &n))) {
1548 if(XQueryPointer(dpy, root, &dummy, &dummy, &x, &y, &di, &di, &dui))
1549 for(i = 0; i < n; i++)
1550 if(INRECT(x, y, info[i].x_org, info[i].y_org, info[i].width, info[i].height))
1554 wy = showbar && topbar ? info[i].y_org + bh : info[i].y_org;
1556 wh = showbar ? info[i].height - bh : info[i].height;
1563 wy = showbar && topbar ? sy + bh : sy;
1565 wh = showbar ? sh - bh : sh;
1569 by = showbar ? (topbar ? wy - bh : wy + wh) : -bh;
1573 updatenumlockmask(void) {
1575 XModifierKeymap *modmap;
1578 modmap = XGetModifierMapping(dpy);
1579 for(i = 0; i < 8; i++)
1580 for(j = 0; j < modmap->max_keypermod; j++)
1581 if(modmap->modifiermap[i * modmap->max_keypermod + j] == XKeysymToKeycode(dpy, XK_Num_Lock))
1582 numlockmask = (1 << i);
1583 XFreeModifiermap(modmap);
1587 updatesizehints(Client *c) {
1591 XGetWMNormalHints(dpy, c->win, &size, &msize);
1592 if(size.flags & PBaseSize) {
1593 c->basew = size.base_width;
1594 c->baseh = size.base_height;
1596 else if(size.flags & PMinSize) {
1597 c->basew = size.min_width;
1598 c->baseh = size.min_height;
1601 c->basew = c->baseh = 0;
1602 if(size.flags & PResizeInc) {
1603 c->incw = size.width_inc;
1604 c->inch = size.height_inc;
1607 c->incw = c->inch = 0;
1608 if(size.flags & PMaxSize) {
1609 c->maxw = size.max_width;
1610 c->maxh = size.max_height;
1613 c->maxw = c->maxh = 0;
1614 if(size.flags & PMinSize) {
1615 c->minw = size.min_width;
1616 c->minh = size.min_height;
1618 else if(size.flags & PBaseSize) {
1619 c->minw = size.base_width;
1620 c->minh = size.base_height;
1623 c->minw = c->minh = 0;
1624 if(size.flags & PAspect) {
1625 c->mina = (float)size.min_aspect.y / (float)size.min_aspect.x;
1626 c->maxa = (float)size.max_aspect.x / (float)size.max_aspect.y;
1629 c->maxa = c->mina = 0.0;
1630 c->isfixed = (c->maxw && c->minw && c->maxh && c->minh
1631 && c->maxw == c->minw && c->maxh == c->minh);
1635 updatetitle(Client *c) {
1636 if(!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
1637 gettextprop(c->win, wmatom[WMName], c->name, sizeof c->name);
1641 updatewmhints(Client *c) {
1644 if((wmh = XGetWMHints(dpy, c->win))) {
1645 if(ISVISIBLE(c) && wmh->flags & XUrgencyHint) {
1646 wmh->flags &= ~XUrgencyHint;
1647 XSetWMHints(dpy, c->win, wmh);
1650 c->isurgent = (wmh->flags & XUrgencyHint) ? True : False;
1657 view(const Arg *arg) {
1658 if((arg->ui & TAGMASK) == tagset[seltags])
1660 seltags ^= 1; /* toggle sel tagset */
1661 if(arg->ui & TAGMASK)
1662 tagset[seltags] = arg->ui & TAGMASK;
1667 /* There's no way to check accesses to destroyed windows, thus those cases are
1668 * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
1669 * default error handler, which may call exit. */
1671 xerror(Display *dpy, XErrorEvent *ee) {
1672 if(ee->error_code == BadWindow
1673 || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1674 || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1675 || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1676 || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1677 || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1678 || (ee->request_code == X_GrabButton && ee->error_code == BadAccess)
1679 || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1680 || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1682 fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1683 ee->request_code, ee->error_code);
1684 return xerrorxlib(dpy, ee); /* may call exit */
1688 xerrordummy(Display *dpy, XErrorEvent *ee) {
1692 /* Startup Error handler to check if another window manager
1693 * is already running. */
1695 xerrorstart(Display *dpy, XErrorEvent *ee) {
1701 zoom(const Arg *arg) {
1704 if(!lt[sellt]->arrange || lt[sellt]->arrange == monocle || (sel && sel->isfloating))
1706 if(c == nexttiled(clients))
1707 if(!c || !(c = nexttiled(c->next)))
1716 main(int argc, char *argv[]) {
1717 if(argc == 2 && !strcmp("-v", argv[1]))
1718 die("dwm-"VERSION", © 2006-2008 dwm engineers, see LICENSE for details\n");
1720 die("usage: dwm [-v]\n");
1722 if(!setlocale(LC_CTYPE, "") || !XSupportsLocale())
1723 fprintf(stderr, "warning: no locale support\n");
1725 if(!(dpy = XOpenDisplay(0)))
1726 die("dwm: cannot open display\n");