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 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 spawn(const Arg *arg);
186 static void tag(const Arg *arg);
187 static int textnw(const char *text, unsigned int len);
188 static void tile(void);
189 static void togglebar(const Arg *arg);
190 static void togglefloating(const Arg *arg);
191 static void toggletag(const Arg *arg);
192 static void toggleview(const Arg *arg);
193 static void unmanage(Client *c);
194 static void unmapnotify(XEvent *e);
195 static void updatebar(void);
196 static void updategeom(void);
197 static void updatenumlockmask(void);
198 static void updatesizehints(Client *c);
199 static void updatetitle(Client *c);
200 static void updatewmhints(Client *c);
201 static void view(const Arg *arg);
202 static int xerror(Display *dpy, XErrorEvent *ee);
203 static int xerrordummy(Display *dpy, XErrorEvent *ee);
204 static int xerrorstart(Display *dpy, XErrorEvent *ee);
205 static void zoom(const Arg *arg);
208 static char stext[256];
210 static int sx, sy, sw, sh; /* X display screen geometry x, y, width, height */
211 static int by, bh, blw; /* bar geometry y, height and layout symbol width */
212 static int wx, wy, ww, wh; /* window area geometry x, y, width, height, bar excluded */
213 static unsigned int seltags = 0, sellt = 0;
214 static int (*xerrorxlib)(Display *, XErrorEvent *);
215 static unsigned int numlockmask = 0;
216 static void (*handler[LASTEvent]) (XEvent *) = {
217 [ButtonPress] = buttonpress,
218 [ConfigureRequest] = configurerequest,
219 [ConfigureNotify] = configurenotify,
220 [DestroyNotify] = destroynotify,
221 [EnterNotify] = enternotify,
224 [KeyPress] = keypress,
225 [MappingNotify] = mappingnotify,
226 [MapRequest] = maprequest,
227 [PropertyNotify] = propertynotify,
228 [UnmapNotify] = unmapnotify
230 static Atom wmatom[WMLast], netatom[NetLast];
232 static Bool running = True;
233 static Client *clients = NULL;
234 static Client *sel = NULL;
235 static Client *stack = NULL;
236 static Cursor cursor[CurLast];
239 static Layout *lt[] = { NULL, NULL };
240 static Window root, barwin;
241 /* configuration, allows nested code to access above variables */
244 /* compile-time check if all tags fit into an unsigned int bit array. */
245 struct NumTags { char limitexceeded[sizeof(unsigned int) * 8 < LENGTH(tags) ? -1 : 1]; };
247 /* function implementations */
249 applyrules(Client *c) {
252 XClassHint ch = { 0 };
255 if(XGetClassHint(dpy, c->win, &ch)) {
256 for(i = 0; i < LENGTH(rules); i++) {
258 if((!r->title || strstr(c->name, r->title))
259 && (!r->class || (ch.res_class && strstr(ch.res_class, r->class)))
260 && (!r->instance || (ch.res_name && strstr(ch.res_name, r->instance)))) {
261 c->isfloating = r->isfloating;
262 c->tags |= r->tags & TAGMASK;
271 c->tags = tagset[seltags];
278 if(lt[sellt]->arrange)
279 lt[sellt]->arrange();
290 attachstack(Client *c) {
296 buttonpress(XEvent *e) {
297 unsigned int i, x, click;
300 XButtonPressedEvent *ev = &e->xbutton;
303 if(ev->window == barwin) {
305 do x += TEXTW(tags[i]); while(ev->x >= x && ++i < LENGTH(tags));
306 if(i < LENGTH(tags)) {
310 else if(ev->x < x + blw)
312 else if(ev->x > wx + ww - TEXTW(stext))
313 click = ClkStatusText;
317 else if((c = getclient(ev->window))) {
319 click = ClkClientWin;
322 for(i = 0; i < LENGTH(buttons); i++)
323 if(click == buttons[i].click && buttons[i].func && buttons[i].button == ev->button
324 && CLEANMASK(buttons[i].mask) == CLEANMASK(ev->state))
325 buttons[i].func(click == ClkTagBar && buttons[i].arg.i == 0 ? &arg : &buttons[i].arg);
331 xerrorxlib = XSetErrorHandler(xerrorstart);
333 /* this causes an error if some other window manager is running */
334 XSelectInput(dpy, DefaultRootWindow(dpy), SubstructureRedirectMask);
337 die("dwm: another window manager is already running\n");
338 XSetErrorHandler(xerror);
345 Layout foo = { "", NULL };
353 XFreeFontSet(dpy, dc.font.set);
355 XFreeFont(dpy, dc.font.xfont);
356 XUngrabKey(dpy, AnyKey, AnyModifier, root);
357 XFreePixmap(dpy, dc.drawable);
359 XFreeCursor(dpy, cursor[CurNormal]);
360 XFreeCursor(dpy, cursor[CurResize]);
361 XFreeCursor(dpy, cursor[CurMove]);
362 XDestroyWindow(dpy, barwin);
364 XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime);
372 for(c = clients; c; c = c->next)
373 if(ISVISIBLE(c) && c->isurgent) {
375 if (!(wmh = XGetWMHints(dpy, c->win)))
378 wmh->flags &= ~XUrgencyHint;
379 XSetWMHints(dpy, c->win, wmh);
385 configure(Client *c) {
388 ce.type = ConfigureNotify;
396 ce.border_width = c->bw;
398 ce.override_redirect = False;
399 XSendEvent(dpy, c->win, False, StructureNotifyMask, (XEvent *)&ce);
403 configurenotify(XEvent *e) {
404 XConfigureEvent *ev = &e->xconfigure;
406 if(ev->window == root && (ev->width != sw || ev->height != sh)) {
416 configurerequest(XEvent *e) {
418 XConfigureRequestEvent *ev = &e->xconfigurerequest;
421 if((c = getclient(ev->window))) {
422 if(ev->value_mask & CWBorderWidth)
423 c->bw = ev->border_width;
424 else if(c->isfloating || !lt[sellt]->arrange) {
425 if(ev->value_mask & CWX)
427 if(ev->value_mask & CWY)
429 if(ev->value_mask & CWWidth)
431 if(ev->value_mask & CWHeight)
433 if((c->x - sx + c->w) > sw && c->isfloating)
434 c->x = sx + (sw / 2 - c->w / 2); /* center in x direction */
435 if((c->y - sy + c->h) > sh && c->isfloating)
436 c->y = sy + (sh / 2 - c->h / 2); /* center in y direction */
437 if((ev->value_mask & (CWX|CWY)) && !(ev->value_mask & (CWWidth|CWHeight)))
440 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h);
448 wc.width = ev->width;
449 wc.height = ev->height;
450 wc.border_width = ev->border_width;
451 wc.sibling = ev->above;
452 wc.stack_mode = ev->detail;
453 XConfigureWindow(dpy, ev->window, ev->value_mask, &wc);
459 destroynotify(XEvent *e) {
461 XDestroyWindowEvent *ev = &e->xdestroywindow;
463 if((c = getclient(ev->window)))
471 for(tc = &clients; *tc && *tc != c; tc = &(*tc)->next);
476 detachstack(Client *c) {
479 for(tc = &stack; *tc && *tc != c; tc = &(*tc)->snext);
484 die(const char *errstr, ...) {
487 va_start(ap, errstr);
488 vfprintf(stderr, errstr, ap);
496 unsigned int i, occ = 0, urg = 0;
500 for(c = clients; c; c = c->next) {
507 for(i = 0; i < LENGTH(tags); i++) {
508 dc.w = TEXTW(tags[i]);
509 col = tagset[seltags] & 1 << i ? dc.sel : dc.norm;
510 drawtext(tags[i], col, urg & 1 << i);
511 drawsquare(sel && sel->tags & 1 << i, occ & 1 << i, urg & 1 << i, col);
516 drawtext(lt[sellt]->symbol, dc.norm, False);
527 drawtext(stext, dc.norm, False);
528 if((dc.w = dc.x - x) > bh) {
531 drawtext(sel->name, dc.sel, False);
532 drawsquare(sel->isfixed, sel->isfloating, False, dc.sel);
535 drawtext(NULL, dc.norm, False);
537 XCopyArea(dpy, dc.drawable, barwin, dc.gc, 0, 0, ww, bh, 0, 0);
542 drawsquare(Bool filled, Bool empty, Bool invert, unsigned long col[ColLast]) {
545 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
547 gcv.foreground = col[invert ? ColBG : ColFG];
548 XChangeGC(dpy, dc.gc, GCForeground, &gcv);
549 x = (dc.font.ascent + dc.font.descent + 2) / 4;
553 r.width = r.height = x + 1;
554 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
557 r.width = r.height = x;
558 XDrawRectangles(dpy, dc.drawable, dc.gc, &r, 1);
563 drawtext(const char *text, unsigned long col[ColLast], Bool invert) {
565 int i, x, y, h, len, olen;
566 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
568 XSetForeground(dpy, dc.gc, col[invert ? ColFG : ColBG]);
569 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
573 h = dc.font.ascent + dc.font.descent;
574 y = dc.y + (dc.h / 2) - (h / 2) + dc.font.ascent;
576 /* shorten text if necessary */
577 for(len = MIN(olen, sizeof buf); len && textnw(text, len) > dc.w - h; len--);
580 memcpy(buf, text, len);
582 for(i = len; i && i > len - 3; buf[--i] = '.');
583 XSetForeground(dpy, dc.gc, col[invert ? ColBG : ColFG]);
585 XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
587 XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
591 enternotify(XEvent *e) {
593 XCrossingEvent *ev = &e->xcrossing;
595 if((ev->mode != NotifyNormal || ev->detail == NotifyInferior) && ev->window != root)
597 if((c = getclient(ev->window)))
605 XExposeEvent *ev = &e->xexpose;
607 if(ev->count == 0 && (ev->window == barwin))
613 if(!c || !ISVISIBLE(c))
614 for(c = stack; c && !ISVISIBLE(c); c = c->snext);
615 if(sel && sel != c) {
616 grabbuttons(sel, False);
617 XSetWindowBorder(dpy, sel->win, dc.norm[ColBorder]);
622 grabbuttons(c, True);
623 XSetWindowBorder(dpy, c->win, dc.sel[ColBorder]);
624 XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
627 XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
633 focusin(XEvent *e) { /* there are some broken focus acquiring clients */
634 XFocusChangeEvent *ev = &e->xfocus;
636 if(sel && ev->window != sel->win)
637 XSetInputFocus(dpy, sel->win, RevertToPointerRoot, CurrentTime);
641 focusstack(const Arg *arg) {
642 Client *c = NULL, *i;
647 for(c = sel->next; c && !ISVISIBLE(c); c = c->next);
649 for(c = clients; c && !ISVISIBLE(c); c = c->next);
652 for(i = clients; i != sel; i = i->next)
656 for(; i; i = i->next)
667 getclient(Window w) {
670 for(c = clients; c && c->win != w; c = c->next);
675 getcolor(const char *colstr) {
676 Colormap cmap = DefaultColormap(dpy, screen);
679 if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
680 die("error, cannot allocate color '%s'\n", colstr);
688 unsigned char *p = NULL;
689 unsigned long n, extra;
692 status = XGetWindowProperty(dpy, w, wmatom[WMState], 0L, 2L, False, wmatom[WMState],
693 &real, &format, &n, &extra, (unsigned char **)&p);
694 if(status != Success)
703 gettextprop(Window w, Atom atom, char *text, unsigned int size) {
708 if(!text || size == 0)
711 XGetTextProperty(dpy, w, &name, atom);
714 if(name.encoding == XA_STRING)
715 strncpy(text, (char *)name.value, size - 1);
717 if(XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success
719 strncpy(text, *list, size - 1);
720 XFreeStringList(list);
723 text[size - 1] = '\0';
729 grabbuttons(Client *c, Bool focused) {
733 unsigned int modifiers[] = { 0, LockMask, numlockmask, numlockmask|LockMask };
734 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
736 for(i = 0; i < LENGTH(buttons); i++)
737 if(buttons[i].click == ClkClientWin)
738 for(j = 0; j < LENGTH(modifiers); j++)
739 XGrabButton(dpy, buttons[i].button, buttons[i].mask | modifiers[j], c->win, False, BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
741 XGrabButton(dpy, AnyButton, AnyModifier, c->win, False,
742 BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
751 unsigned int modifiers[] = { 0, LockMask, numlockmask, numlockmask|LockMask };
754 XUngrabKey(dpy, AnyKey, AnyModifier, root);
755 for(i = 0; i < LENGTH(keys); i++) {
756 if((code = XKeysymToKeycode(dpy, keys[i].keysym)))
757 for(j = 0; j < LENGTH(modifiers); j++)
758 XGrabKey(dpy, code, keys[i].mod | modifiers[j], root,
759 True, GrabModeAsync, GrabModeAsync);
765 initfont(const char *fontstr) {
766 char *def, **missing;
770 dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
773 fprintf(stderr, "dwm: missing fontset: %s\n", missing[n]);
774 XFreeStringList(missing);
777 XFontSetExtents *font_extents;
778 XFontStruct **xfonts;
780 dc.font.ascent = dc.font.descent = 0;
781 font_extents = XExtentsOfFontSet(dc.font.set);
782 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
783 for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
784 dc.font.ascent = MAX(dc.font.ascent, (*xfonts)->ascent);
785 dc.font.descent = MAX(dc.font.descent,(*xfonts)->descent);
790 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr))
791 && !(dc.font.xfont = XLoadQueryFont(dpy, "fixed")))
792 die("error, cannot load font: '%s'\n", fontstr);
793 dc.font.ascent = dc.font.xfont->ascent;
794 dc.font.descent = dc.font.xfont->descent;
796 dc.font.height = dc.font.ascent + dc.font.descent;
800 isprotodel(Client *c) {
805 if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
806 for(i = 0; !ret && i < n; i++)
807 if(protocols[i] == wmatom[WMDelete])
815 keypress(XEvent *e) {
821 keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
822 for(i = 0; i < LENGTH(keys); i++)
823 if(keysym == keys[i].keysym
824 && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state)
826 keys[i].func(&(keys[i].arg));
830 killclient(const Arg *arg) {
835 if(isprotodel(sel)) {
836 ev.type = ClientMessage;
837 ev.xclient.window = sel->win;
838 ev.xclient.message_type = wmatom[WMProtocols];
839 ev.xclient.format = 32;
840 ev.xclient.data.l[0] = wmatom[WMDelete];
841 ev.xclient.data.l[1] = CurrentTime;
842 XSendEvent(dpy, sel->win, False, NoEventMask, &ev);
845 XKillClient(dpy, sel->win);
849 manage(Window w, XWindowAttributes *wa) {
851 Client *c, *t = NULL;
855 if(!(c = malloc(sizeof(Client))))
856 die("fatal: could not malloc() %u bytes\n", sizeof(Client));
865 c->oldbw = wa->border_width;
866 if(c->w == sw && c->h == sh) {
872 if(c->x + WIDTH(c) > sx + sw)
873 c->x = sx + sw - WIDTH(c);
874 if(c->y + HEIGHT(c) > sy + sh)
875 c->y = sy + sh - HEIGHT(c);
876 c->x = MAX(c->x, sx);
877 /* only fix client y-offset, if the client center might cover the bar */
878 c->y = MAX(c->y, ((by == 0) && (c->x + (c->w / 2) >= wx) && (c->x + (c->w / 2) < wx + ww)) ? bh : sy);
882 wc.border_width = c->bw;
883 XConfigureWindow(dpy, w, CWBorderWidth, &wc);
884 XSetWindowBorder(dpy, w, dc.norm[ColBorder]);
885 configure(c); /* propagates border_width, if size doesn't change */
887 XSelectInput(dpy, w, EnterWindowMask|FocusChangeMask|PropertyChangeMask|StructureNotifyMask);
888 grabbuttons(c, False);
890 if(XGetTransientForHint(dpy, w, &trans))
891 t = getclient(trans);
897 c->isfloating = trans != None || c->isfixed;
899 XRaiseWindow(dpy, c->win);
902 XMoveResizeWindow(dpy, c->win, c->x + 2 * sw, c->y, c->w, c->h); /* some windows require this */
903 XMapWindow(dpy, c->win);
904 setclientstate(c, NormalState);
909 mappingnotify(XEvent *e) {
910 XMappingEvent *ev = &e->xmapping;
912 XRefreshKeyboardMapping(ev);
913 if(ev->request == MappingKeyboard)
918 maprequest(XEvent *e) {
919 static XWindowAttributes wa;
920 XMapRequestEvent *ev = &e->xmaprequest;
922 if(!XGetWindowAttributes(dpy, ev->window, &wa))
924 if(wa.override_redirect)
926 if(!getclient(ev->window))
927 manage(ev->window, &wa);
934 for(c = nexttiled(clients); c; c = nexttiled(c->next))
935 resize(c, wx, wy, ww - 2*c->bw, wh - 2*c->bw, resizehints);
939 movemouse(const Arg *arg) {
940 int x, y, ocx, ocy, di, nx, ny;
951 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
952 None, cursor[CurMove], CurrentTime) != GrabSuccess)
954 XQueryPointer(dpy, root, &dummy, &dummy, &x, &y, &di, &di, &dui);
956 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
958 case ConfigureRequest:
961 handler[ev.type](&ev);
965 nx = ocx + (ev.xmotion.x - x);
966 ny = ocy + (ev.xmotion.y - y);
967 if(snap && nx >= wx && nx <= wx + ww
968 && ny >= wy && ny <= wy + wh) {
969 if(abs(wx - nx) < snap)
971 else if(abs((wx + ww) - (nx + WIDTH(c))) < snap)
972 nx = wx + ww - WIDTH(c);
973 if(abs(wy - ny) < snap)
975 else if(abs((wy + wh) - (ny + HEIGHT(c))) < snap)
976 ny = wy + wh - HEIGHT(c);
977 if(!c->isfloating && lt[sellt]->arrange && (abs(nx - c->x) > snap || abs(ny - c->y) > snap))
978 togglefloating(NULL);
980 if(!lt[sellt]->arrange || c->isfloating)
981 resize(c, nx, ny, c->w, c->h, False);
985 while(ev.type != ButtonRelease);
986 XUngrabPointer(dpy, CurrentTime);
990 nexttiled(Client *c) {
991 for(; c && (c->isfloating || !ISVISIBLE(c)); c = c->next);
996 propertynotify(XEvent *e) {
999 XPropertyEvent *ev = &e->xproperty;
1001 if(ev->state == PropertyDelete)
1002 return; /* ignore */
1003 if((c = getclient(ev->window))) {
1006 case XA_WM_TRANSIENT_FOR:
1007 XGetTransientForHint(dpy, c->win, &trans);
1008 if(!c->isfloating && (c->isfloating = (getclient(trans) != NULL)))
1011 case XA_WM_NORMAL_HINTS:
1019 if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
1028 quit(const Arg *arg) {
1029 readin = running = False;
1033 resize(Client *c, int x, int y, int w, int h, Bool sizehints) {
1037 /* see last two sentences in ICCCM 4.1.2.3 */
1038 Bool baseismin = c->basew == c->minw && c->baseh == c->minh;
1040 /* set minimum possible */
1044 if(!baseismin) { /* temporarily remove base dimensions */
1049 /* adjust for aspect limits */
1050 if(c->mina > 0 && c->maxa > 0) {
1051 if(c->maxa < (float)w / h)
1053 else if(c->mina < (float)h / w)
1057 if(baseismin) { /* increment calculation requires this */
1062 /* adjust for increment value */
1068 /* restore base dimensions */
1072 w = MAX(w, c->minw);
1073 h = MAX(h, c->minh);
1076 w = MIN(w, c->maxw);
1079 h = MIN(h, c->maxh);
1081 if(w <= 0 || h <= 0)
1087 if(x + w + 2 * c->bw < sx)
1089 if(y + h + 2 * c->bw < sy)
1095 if(c->x != x || c->y != y || c->w != w || c->h != h) {
1098 c->w = wc.width = w;
1099 c->h = wc.height = h;
1100 wc.border_width = c->bw;
1101 XConfigureWindow(dpy, c->win,
1102 CWX|CWY|CWWidth|CWHeight|CWBorderWidth, &wc);
1109 resizemouse(const Arg *arg) {
1120 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1121 None, cursor[CurResize], CurrentTime) != GrabSuccess)
1123 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->bw - 1, c->h + c->bw - 1);
1125 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
1127 case ConfigureRequest:
1130 handler[ev.type](&ev);
1134 nw = MAX(ev.xmotion.x - ocx - 2*c->bw + 1, 1);
1135 nh = MAX(ev.xmotion.y - ocy - 2*c->bw + 1, 1);
1137 if(snap && nw >= wx && nw <= wx + ww
1138 && nh >= wy && nh <= wy + wh) {
1139 if(!c->isfloating && lt[sellt]->arrange
1140 && (abs(nw - c->w) > snap || abs(nh - c->h) > snap))
1141 togglefloating(NULL);
1143 if(!lt[sellt]->arrange || c->isfloating)
1144 resize(c, c->x, c->y, nw, nh, True);
1148 while(ev.type != ButtonRelease);
1149 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->bw - 1, c->h + c->bw - 1);
1150 XUngrabPointer(dpy, CurrentTime);
1151 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1163 if(sel->isfloating || !lt[sellt]->arrange)
1164 XRaiseWindow(dpy, sel->win);
1165 if(lt[sellt]->arrange) {
1166 wc.stack_mode = Below;
1167 wc.sibling = barwin;
1168 for(c = stack; c; c = c->snext)
1169 if(!c->isfloating && ISVISIBLE(c)) {
1170 XConfigureWindow(dpy, c->win, CWSibling|CWStackMode, &wc);
1171 wc.sibling = c->win;
1175 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1181 char sbuf[sizeof stext];
1184 unsigned int len, offset;
1187 /* main event loop, also reads status text from stdin */
1189 xfd = ConnectionNumber(dpy);
1191 len = sizeof stext - 1;
1192 sbuf[len] = stext[len] = '\0'; /* 0-terminator is never touched */
1196 FD_SET(STDIN_FILENO, &rd);
1198 if(select(xfd + 1, &rd, NULL, NULL, NULL) == -1) {
1201 die("select failed\n");
1203 if(FD_ISSET(STDIN_FILENO, &rd)) {
1204 switch((r = read(STDIN_FILENO, sbuf + offset, len - offset))) {
1206 strncpy(stext, strerror(errno), len);
1210 strncpy(stext, "EOF", 4);
1214 for(p = sbuf + offset; r > 0; p++, r--, offset++)
1215 if(*p == '\n' || *p == '\0') {
1217 strncpy(stext, sbuf, len);
1218 p += r - 1; /* p is sbuf + offset + r - 1 */
1219 for(r = 0; *(p - r) && *(p - r) != '\n'; r++);
1222 memmove(sbuf, p - r + 1, r);
1229 while(XPending(dpy)) {
1230 XNextEvent(dpy, &ev);
1231 if(handler[ev.type])
1232 (handler[ev.type])(&ev); /* call handler */
1239 unsigned int i, num;
1240 Window d1, d2, *wins = NULL;
1241 XWindowAttributes wa;
1243 if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1244 for(i = 0; i < num; i++) {
1245 if(!XGetWindowAttributes(dpy, wins[i], &wa)
1246 || wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1248 if(wa.map_state == IsViewable || getstate(wins[i]) == IconicState)
1249 manage(wins[i], &wa);
1251 for(i = 0; i < num; i++) { /* now the transients */
1252 if(!XGetWindowAttributes(dpy, wins[i], &wa))
1254 if(XGetTransientForHint(dpy, wins[i], &d1)
1255 && (wa.map_state == IsViewable || getstate(wins[i]) == IconicState))
1256 manage(wins[i], &wa);
1264 setclientstate(Client *c, long state) {
1265 long data[] = {state, None};
1267 XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1268 PropModeReplace, (unsigned char *)data, 2);
1272 setlayout(const Arg *arg) {
1273 if(!arg || !arg->v || arg->v != lt[sellt])
1276 lt[sellt] = (Layout *)arg->v;
1283 /* arg > 1.0 will set mfact absolutly */
1285 setmfact(const Arg *arg) {
1288 if(!arg || !lt[sellt]->arrange)
1290 f = arg->f < 1.0 ? arg->f + mfact : arg->f - 1.0;
1291 if(f < 0.1 || f > 0.9)
1301 XSetWindowAttributes wa;
1304 screen = DefaultScreen(dpy);
1305 root = RootWindow(dpy, screen);
1309 sw = DisplayWidth(dpy, screen);
1310 sh = DisplayHeight(dpy, screen);
1311 bh = dc.h = dc.font.height + 2;
1312 lt[0] = &layouts[0];
1313 lt[1] = &layouts[1 % LENGTH(layouts)];
1317 wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1318 wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1319 wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1320 netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1321 netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1324 wa.cursor = cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1325 cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1326 cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1328 /* init appearance */
1329 dc.norm[ColBorder] = getcolor(normbordercolor);
1330 dc.norm[ColBG] = getcolor(normbgcolor);
1331 dc.norm[ColFG] = getcolor(normfgcolor);
1332 dc.sel[ColBorder] = getcolor(selbordercolor);
1333 dc.sel[ColBG] = getcolor(selbgcolor);
1334 dc.sel[ColFG] = getcolor(selfgcolor);
1335 dc.drawable = XCreatePixmap(dpy, root, DisplayWidth(dpy, screen), bh, DefaultDepth(dpy, screen));
1336 dc.gc = XCreateGC(dpy, root, 0, 0);
1337 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
1339 XSetFont(dpy, dc.gc, dc.font.xfont->fid);
1342 for(blw = i = 0; LENGTH(layouts) > 1 && i < LENGTH(layouts); i++) {
1343 w = TEXTW(layouts[i].symbol);
1347 wa.override_redirect = 1;
1348 wa.background_pixmap = ParentRelative;
1349 wa.event_mask = ButtonPressMask|ExposureMask;
1351 barwin = XCreateWindow(dpy, root, wx, by, ww, bh, 0, DefaultDepth(dpy, screen),
1352 CopyFromParent, DefaultVisual(dpy, screen),
1353 CWOverrideRedirect|CWBackPixmap|CWEventMask, &wa);
1354 XDefineCursor(dpy, barwin, cursor[CurNormal]);
1355 XMapRaised(dpy, barwin);
1356 strcpy(stext, "dwm-"VERSION);
1359 /* EWMH support per view */
1360 XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1361 PropModeReplace, (unsigned char *) netatom, NetLast);
1363 /* select for events */
1364 wa.event_mask = SubstructureRedirectMask|SubstructureNotifyMask|ButtonPressMask
1365 |EnterWindowMask|LeaveWindowMask|StructureNotifyMask;
1366 XChangeWindowAttributes(dpy, root, CWEventMask|CWCursor, &wa);
1367 XSelectInput(dpy, root, wa.event_mask);
1373 showhide(Client *c) {
1376 if(ISVISIBLE(c)) { /* show clients top down */
1377 XMoveWindow(dpy, c->win, c->x, c->y);
1378 if(!lt[sellt]->arrange || c->isfloating)
1379 resize(c, c->x, c->y, c->w, c->h, True);
1382 else { /* hide clients bottom up */
1384 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
1389 spawn(const Arg *arg) {
1390 /* The double-fork construct avoids zombie processes and keeps the code
1391 * clean from stupid signal handlers. */
1395 close(ConnectionNumber(dpy));
1397 execvp(((char **)arg->v)[0], (char **)arg->v);
1398 fprintf(stderr, "dwm: execvp %s", ((char **)arg->v)[0]);
1407 tag(const Arg *arg) {
1408 if(sel && arg->ui & TAGMASK) {
1409 sel->tags = arg->ui & TAGMASK;
1415 textnw(const char *text, unsigned int len) {
1419 XmbTextExtents(dc.font.set, text, len, NULL, &r);
1422 return XTextWidth(dc.font.xfont, text, len);
1431 for(n = 0, c = nexttiled(clients); c; c = nexttiled(c->next), n++);
1436 c = nexttiled(clients);
1438 resize(c, wx, wy, (n == 1 ? ww : mw) - 2*c->bw, wh - 2*c->bw, resizehints);
1444 x = (wx + mw > c->x + c->w) ? c->x + c->w + 2 * c->bw : wx + mw;
1446 w = (wx + mw > c->x + c->w) ? wx + ww - x : ww - mw;
1451 for(i = 0, c = nexttiled(c->next); c; c = nexttiled(c->next), i++) {
1452 resize(c, x, y, w - 2*c->bw, /* remainder */ ((i + 1 == n)
1453 ? wy + wh - y : h) - 2*c->bw, resizehints);
1455 y = c->y + HEIGHT(c);
1460 togglebar(const Arg *arg) {
1468 togglefloating(const Arg *arg) {
1471 sel->isfloating = !sel->isfloating || sel->isfixed;
1473 resize(sel, sel->x, sel->y, sel->w, sel->h, True);
1478 toggletag(const Arg *arg) {
1484 mask = sel->tags ^ (arg->ui & TAGMASK);
1492 toggleview(const Arg *arg) {
1493 unsigned int mask = tagset[seltags] ^ (arg->ui & TAGMASK);
1496 tagset[seltags] = mask;
1503 unmanage(Client *c) {
1506 wc.border_width = c->oldbw;
1507 /* The server grab construct avoids race conditions. */
1509 XSetErrorHandler(xerrordummy);
1510 XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
1515 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1516 setclientstate(c, WithdrawnState);
1519 XSetErrorHandler(xerror);
1525 unmapnotify(XEvent *e) {
1527 XUnmapEvent *ev = &e->xunmap;
1529 if((c = getclient(ev->window)))
1535 if(dc.drawable != 0)
1536 XFreePixmap(dpy, dc.drawable);
1537 dc.drawable = XCreatePixmap(dpy, root, ww, bh, DefaultDepth(dpy, screen));
1538 XMoveResizeWindow(dpy, barwin, wx, by, ww, bh);
1545 XineramaScreenInfo *info = NULL;
1547 /* window area geometry */
1548 if(XineramaIsActive(dpy) && (info = XineramaQueryScreens(dpy, &n))) {
1553 if(XQueryPointer(dpy, root, &dummy, &dummy, &x, &y, &di, &di, &dui))
1554 for(i = 0; i < n; i++)
1555 if(INRECT(x, y, info[i].x_org, info[i].y_org, info[i].width, info[i].height))
1559 wy = showbar && topbar ? info[i].y_org + bh : info[i].y_org;
1561 wh = showbar ? info[i].height - bh : info[i].height;
1568 wy = showbar && topbar ? sy + bh : sy;
1570 wh = showbar ? sh - bh : sh;
1574 by = showbar ? (topbar ? wy - bh : wy + wh) : -bh;
1578 updatenumlockmask(void) {
1580 XModifierKeymap *modmap;
1583 modmap = XGetModifierMapping(dpy);
1584 for(i = 0; i < 8; i++)
1585 for(j = 0; j < modmap->max_keypermod; j++)
1586 if(modmap->modifiermap[i * modmap->max_keypermod + j] == XKeysymToKeycode(dpy, XK_Num_Lock))
1587 numlockmask = (1 << i);
1588 XFreeModifiermap(modmap);
1592 updatesizehints(Client *c) {
1596 if(!XGetWMNormalHints(dpy, c->win, &size, &msize))
1597 /* size is uninitialized, ensure that size.flags aren't used */
1599 if(size.flags & PBaseSize) {
1600 c->basew = size.base_width;
1601 c->baseh = size.base_height;
1603 else if(size.flags & PMinSize) {
1604 c->basew = size.min_width;
1605 c->baseh = size.min_height;
1608 c->basew = c->baseh = 0;
1609 if(size.flags & PResizeInc) {
1610 c->incw = size.width_inc;
1611 c->inch = size.height_inc;
1614 c->incw = c->inch = 0;
1615 if(size.flags & PMaxSize) {
1616 c->maxw = size.max_width;
1617 c->maxh = size.max_height;
1620 c->maxw = c->maxh = 0;
1621 if(size.flags & PMinSize) {
1622 c->minw = size.min_width;
1623 c->minh = size.min_height;
1625 else if(size.flags & PBaseSize) {
1626 c->minw = size.base_width;
1627 c->minh = size.base_height;
1630 c->minw = c->minh = 0;
1631 if(size.flags & PAspect) {
1632 c->mina = (float)size.min_aspect.y / (float)size.min_aspect.x;
1633 c->maxa = (float)size.max_aspect.x / (float)size.max_aspect.y;
1636 c->maxa = c->mina = 0.0;
1637 c->isfixed = (c->maxw && c->minw && c->maxh && c->minh
1638 && c->maxw == c->minw && c->maxh == c->minh);
1642 updatetitle(Client *c) {
1643 if(!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
1644 gettextprop(c->win, XA_WM_NAME, c->name, sizeof c->name);
1648 updatewmhints(Client *c) {
1651 if((wmh = XGetWMHints(dpy, c->win))) {
1652 if(ISVISIBLE(c) && wmh->flags & XUrgencyHint) {
1653 wmh->flags &= ~XUrgencyHint;
1654 XSetWMHints(dpy, c->win, wmh);
1657 c->isurgent = (wmh->flags & XUrgencyHint) ? True : False;
1664 view(const Arg *arg) {
1665 if((arg->ui & TAGMASK) == tagset[seltags])
1667 seltags ^= 1; /* toggle sel tagset */
1668 if(arg->ui & TAGMASK)
1669 tagset[seltags] = arg->ui & TAGMASK;
1674 /* There's no way to check accesses to destroyed windows, thus those cases are
1675 * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
1676 * default error handler, which may call exit. */
1678 xerror(Display *dpy, XErrorEvent *ee) {
1679 if(ee->error_code == BadWindow
1680 || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1681 || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1682 || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1683 || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1684 || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1685 || (ee->request_code == X_GrabButton && ee->error_code == BadAccess)
1686 || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1687 || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1689 fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1690 ee->request_code, ee->error_code);
1691 return xerrorxlib(dpy, ee); /* may call exit */
1695 xerrordummy(Display *dpy, XErrorEvent *ee) {
1699 /* Startup Error handler to check if another window manager
1700 * is already running. */
1702 xerrorstart(Display *dpy, XErrorEvent *ee) {
1708 zoom(const Arg *arg) {
1711 if(!lt[sellt]->arrange || lt[sellt]->arrange == monocle || (sel && sel->isfloating))
1713 if(c == nexttiled(clients))
1714 if(!c || !(c = nexttiled(c->next)))
1723 main(int argc, char *argv[]) {
1724 if(argc == 2 && !strcmp("-v", argv[1]))
1725 die("dwm-"VERSION", © 2006-2008 dwm engineers, see LICENSE for details\n");
1727 die("usage: dwm [-v]\n");
1729 if(!setlocale(LC_CTYPE, "") || !XSupportsLocale())
1730 fprintf(stderr, "warning: no locale support\n");
1732 if(!(dpy = XOpenDisplay(0)))
1733 die("dwm: cannot open display\n");