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 * 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 WIDTH(x) ((x)->w + 2 * (x)->bw)
57 #define HEIGHT(x) ((x)->h + 2 * (x)->bw)
58 #define TAGMASK ((int)((1LL << LENGTH(tags)) - 1))
59 #define TEXTW(x) (textnw(x, strlen(x)) + dc.font.height)
62 enum { CurNormal, CurResize, CurMove, CurLast }; /* cursor */
63 enum { ColBorder, ColFG, ColBG, ColLast }; /* color */
64 enum { NetSupported, NetWMName, NetLast }; /* EWMH atoms */
65 enum { WMProtocols, WMDelete, WMState, WMLast }; /* default atoms */
66 enum { ClkTagBar, ClkLtSymbol, ClkStatusText, ClkWinTitle,
67 ClkClientWin, ClkRootWin, ClkLast }; /* clicks */
80 void (*func)(const Arg *arg);
84 typedef struct Client Client;
89 int basew, baseh, incw, inch, maxw, maxh, minw, minh;
92 Bool isfixed, isfloating, isurgent;
100 unsigned long norm[ColLast];
101 unsigned long sel[ColLast];
111 } DC; /* draw context */
116 void (*func)(const Arg *);
122 void (*arrange)(void);
127 const char *instance;
133 /* function declarations */
134 static void applyrules(Client *c);
135 static void arrange(void);
136 static void attach(Client *c);
137 static void attachstack(Client *c);
138 static void buttonpress(XEvent *e);
139 static void checkotherwm(void);
140 static void cleanup(void);
141 static void clearurgent(void);
142 static void configure(Client *c);
143 static void configurenotify(XEvent *e);
144 static void configurerequest(XEvent *e);
145 static void destroynotify(XEvent *e);
146 static void detach(Client *c);
147 static void detachstack(Client *c);
148 static void die(const char *errstr, ...);
149 static void drawbar(void);
150 static void drawsquare(Bool filled, Bool empty, Bool invert, unsigned long col[ColLast]);
151 static void drawtext(const char *text, unsigned long col[ColLast], Bool invert);
152 static void enternotify(XEvent *e);
153 static void expose(XEvent *e);
154 static void focus(Client *c);
155 static void focusin(XEvent *e);
156 static void focusstack(const Arg *arg);
157 static Client *getclient(Window w);
158 static unsigned long getcolor(const char *colstr);
159 static long getstate(Window w);
160 static Bool gettextprop(Window w, Atom atom, char *text, unsigned int size);
161 static void grabbuttons(Client *c, Bool focused);
162 static void grabkeys(void);
163 static void initfont(const char *fontstr);
164 static Bool isprotodel(Client *c);
165 static void keypress(XEvent *e);
166 static void killclient(const Arg *arg);
167 static void manage(Window w, XWindowAttributes *wa);
168 static void mappingnotify(XEvent *e);
169 static void maprequest(XEvent *e);
170 static void monocle(void);
171 static void movemouse(const Arg *arg);
172 static Client *nexttiled(Client *c);
173 static void propertynotify(XEvent *e);
174 static void quit(const Arg *arg);
175 static void resize(Client *c, int x, int y, int w, int h, Bool sizehints);
176 static void resizemouse(const Arg *arg);
177 static void restack(void);
178 static void run(void);
179 static void scan(void);
180 static void setclientstate(Client *c, long state);
181 static void setlayout(const Arg *arg);
182 static void setmfact(const Arg *arg);
183 static void setup(void);
184 static void showhide(Client *c);
185 static void sigchld(int signal);
186 static void spawn(const Arg *arg);
187 static void tag(const Arg *arg);
188 static int textnw(const char *text, unsigned int len);
189 static void tile(void);
190 static void togglebar(const Arg *arg);
191 static void togglefloating(const Arg *arg);
192 static void toggletag(const Arg *arg);
193 static void toggleview(const Arg *arg);
194 static void unmanage(Client *c);
195 static void unmapnotify(XEvent *e);
196 static void updatebar(void);
197 static void updategeom(void);
198 static void updatenumlockmask(void);
199 static void updatesizehints(Client *c);
200 static void updatetitle(Client *c);
201 static void updatewmhints(Client *c);
202 static void view(const Arg *arg);
203 static int xerror(Display *dpy, XErrorEvent *ee);
204 static int xerrordummy(Display *dpy, XErrorEvent *ee);
205 static int xerrorstart(Display *dpy, XErrorEvent *ee);
206 static void zoom(const Arg *arg);
209 static char stext[256];
211 static int sx, sy, sw, sh; /* X display screen geometry x, y, width, height */
212 static int by, bh, blw; /* bar geometry y, height and layout symbol width */
213 static int wx, wy, ww, wh; /* window area geometry x, y, width, height, bar excluded */
214 static unsigned int seltags = 0, sellt = 0;
215 static int (*xerrorxlib)(Display *, XErrorEvent *);
216 static unsigned int numlockmask = 0;
217 static void (*handler[LASTEvent]) (XEvent *) = {
218 [ButtonPress] = buttonpress,
219 [ConfigureRequest] = configurerequest,
220 [ConfigureNotify] = configurenotify,
221 [DestroyNotify] = destroynotify,
222 [EnterNotify] = enternotify,
225 [KeyPress] = keypress,
226 [MappingNotify] = mappingnotify,
227 [MapRequest] = maprequest,
228 [PropertyNotify] = propertynotify,
229 [UnmapNotify] = unmapnotify
231 static Atom wmatom[WMLast], netatom[NetLast];
233 static Bool running = True;
234 static Client *clients = NULL;
235 static Client *sel = NULL;
236 static Client *stack = NULL;
237 static Cursor cursor[CurLast];
240 static Layout *lt[] = { NULL, NULL };
241 static Window root, barwin;
242 /* configuration, allows nested code to access above variables */
245 /* compile-time check if all tags fit into an unsigned int bit array. */
246 struct NumTags { char limitexceeded[sizeof(unsigned int) * 8 < LENGTH(tags) ? -1 : 1]; };
248 /* function implementations */
250 applyrules(Client *c) {
253 XClassHint ch = { 0 };
256 if(XGetClassHint(dpy, c->win, &ch)) {
257 for(i = 0; i < LENGTH(rules); i++) {
259 if((!r->title || strstr(c->name, r->title))
260 && (!r->class || (ch.res_class && strstr(ch.res_class, r->class)))
261 && (!r->instance || (ch.res_name && strstr(ch.res_name, r->instance)))) {
262 c->isfloating = r->isfloating;
263 c->tags |= r->tags & TAGMASK;
272 c->tags = tagset[seltags];
279 if(lt[sellt]->arrange)
280 lt[sellt]->arrange();
291 attachstack(Client *c) {
297 buttonpress(XEvent *e) {
298 unsigned int i, x, click;
301 XButtonPressedEvent *ev = &e->xbutton;
304 if(ev->window == barwin) {
306 do x += TEXTW(tags[i]); while(ev->x >= x && ++i < LENGTH(tags));
307 if(i < LENGTH(tags)) {
311 else if(ev->x < x + blw)
313 else if(ev->x > wx + ww - TEXTW(stext))
314 click = ClkStatusText;
318 else if((c = getclient(ev->window))) {
320 click = ClkClientWin;
323 for(i = 0; i < LENGTH(buttons); i++)
324 if(click == buttons[i].click && buttons[i].func && buttons[i].button == ev->button
325 && CLEANMASK(buttons[i].mask) == CLEANMASK(ev->state))
326 buttons[i].func(click == ClkTagBar && buttons[i].arg.i == 0 ? &arg : &buttons[i].arg);
332 xerrorxlib = XSetErrorHandler(xerrorstart);
334 /* this causes an error if some other window manager is running */
335 XSelectInput(dpy, DefaultRootWindow(dpy), SubstructureRedirectMask);
338 die("dwm: another window manager is already running\n");
339 XSetErrorHandler(xerror);
346 Layout foo = { "", NULL };
354 XFreeFontSet(dpy, dc.font.set);
356 XFreeFont(dpy, dc.font.xfont);
357 XUngrabKey(dpy, AnyKey, AnyModifier, root);
358 XFreePixmap(dpy, dc.drawable);
360 XFreeCursor(dpy, cursor[CurNormal]);
361 XFreeCursor(dpy, cursor[CurResize]);
362 XFreeCursor(dpy, cursor[CurMove]);
363 XDestroyWindow(dpy, barwin);
365 XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime);
373 for(c = clients; c; c = c->next)
374 if(ISVISIBLE(c) && c->isurgent) {
376 if (!(wmh = XGetWMHints(dpy, c->win)))
379 wmh->flags &= ~XUrgencyHint;
380 XSetWMHints(dpy, c->win, wmh);
386 configure(Client *c) {
389 ce.type = ConfigureNotify;
397 ce.border_width = c->bw;
399 ce.override_redirect = False;
400 XSendEvent(dpy, c->win, False, StructureNotifyMask, (XEvent *)&ce);
404 configurenotify(XEvent *e) {
405 XConfigureEvent *ev = &e->xconfigure;
407 if(ev->window == root && (ev->width != sw || ev->height != sh)) {
417 configurerequest(XEvent *e) {
419 XConfigureRequestEvent *ev = &e->xconfigurerequest;
422 if((c = getclient(ev->window))) {
423 if(ev->value_mask & CWBorderWidth)
424 c->bw = ev->border_width;
425 else if(c->isfloating || !lt[sellt]->arrange) {
426 if(ev->value_mask & CWX)
428 if(ev->value_mask & CWY)
430 if(ev->value_mask & CWWidth)
432 if(ev->value_mask & CWHeight)
434 if((c->x - sx + c->w) > sw && c->isfloating)
435 c->x = sx + (sw / 2 - c->w / 2); /* center in x direction */
436 if((c->y - sy + c->h) > sh && c->isfloating)
437 c->y = sy + (sh / 2 - c->h / 2); /* center in y direction */
438 if((ev->value_mask & (CWX|CWY)) && !(ev->value_mask & (CWWidth|CWHeight)))
441 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h);
449 wc.width = ev->width;
450 wc.height = ev->height;
451 wc.border_width = ev->border_width;
452 wc.sibling = ev->above;
453 wc.stack_mode = ev->detail;
454 XConfigureWindow(dpy, ev->window, ev->value_mask, &wc);
460 destroynotify(XEvent *e) {
462 XDestroyWindowEvent *ev = &e->xdestroywindow;
464 if((c = getclient(ev->window)))
472 for(tc = &clients; *tc && *tc != c; tc = &(*tc)->next);
477 detachstack(Client *c) {
480 for(tc = &stack; *tc && *tc != c; tc = &(*tc)->snext);
485 die(const char *errstr, ...) {
488 va_start(ap, errstr);
489 vfprintf(stderr, errstr, ap);
497 unsigned int i, occ = 0, urg = 0;
501 for(c = clients; c; c = c->next) {
508 for(i = 0; i < LENGTH(tags); i++) {
509 dc.w = TEXTW(tags[i]);
510 col = tagset[seltags] & 1 << i ? dc.sel : dc.norm;
511 drawtext(tags[i], col, urg & 1 << i);
512 drawsquare(sel && sel->tags & 1 << i, occ & 1 << i, urg & 1 << i, col);
517 drawtext(lt[sellt]->symbol, dc.norm, False);
528 drawtext(stext, dc.norm, False);
529 if((dc.w = dc.x - x) > bh) {
532 drawtext(sel->name, dc.sel, False);
533 drawsquare(sel->isfixed, sel->isfloating, False, dc.sel);
536 drawtext(NULL, dc.norm, False);
538 XCopyArea(dpy, dc.drawable, barwin, dc.gc, 0, 0, ww, bh, 0, 0);
543 drawsquare(Bool filled, Bool empty, Bool invert, unsigned long col[ColLast]) {
546 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
548 gcv.foreground = col[invert ? ColBG : ColFG];
549 XChangeGC(dpy, dc.gc, GCForeground, &gcv);
550 x = (dc.font.ascent + dc.font.descent + 2) / 4;
554 r.width = r.height = x + 1;
555 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
558 r.width = r.height = x;
559 XDrawRectangles(dpy, dc.drawable, dc.gc, &r, 1);
564 drawtext(const char *text, unsigned long col[ColLast], Bool invert) {
566 int i, x, y, h, len, olen;
567 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
569 XSetForeground(dpy, dc.gc, col[invert ? ColFG : ColBG]);
570 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
574 h = dc.font.ascent + dc.font.descent;
575 y = dc.y + (dc.h / 2) - (h / 2) + dc.font.ascent;
577 /* shorten text if necessary */
578 for(len = MIN(olen, sizeof buf); len && textnw(text, len) > dc.w - h; len--);
581 memcpy(buf, text, len);
583 for(i = len; i && i > len - 3; buf[--i] = '.');
584 XSetForeground(dpy, dc.gc, col[invert ? ColBG : ColFG]);
586 XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
588 XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
592 enternotify(XEvent *e) {
594 XCrossingEvent *ev = &e->xcrossing;
596 if((ev->mode != NotifyNormal || ev->detail == NotifyInferior) && ev->window != root)
598 if((c = getclient(ev->window)))
606 XExposeEvent *ev = &e->xexpose;
608 if(ev->count == 0 && (ev->window == barwin))
614 if(!c || !ISVISIBLE(c))
615 for(c = stack; c && !ISVISIBLE(c); c = c->snext);
616 if(sel && sel != c) {
617 grabbuttons(sel, False);
618 XSetWindowBorder(dpy, sel->win, dc.norm[ColBorder]);
623 grabbuttons(c, True);
624 XSetWindowBorder(dpy, c->win, dc.sel[ColBorder]);
625 XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
628 XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
634 focusin(XEvent *e) { /* there are some broken focus acquiring clients */
635 XFocusChangeEvent *ev = &e->xfocus;
637 if(sel && ev->window != sel->win)
638 XSetInputFocus(dpy, sel->win, RevertToPointerRoot, CurrentTime);
642 focusstack(const Arg *arg) {
643 Client *c = NULL, *i;
648 for(c = sel->next; c && !ISVISIBLE(c); c = c->next);
650 for(c = clients; c && !ISVISIBLE(c); c = c->next);
653 for(i = clients; i != sel; i = i->next)
657 for(; i; i = i->next)
668 getclient(Window w) {
671 for(c = clients; c && c->win != w; c = c->next);
676 getcolor(const char *colstr) {
677 Colormap cmap = DefaultColormap(dpy, screen);
680 if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
681 die("error, cannot allocate color '%s'\n", colstr);
689 unsigned char *p = NULL;
690 unsigned long n, extra;
693 status = XGetWindowProperty(dpy, w, wmatom[WMState], 0L, 2L, False, wmatom[WMState],
694 &real, &format, &n, &extra, (unsigned char **)&p);
695 if(status != Success)
704 gettextprop(Window w, Atom atom, char *text, unsigned int size) {
709 if(!text || size == 0)
712 XGetTextProperty(dpy, w, &name, atom);
715 if(name.encoding == XA_STRING)
716 strncpy(text, (char *)name.value, size - 1);
718 if(XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success
720 strncpy(text, *list, size - 1);
721 XFreeStringList(list);
724 text[size - 1] = '\0';
730 grabbuttons(Client *c, Bool focused) {
734 unsigned int modifiers[] = { 0, LockMask, numlockmask, numlockmask|LockMask };
735 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
737 for(i = 0; i < LENGTH(buttons); i++)
738 if(buttons[i].click == ClkClientWin)
739 for(j = 0; j < LENGTH(modifiers); j++)
740 XGrabButton(dpy, buttons[i].button, buttons[i].mask | modifiers[j], c->win, False, BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
742 XGrabButton(dpy, AnyButton, AnyModifier, c->win, False,
743 BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
752 unsigned int modifiers[] = { 0, LockMask, numlockmask, numlockmask|LockMask };
755 XUngrabKey(dpy, AnyKey, AnyModifier, root);
756 for(i = 0; i < LENGTH(keys); i++) {
757 if((code = XKeysymToKeycode(dpy, keys[i].keysym)))
758 for(j = 0; j < LENGTH(modifiers); j++)
759 XGrabKey(dpy, code, keys[i].mod | modifiers[j], root,
760 True, GrabModeAsync, GrabModeAsync);
766 initfont(const char *fontstr) {
767 char *def, **missing;
771 dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
774 fprintf(stderr, "dwm: missing fontset: %s\n", missing[n]);
775 XFreeStringList(missing);
778 XFontSetExtents *font_extents;
779 XFontStruct **xfonts;
781 dc.font.ascent = dc.font.descent = 0;
782 font_extents = XExtentsOfFontSet(dc.font.set);
783 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
784 for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
785 dc.font.ascent = MAX(dc.font.ascent, (*xfonts)->ascent);
786 dc.font.descent = MAX(dc.font.descent,(*xfonts)->descent);
791 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr))
792 && !(dc.font.xfont = XLoadQueryFont(dpy, "fixed")))
793 die("error, cannot load font: '%s'\n", fontstr);
794 dc.font.ascent = dc.font.xfont->ascent;
795 dc.font.descent = dc.font.xfont->descent;
797 dc.font.height = dc.font.ascent + dc.font.descent;
801 isprotodel(Client *c) {
806 if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
807 for(i = 0; !ret && i < n; i++)
808 if(protocols[i] == wmatom[WMDelete])
816 keypress(XEvent *e) {
822 keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
823 for(i = 0; i < LENGTH(keys); i++)
824 if(keysym == keys[i].keysym
825 && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state)
827 keys[i].func(&(keys[i].arg));
831 killclient(const Arg *arg) {
836 if(isprotodel(sel)) {
837 ev.type = ClientMessage;
838 ev.xclient.window = sel->win;
839 ev.xclient.message_type = wmatom[WMProtocols];
840 ev.xclient.format = 32;
841 ev.xclient.data.l[0] = wmatom[WMDelete];
842 ev.xclient.data.l[1] = CurrentTime;
843 XSendEvent(dpy, sel->win, False, NoEventMask, &ev);
846 XKillClient(dpy, sel->win);
850 manage(Window w, XWindowAttributes *wa) {
852 Client *c, *t = NULL;
856 if(!(c = malloc(sizeof(Client))))
857 die("fatal: could not malloc() %u bytes\n", sizeof(Client));
866 c->oldbw = wa->border_width;
867 if(c->w == sw && c->h == sh) {
873 if(c->x + WIDTH(c) > sx + sw)
874 c->x = sx + sw - WIDTH(c);
875 if(c->y + HEIGHT(c) > sy + sh)
876 c->y = sy + sh - HEIGHT(c);
877 c->x = MAX(c->x, sx);
878 /* only fix client y-offset, if the client center might cover the bar */
879 c->y = MAX(c->y, ((by == 0) && (c->x + (c->w / 2) >= wx) && (c->x + (c->w / 2) < wx + ww)) ? bh : sy);
883 wc.border_width = c->bw;
884 XConfigureWindow(dpy, w, CWBorderWidth, &wc);
885 XSetWindowBorder(dpy, w, dc.norm[ColBorder]);
886 configure(c); /* propagates border_width, if size doesn't change */
888 XSelectInput(dpy, w, EnterWindowMask|FocusChangeMask|PropertyChangeMask|StructureNotifyMask);
889 grabbuttons(c, False);
891 if(XGetTransientForHint(dpy, w, &trans))
892 t = getclient(trans);
898 c->isfloating = trans != None || c->isfixed;
900 XRaiseWindow(dpy, c->win);
903 XMoveResizeWindow(dpy, c->win, c->x + 2 * sw, c->y, c->w, c->h); /* some windows require this */
904 XMapWindow(dpy, c->win);
905 setclientstate(c, NormalState);
910 mappingnotify(XEvent *e) {
911 XMappingEvent *ev = &e->xmapping;
913 XRefreshKeyboardMapping(ev);
914 if(ev->request == MappingKeyboard)
919 maprequest(XEvent *e) {
920 static XWindowAttributes wa;
921 XMapRequestEvent *ev = &e->xmaprequest;
923 if(!XGetWindowAttributes(dpy, ev->window, &wa))
925 if(wa.override_redirect)
927 if(!getclient(ev->window))
928 manage(ev->window, &wa);
935 for(c = nexttiled(clients); c; c = nexttiled(c->next))
936 resize(c, wx, wy, ww - 2 * c->bw, wh - 2 * c->bw, resizehints);
940 movemouse(const Arg *arg) {
941 int x, y, ocx, ocy, di, nx, ny;
952 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
953 None, cursor[CurMove], CurrentTime) != GrabSuccess)
955 XQueryPointer(dpy, root, &dummy, &dummy, &x, &y, &di, &di, &dui);
959 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
961 case ConfigureRequest:
964 handler[ev.type](&ev);
967 nx = ocx + (ev.xmotion.x - x);
968 ny = ocy + (ev.xmotion.y - y);
969 if(snap && nx >= wx && nx <= wx + ww
970 && ny >= wy && ny <= wy + wh) {
971 if(abs(wx - nx) < snap)
973 else if(abs((wx + ww) - (nx + WIDTH(c))) < snap)
974 nx = wx + ww - WIDTH(c);
975 if(abs(wy - ny) < snap)
977 else if(abs((wy + wh) - (ny + HEIGHT(c))) < snap)
978 ny = wy + wh - HEIGHT(c);
979 if(!c->isfloating && lt[sellt]->arrange && (abs(nx - c->x) > snap || abs(ny - c->y) > snap))
980 togglefloating(NULL);
982 if(!lt[sellt]->arrange || c->isfloating)
983 resize(c, nx, ny, c->w, c->h, False);
987 while(ev.type != ButtonRelease);
990 XUngrabPointer(dpy, CurrentTime);
994 nexttiled(Client *c) {
995 for(; c && (c->isfloating || !ISVISIBLE(c)); c = c->next);
1000 propertynotify(XEvent *e) {
1003 XPropertyEvent *ev = &e->xproperty;
1005 if(ev->state == PropertyDelete)
1006 return; /* ignore */
1007 if((c = getclient(ev->window))) {
1010 case XA_WM_TRANSIENT_FOR:
1011 XGetTransientForHint(dpy, c->win, &trans);
1012 if(!c->isfloating && (c->isfloating = (getclient(trans) != NULL)))
1015 case XA_WM_NORMAL_HINTS:
1023 if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
1032 quit(const Arg *arg) {
1033 readin = running = False;
1037 resize(Client *c, int x, int y, int w, int h, Bool sizehints) {
1041 /* see last two sentences in ICCCM 4.1.2.3 */
1042 Bool baseismin = c->basew == c->minw && c->baseh == c->minh;
1044 /* set minimum possible */
1048 if(!baseismin) { /* temporarily remove base dimensions */
1053 /* adjust for aspect limits */
1054 if(c->mina > 0 && c->maxa > 0) {
1055 if(c->maxa < (float)w / h)
1057 else if(c->mina < (float)h / w)
1061 if(baseismin) { /* increment calculation requires this */
1066 /* adjust for increment value */
1072 /* restore base dimensions */
1076 w = MAX(w, c->minw);
1077 h = MAX(h, c->minh);
1080 w = MIN(w, c->maxw);
1083 h = MIN(h, c->maxh);
1085 if(w <= 0 || h <= 0)
1091 if(x + w + 2 * c->bw < sx)
1093 if(y + h + 2 * c->bw < sy)
1099 if(c->x != x || c->y != y || c->w != w || c->h != h) {
1102 c->w = wc.width = w;
1103 c->h = wc.height = h;
1104 wc.border_width = c->bw;
1105 XConfigureWindow(dpy, c->win,
1106 CWX|CWY|CWWidth|CWHeight|CWBorderWidth, &wc);
1113 resizemouse(const Arg *arg) {
1124 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1125 None, cursor[CurResize], CurrentTime) != GrabSuccess)
1127 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->bw - 1, c->h + c->bw - 1);
1131 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
1133 case ConfigureRequest:
1136 handler[ev.type](&ev);
1139 nw = MAX(ev.xmotion.x - ocx - 2*c->bw + 1, 1);
1140 nh = MAX(ev.xmotion.y - ocy - 2*c->bw + 1, 1);
1142 if(snap && nw >= wx && nw <= wx + ww
1143 && nh >= wy && nh <= wy + wh) {
1144 if(!c->isfloating && lt[sellt]->arrange
1145 && (abs(nw - c->w) > snap || abs(nh - c->h) > snap))
1146 togglefloating(NULL);
1148 if(!lt[sellt]->arrange || c->isfloating)
1149 resize(c, c->x, c->y, nw, nh, True);
1153 while(ev.type != ButtonRelease);
1156 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->bw - 1, c->h + c->bw - 1);
1157 XUngrabPointer(dpy, CurrentTime);
1158 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1170 if(sel->isfloating || !lt[sellt]->arrange)
1171 XRaiseWindow(dpy, sel->win);
1172 if(lt[sellt]->arrange) {
1173 wc.stack_mode = Below;
1174 wc.sibling = barwin;
1175 for(c = stack; c; c = c->snext)
1176 if(!c->isfloating && ISVISIBLE(c)) {
1177 XConfigureWindow(dpy, c->win, CWSibling|CWStackMode, &wc);
1178 wc.sibling = c->win;
1182 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1188 char sbuf[sizeof stext];
1191 unsigned int len, offset;
1194 /* main event loop, also reads status text from stdin */
1196 xfd = ConnectionNumber(dpy);
1198 len = sizeof stext - 1;
1199 sbuf[len] = stext[len] = '\0'; /* 0-terminator is never touched */
1203 FD_SET(STDIN_FILENO, &rd);
1205 if(select(xfd + 1, &rd, NULL, NULL, NULL) == -1) {
1208 die("select failed\n");
1210 if(FD_ISSET(STDIN_FILENO, &rd)) {
1211 switch((r = read(STDIN_FILENO, sbuf + offset, len - offset))) {
1213 strncpy(stext, strerror(errno), len);
1217 strncpy(stext, "EOF", 4);
1221 for(p = sbuf + offset; r > 0; p++, r--, offset++)
1222 if(*p == '\n' || *p == '\0') {
1224 strncpy(stext, sbuf, len);
1225 p += r - 1; /* p is sbuf + offset + r - 1 */
1226 for(r = 0; *(p - r) && *(p - r) != '\n'; r++);
1229 memmove(sbuf, p - r + 1, r);
1236 while(XPending(dpy)) {
1237 XNextEvent(dpy, &ev);
1238 if(handler[ev.type])
1239 (handler[ev.type])(&ev); /* call handler */
1246 unsigned int i, num;
1247 Window d1, d2, *wins = NULL;
1248 XWindowAttributes wa;
1250 if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1251 for(i = 0; i < num; i++) {
1252 if(!XGetWindowAttributes(dpy, wins[i], &wa)
1253 || wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1255 if(wa.map_state == IsViewable || getstate(wins[i]) == IconicState)
1256 manage(wins[i], &wa);
1258 for(i = 0; i < num; i++) { /* now the transients */
1259 if(!XGetWindowAttributes(dpy, wins[i], &wa))
1261 if(XGetTransientForHint(dpy, wins[i], &d1)
1262 && (wa.map_state == IsViewable || getstate(wins[i]) == IconicState))
1263 manage(wins[i], &wa);
1271 setclientstate(Client *c, long state) {
1272 long data[] = {state, None};
1274 XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1275 PropModeReplace, (unsigned char *)data, 2);
1279 setlayout(const Arg *arg) {
1280 if(!arg || !arg->v || arg->v != lt[sellt])
1283 lt[sellt] = (Layout *)arg->v;
1290 /* arg > 1.0 will set mfact absolutly */
1292 setmfact(const Arg *arg) {
1295 if(!arg || !lt[sellt]->arrange)
1297 f = arg->f < 1.0 ? arg->f + mfact : arg->f - 1.0;
1298 if(f < 0.1 || f > 0.9)
1308 XSetWindowAttributes wa;
1311 screen = DefaultScreen(dpy);
1312 root = RootWindow(dpy, screen);
1316 sw = DisplayWidth(dpy, screen);
1317 sh = DisplayHeight(dpy, screen);
1318 bh = dc.h = dc.font.height + 2;
1319 lt[0] = &layouts[0];
1320 lt[1] = &layouts[1 % LENGTH(layouts)];
1324 wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1325 wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1326 wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1327 netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1328 netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1331 wa.cursor = cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1332 cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1333 cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1335 /* init appearance */
1336 dc.norm[ColBorder] = getcolor(normbordercolor);
1337 dc.norm[ColBG] = getcolor(normbgcolor);
1338 dc.norm[ColFG] = getcolor(normfgcolor);
1339 dc.sel[ColBorder] = getcolor(selbordercolor);
1340 dc.sel[ColBG] = getcolor(selbgcolor);
1341 dc.sel[ColFG] = getcolor(selfgcolor);
1342 dc.drawable = XCreatePixmap(dpy, root, DisplayWidth(dpy, screen), bh, DefaultDepth(dpy, screen));
1343 dc.gc = XCreateGC(dpy, root, 0, 0);
1344 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
1346 XSetFont(dpy, dc.gc, dc.font.xfont->fid);
1349 for(blw = i = 0; LENGTH(layouts) > 1 && i < LENGTH(layouts); i++) {
1350 w = TEXTW(layouts[i].symbol);
1354 wa.override_redirect = 1;
1355 wa.background_pixmap = ParentRelative;
1356 wa.event_mask = ButtonPressMask|ExposureMask;
1358 barwin = XCreateWindow(dpy, root, wx, by, ww, bh, 0, DefaultDepth(dpy, screen),
1359 CopyFromParent, DefaultVisual(dpy, screen),
1360 CWOverrideRedirect|CWBackPixmap|CWEventMask, &wa);
1361 XDefineCursor(dpy, barwin, cursor[CurNormal]);
1362 XMapRaised(dpy, barwin);
1363 strcpy(stext, "dwm-"VERSION);
1366 /* EWMH support per view */
1367 XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1368 PropModeReplace, (unsigned char *) netatom, NetLast);
1370 /* select for events */
1371 wa.event_mask = SubstructureRedirectMask|SubstructureNotifyMask|ButtonPressMask
1372 |EnterWindowMask|LeaveWindowMask|StructureNotifyMask;
1373 XChangeWindowAttributes(dpy, root, CWEventMask|CWCursor, &wa);
1374 XSelectInput(dpy, root, wa.event_mask);
1380 showhide(Client *c) {
1383 if(ISVISIBLE(c)) { /* show clients top down */
1384 XMoveWindow(dpy, c->win, c->x, c->y);
1385 if(!lt[sellt]->arrange || c->isfloating)
1386 resize(c, c->x, c->y, c->w, c->h, True);
1389 else { /* hide clients bottom up */
1391 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
1397 sigchld(int signal) {
1398 while(0 < waitpid(-1, NULL, WNOHANG));
1402 spawn(const Arg *arg) {
1403 signal(SIGCHLD, sigchld);
1406 close(ConnectionNumber(dpy));
1408 execvp(((char **)arg->v)[0], (char **)arg->v);
1409 fprintf(stderr, "dwm: execvp %s", ((char **)arg->v)[0]);
1416 tag(const Arg *arg) {
1417 if(sel && arg->ui & TAGMASK) {
1418 sel->tags = arg->ui & TAGMASK;
1424 textnw(const char *text, unsigned int len) {
1428 XmbTextExtents(dc.font.set, text, len, NULL, &r);
1431 return XTextWidth(dc.font.xfont, text, len);
1440 for(n = 0, c = nexttiled(clients); c; c = nexttiled(c->next), n++);
1445 c = nexttiled(clients);
1447 resize(c, wx, wy, (n == 1 ? ww : mw) - 2 * c->bw, wh - 2 * c->bw, resizehints);
1453 x = (wx + mw > c->x + c->w) ? c->x + c->w + 2 * c->bw : wx + mw;
1455 w = (wx + mw > c->x + c->w) ? wx + ww - x : ww - mw;
1460 for(i = 0, c = nexttiled(c->next); c; c = nexttiled(c->next), i++) {
1461 resize(c, x, y, w - 2 * c->bw, /* remainder */ ((i + 1 == n)
1462 ? wy + wh - y - 2 * c->bw : h - 2 * c->bw), resizehints);
1464 y = c->y + HEIGHT(c);
1469 togglebar(const Arg *arg) {
1477 togglefloating(const Arg *arg) {
1480 sel->isfloating = !sel->isfloating || sel->isfixed;
1482 resize(sel, sel->x, sel->y, sel->w, sel->h, True);
1487 toggletag(const Arg *arg) {
1493 mask = sel->tags ^ (arg->ui & TAGMASK);
1501 toggleview(const Arg *arg) {
1502 unsigned int mask = tagset[seltags] ^ (arg->ui & TAGMASK);
1505 tagset[seltags] = mask;
1512 unmanage(Client *c) {
1515 wc.border_width = c->oldbw;
1516 /* The server grab construct avoids race conditions. */
1518 XSetErrorHandler(xerrordummy);
1519 XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
1524 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1525 setclientstate(c, WithdrawnState);
1528 XSetErrorHandler(xerror);
1534 unmapnotify(XEvent *e) {
1536 XUnmapEvent *ev = &e->xunmap;
1538 if((c = getclient(ev->window)))
1544 if(dc.drawable != 0)
1545 XFreePixmap(dpy, dc.drawable);
1546 dc.drawable = XCreatePixmap(dpy, root, ww, bh, DefaultDepth(dpy, screen));
1547 XMoveResizeWindow(dpy, barwin, wx, by, ww, bh);
1554 XineramaScreenInfo *info = NULL;
1556 /* window area geometry */
1557 if(XineramaIsActive(dpy) && (info = XineramaQueryScreens(dpy, &n))) {
1562 if(XQueryPointer(dpy, root, &dummy, &dummy, &x, &y, &di, &di, &dui))
1563 for(i = 0; i < n; i++)
1564 if(INRECT(x, y, info[i].x_org, info[i].y_org, info[i].width, info[i].height))
1568 wy = showbar && topbar ? info[i].y_org + bh : info[i].y_org;
1570 wh = showbar ? info[i].height - bh : info[i].height;
1577 wy = showbar && topbar ? sy + bh : sy;
1579 wh = showbar ? sh - bh : sh;
1583 by = showbar ? (topbar ? wy - bh : wy + wh) : -bh;
1587 updatenumlockmask(void) {
1589 XModifierKeymap *modmap;
1592 modmap = XGetModifierMapping(dpy);
1593 for(i = 0; i < 8; i++)
1594 for(j = 0; j < modmap->max_keypermod; j++)
1595 if(modmap->modifiermap[i * modmap->max_keypermod + j] == XKeysymToKeycode(dpy, XK_Num_Lock))
1596 numlockmask = (1 << i);
1597 XFreeModifiermap(modmap);
1601 updatesizehints(Client *c) {
1605 if(!XGetWMNormalHints(dpy, c->win, &size, &msize))
1606 /* size is uninitialized, ensure that size.flags aren't used */
1608 if(size.flags & PBaseSize) {
1609 c->basew = size.base_width;
1610 c->baseh = size.base_height;
1612 else if(size.flags & PMinSize) {
1613 c->basew = size.min_width;
1614 c->baseh = size.min_height;
1617 c->basew = c->baseh = 0;
1618 if(size.flags & PResizeInc) {
1619 c->incw = size.width_inc;
1620 c->inch = size.height_inc;
1623 c->incw = c->inch = 0;
1624 if(size.flags & PMaxSize) {
1625 c->maxw = size.max_width;
1626 c->maxh = size.max_height;
1629 c->maxw = c->maxh = 0;
1630 if(size.flags & PMinSize) {
1631 c->minw = size.min_width;
1632 c->minh = size.min_height;
1634 else if(size.flags & PBaseSize) {
1635 c->minw = size.base_width;
1636 c->minh = size.base_height;
1639 c->minw = c->minh = 0;
1640 if(size.flags & PAspect) {
1641 c->mina = (float)size.min_aspect.y / (float)size.min_aspect.x;
1642 c->maxa = (float)size.max_aspect.x / (float)size.max_aspect.y;
1645 c->maxa = c->mina = 0.0;
1646 c->isfixed = (c->maxw && c->minw && c->maxh && c->minh
1647 && c->maxw == c->minw && c->maxh == c->minh);
1651 updatetitle(Client *c) {
1652 if(!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
1653 gettextprop(c->win, XA_WM_NAME, c->name, sizeof c->name);
1657 updatewmhints(Client *c) {
1660 if((wmh = XGetWMHints(dpy, c->win))) {
1661 if(ISVISIBLE(c) && wmh->flags & XUrgencyHint) {
1662 wmh->flags &= ~XUrgencyHint;
1663 XSetWMHints(dpy, c->win, wmh);
1666 c->isurgent = (wmh->flags & XUrgencyHint) ? True : False;
1673 view(const Arg *arg) {
1674 if((arg->ui & TAGMASK) == tagset[seltags])
1676 seltags ^= 1; /* toggle sel tagset */
1677 if(arg->ui & TAGMASK)
1678 tagset[seltags] = arg->ui & TAGMASK;
1683 /* There's no way to check accesses to destroyed windows, thus those cases are
1684 * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
1685 * default error handler, which may call exit. */
1687 xerror(Display *dpy, XErrorEvent *ee) {
1688 if(ee->error_code == BadWindow
1689 || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1690 || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1691 || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1692 || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1693 || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1694 || (ee->request_code == X_GrabButton && ee->error_code == BadAccess)
1695 || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1696 || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1698 fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1699 ee->request_code, ee->error_code);
1700 return xerrorxlib(dpy, ee); /* may call exit */
1704 xerrordummy(Display *dpy, XErrorEvent *ee) {
1708 /* Startup Error handler to check if another window manager
1709 * is already running. */
1711 xerrorstart(Display *dpy, XErrorEvent *ee) {
1717 zoom(const Arg *arg) {
1720 if(!lt[sellt]->arrange || lt[sellt]->arrange == monocle || (sel && sel->isfloating))
1722 if(c == nexttiled(clients))
1723 if(!c || !(c = nexttiled(c->next)))
1732 main(int argc, char *argv[]) {
1733 if(argc == 2 && !strcmp("-v", argv[1]))
1734 die("dwm-"VERSION", © 2006-2008 dwm engineers, see LICENSE for details\n");
1736 die("usage: dwm [-v]\n");
1738 if(!setlocale(LC_CTYPE, "") || !XSupportsLocale())
1739 fprintf(stderr, "warning: no locale support\n");
1741 if(!(dpy = XOpenDisplay(0)))
1742 die("dwm: cannot open display\n");