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(Client *c);
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);
368 clearurgent(Client *c) {
372 if(!(wmh = XGetWMHints(dpy, c->win)))
374 wmh->flags &= ~XUrgencyHint;
375 XSetWMHints(dpy, c->win, wmh);
380 configure(Client *c) {
383 ce.type = ConfigureNotify;
391 ce.border_width = c->bw;
393 ce.override_redirect = False;
394 XSendEvent(dpy, c->win, False, StructureNotifyMask, (XEvent *)&ce);
398 configurenotify(XEvent *e) {
399 XConfigureEvent *ev = &e->xconfigure;
401 if(ev->window == root && (ev->width != sw || ev->height != sh)) {
411 configurerequest(XEvent *e) {
413 XConfigureRequestEvent *ev = &e->xconfigurerequest;
416 if((c = getclient(ev->window))) {
417 if(ev->value_mask & CWBorderWidth)
418 c->bw = ev->border_width;
419 else if(c->isfloating || !lt[sellt]->arrange) {
420 if(ev->value_mask & CWX)
422 if(ev->value_mask & CWY)
424 if(ev->value_mask & CWWidth)
426 if(ev->value_mask & CWHeight)
428 if((c->x - sx + c->w) > sw && c->isfloating)
429 c->x = sx + (sw / 2 - c->w / 2); /* center in x direction */
430 if((c->y - sy + c->h) > sh && c->isfloating)
431 c->y = sy + (sh / 2 - c->h / 2); /* center in y direction */
432 if((ev->value_mask & (CWX|CWY)) && !(ev->value_mask & (CWWidth|CWHeight)))
435 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h);
443 wc.width = ev->width;
444 wc.height = ev->height;
445 wc.border_width = ev->border_width;
446 wc.sibling = ev->above;
447 wc.stack_mode = ev->detail;
448 XConfigureWindow(dpy, ev->window, ev->value_mask, &wc);
454 destroynotify(XEvent *e) {
456 XDestroyWindowEvent *ev = &e->xdestroywindow;
458 if((c = getclient(ev->window)))
466 for(tc = &clients; *tc && *tc != c; tc = &(*tc)->next);
471 detachstack(Client *c) {
474 for(tc = &stack; *tc && *tc != c; tc = &(*tc)->snext);
479 die(const char *errstr, ...) {
482 va_start(ap, errstr);
483 vfprintf(stderr, errstr, ap);
491 unsigned int i, occ = 0, urg = 0;
495 for(c = clients; c; c = c->next) {
502 for(i = 0; i < LENGTH(tags); i++) {
503 dc.w = TEXTW(tags[i]);
504 col = tagset[seltags] & 1 << i ? dc.sel : dc.norm;
505 drawtext(tags[i], col, urg & 1 << i);
506 drawsquare(sel && sel->tags & 1 << i, occ & 1 << i, urg & 1 << i, col);
511 drawtext(lt[sellt]->symbol, dc.norm, False);
522 drawtext(stext, dc.norm, False);
523 if((dc.w = dc.x - x) > bh) {
526 drawtext(sel->name, dc.sel, False);
527 drawsquare(sel->isfixed, sel->isfloating, False, dc.sel);
530 drawtext(NULL, dc.norm, False);
532 XCopyArea(dpy, dc.drawable, barwin, dc.gc, 0, 0, ww, bh, 0, 0);
537 drawsquare(Bool filled, Bool empty, Bool invert, unsigned long col[ColLast]) {
540 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
542 gcv.foreground = col[invert ? ColBG : ColFG];
543 XChangeGC(dpy, dc.gc, GCForeground, &gcv);
544 x = (dc.font.ascent + dc.font.descent + 2) / 4;
548 r.width = r.height = x + 1;
549 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
552 r.width = r.height = x;
553 XDrawRectangles(dpy, dc.drawable, dc.gc, &r, 1);
558 drawtext(const char *text, unsigned long col[ColLast], Bool invert) {
560 int i, x, y, h, len, olen;
561 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
563 XSetForeground(dpy, dc.gc, col[invert ? ColFG : ColBG]);
564 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
568 h = dc.font.ascent + dc.font.descent;
569 y = dc.y + (dc.h / 2) - (h / 2) + dc.font.ascent;
571 /* shorten text if necessary */
572 for(len = MIN(olen, sizeof buf); len && textnw(text, len) > dc.w - h; len--);
575 memcpy(buf, text, len);
577 for(i = len; i && i > len - 3; buf[--i] = '.');
578 XSetForeground(dpy, dc.gc, col[invert ? ColBG : ColFG]);
580 XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
582 XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
586 enternotify(XEvent *e) {
588 XCrossingEvent *ev = &e->xcrossing;
590 if((ev->mode != NotifyNormal || ev->detail == NotifyInferior) && ev->window != root)
592 if((c = getclient(ev->window)))
600 XExposeEvent *ev = &e->xexpose;
602 if(ev->count == 0 && (ev->window == barwin))
608 if(!c || !ISVISIBLE(c))
609 for(c = stack; c && !ISVISIBLE(c); c = c->snext);
610 if(sel && sel != c) {
611 grabbuttons(sel, False);
612 XSetWindowBorder(dpy, sel->win, dc.norm[ColBorder]);
619 grabbuttons(c, True);
620 XSetWindowBorder(dpy, c->win, dc.sel[ColBorder]);
621 XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
624 XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
630 focusin(XEvent *e) { /* there are some broken focus acquiring clients */
631 XFocusChangeEvent *ev = &e->xfocus;
633 if(sel && ev->window != sel->win)
634 XSetInputFocus(dpy, sel->win, RevertToPointerRoot, CurrentTime);
638 focusstack(const Arg *arg) {
639 Client *c = NULL, *i;
644 for(c = sel->next; c && !ISVISIBLE(c); c = c->next);
646 for(c = clients; c && !ISVISIBLE(c); c = c->next);
649 for(i = clients; i != sel; i = i->next)
653 for(; i; i = i->next)
664 getclient(Window w) {
667 for(c = clients; c && c->win != w; c = c->next);
672 getcolor(const char *colstr) {
673 Colormap cmap = DefaultColormap(dpy, screen);
676 if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
677 die("error, cannot allocate color '%s'\n", colstr);
685 unsigned char *p = NULL;
686 unsigned long n, extra;
689 status = XGetWindowProperty(dpy, w, wmatom[WMState], 0L, 2L, False, wmatom[WMState],
690 &real, &format, &n, &extra, (unsigned char **)&p);
691 if(status != Success)
700 gettextprop(Window w, Atom atom, char *text, unsigned int size) {
705 if(!text || size == 0)
708 XGetTextProperty(dpy, w, &name, atom);
711 if(name.encoding == XA_STRING)
712 strncpy(text, (char *)name.value, size - 1);
714 if(XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success
716 strncpy(text, *list, size - 1);
717 XFreeStringList(list);
720 text[size - 1] = '\0';
726 grabbuttons(Client *c, Bool focused) {
730 unsigned int modifiers[] = { 0, LockMask, numlockmask, numlockmask|LockMask };
731 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
733 for(i = 0; i < LENGTH(buttons); i++)
734 if(buttons[i].click == ClkClientWin)
735 for(j = 0; j < LENGTH(modifiers); j++)
736 XGrabButton(dpy, buttons[i].button, buttons[i].mask | modifiers[j], c->win, False, BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
738 XGrabButton(dpy, AnyButton, AnyModifier, c->win, False,
739 BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
748 unsigned int modifiers[] = { 0, LockMask, numlockmask, numlockmask|LockMask };
751 XUngrabKey(dpy, AnyKey, AnyModifier, root);
752 for(i = 0; i < LENGTH(keys); i++) {
753 if((code = XKeysymToKeycode(dpy, keys[i].keysym)))
754 for(j = 0; j < LENGTH(modifiers); j++)
755 XGrabKey(dpy, code, keys[i].mod | modifiers[j], root,
756 True, GrabModeAsync, GrabModeAsync);
762 initfont(const char *fontstr) {
763 char *def, **missing;
767 dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
770 fprintf(stderr, "dwm: missing fontset: %s\n", missing[n]);
771 XFreeStringList(missing);
774 XFontSetExtents *font_extents;
775 XFontStruct **xfonts;
777 dc.font.ascent = dc.font.descent = 0;
778 font_extents = XExtentsOfFontSet(dc.font.set);
779 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
780 for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
781 dc.font.ascent = MAX(dc.font.ascent, (*xfonts)->ascent);
782 dc.font.descent = MAX(dc.font.descent,(*xfonts)->descent);
787 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr))
788 && !(dc.font.xfont = XLoadQueryFont(dpy, "fixed")))
789 die("error, cannot load font: '%s'\n", fontstr);
790 dc.font.ascent = dc.font.xfont->ascent;
791 dc.font.descent = dc.font.xfont->descent;
793 dc.font.height = dc.font.ascent + dc.font.descent;
797 isprotodel(Client *c) {
802 if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
803 for(i = 0; !ret && i < n; i++)
804 if(protocols[i] == wmatom[WMDelete])
812 keypress(XEvent *e) {
818 keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
819 for(i = 0; i < LENGTH(keys); i++)
820 if(keysym == keys[i].keysym
821 && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state)
823 keys[i].func(&(keys[i].arg));
827 killclient(const Arg *arg) {
832 if(isprotodel(sel)) {
833 ev.type = ClientMessage;
834 ev.xclient.window = sel->win;
835 ev.xclient.message_type = wmatom[WMProtocols];
836 ev.xclient.format = 32;
837 ev.xclient.data.l[0] = wmatom[WMDelete];
838 ev.xclient.data.l[1] = CurrentTime;
839 XSendEvent(dpy, sel->win, False, NoEventMask, &ev);
842 XKillClient(dpy, sel->win);
846 manage(Window w, XWindowAttributes *wa) {
848 Client *c, *t = NULL;
852 if(!(c = malloc(sizeof(Client))))
853 die("fatal: could not malloc() %u bytes\n", sizeof(Client));
862 c->oldbw = wa->border_width;
863 if(c->w == sw && c->h == sh) {
869 if(c->x + WIDTH(c) > sx + sw)
870 c->x = sx + sw - WIDTH(c);
871 if(c->y + HEIGHT(c) > sy + sh)
872 c->y = sy + sh - HEIGHT(c);
873 c->x = MAX(c->x, sx);
874 /* only fix client y-offset, if the client center might cover the bar */
875 c->y = MAX(c->y, ((by == 0) && (c->x + (c->w / 2) >= wx) && (c->x + (c->w / 2) < wx + ww)) ? bh : sy);
879 wc.border_width = c->bw;
880 XConfigureWindow(dpy, w, CWBorderWidth, &wc);
881 XSetWindowBorder(dpy, w, dc.norm[ColBorder]);
882 configure(c); /* propagates border_width, if size doesn't change */
884 XSelectInput(dpy, w, EnterWindowMask|FocusChangeMask|PropertyChangeMask|StructureNotifyMask);
885 grabbuttons(c, False);
887 if(XGetTransientForHint(dpy, w, &trans))
888 t = getclient(trans);
894 c->isfloating = trans != None || c->isfixed;
896 XRaiseWindow(dpy, c->win);
899 XMoveResizeWindow(dpy, c->win, c->x + 2 * sw, c->y, c->w, c->h); /* some windows require this */
900 XMapWindow(dpy, c->win);
901 setclientstate(c, NormalState);
906 mappingnotify(XEvent *e) {
907 XMappingEvent *ev = &e->xmapping;
909 XRefreshKeyboardMapping(ev);
910 if(ev->request == MappingKeyboard)
915 maprequest(XEvent *e) {
916 static XWindowAttributes wa;
917 XMapRequestEvent *ev = &e->xmaprequest;
919 if(!XGetWindowAttributes(dpy, ev->window, &wa))
921 if(wa.override_redirect)
923 if(!getclient(ev->window))
924 manage(ev->window, &wa);
931 for(c = nexttiled(clients); c; c = nexttiled(c->next))
932 resize(c, wx, wy, ww - 2 * c->bw, wh - 2 * c->bw, resizehints);
936 movemouse(const Arg *arg) {
937 int x, y, ocx, ocy, di, nx, ny;
948 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
949 None, cursor[CurMove], CurrentTime) != GrabSuccess)
951 XQueryPointer(dpy, root, &dummy, &dummy, &x, &y, &di, &di, &dui);
955 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
957 case ConfigureRequest:
960 handler[ev.type](&ev);
963 nx = ocx + (ev.xmotion.x - x);
964 ny = ocy + (ev.xmotion.y - y);
965 if(snap && nx >= wx && nx <= wx + ww
966 && ny >= wy && ny <= wy + wh) {
967 if(abs(wx - nx) < snap)
969 else if(abs((wx + ww) - (nx + WIDTH(c))) < snap)
970 nx = wx + ww - WIDTH(c);
971 if(abs(wy - ny) < snap)
973 else if(abs((wy + wh) - (ny + HEIGHT(c))) < snap)
974 ny = wy + wh - HEIGHT(c);
975 if(!c->isfloating && lt[sellt]->arrange && (abs(nx - c->x) > snap || abs(ny - c->y) > snap))
976 togglefloating(NULL);
978 if(!lt[sellt]->arrange || c->isfloating)
979 resize(c, nx, ny, c->w, c->h, False);
983 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);
1127 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
1129 case ConfigureRequest:
1132 handler[ev.type](&ev);
1135 nw = MAX(ev.xmotion.x - ocx - 2*c->bw + 1, 1);
1136 nh = MAX(ev.xmotion.y - ocy - 2*c->bw + 1, 1);
1138 if(snap && nw >= wx && nw <= wx + ww
1139 && nh >= wy && nh <= wy + wh) {
1140 if(!c->isfloating && lt[sellt]->arrange
1141 && (abs(nw - c->w) > snap || abs(nh - c->h) > snap))
1142 togglefloating(NULL);
1144 if(!lt[sellt]->arrange || c->isfloating)
1145 resize(c, c->x, c->y, nw, nh, True);
1149 while(ev.type != ButtonRelease);
1152 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->bw - 1, c->h + c->bw - 1);
1153 XUngrabPointer(dpy, CurrentTime);
1154 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1166 if(sel->isfloating || !lt[sellt]->arrange)
1167 XRaiseWindow(dpy, sel->win);
1168 if(lt[sellt]->arrange) {
1169 wc.stack_mode = Below;
1170 wc.sibling = barwin;
1171 for(c = stack; c; c = c->snext)
1172 if(!c->isfloating && ISVISIBLE(c)) {
1173 XConfigureWindow(dpy, c->win, CWSibling|CWStackMode, &wc);
1174 wc.sibling = c->win;
1178 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1184 char sbuf[sizeof stext];
1187 unsigned int len, offset;
1190 /* main event loop, also reads status text from stdin */
1192 xfd = ConnectionNumber(dpy);
1194 len = sizeof stext - 1;
1195 sbuf[len] = stext[len] = '\0'; /* 0-terminator is never touched */
1199 FD_SET(STDIN_FILENO, &rd);
1201 if(select(xfd + 1, &rd, NULL, NULL, NULL) == -1) {
1204 die("select failed\n");
1206 if(FD_ISSET(STDIN_FILENO, &rd)) {
1207 switch((r = read(STDIN_FILENO, sbuf + offset, len - offset))) {
1209 strncpy(stext, strerror(errno), len);
1213 strncpy(stext, "EOF", 4);
1217 for(p = sbuf + offset; r > 0; p++, r--, offset++)
1218 if(*p == '\n' || *p == '\0') {
1220 strncpy(stext, sbuf, len);
1221 p += r - 1; /* p is sbuf + offset + r - 1 */
1222 for(r = 0; *(p - r) && *(p - r) != '\n'; r++);
1225 memmove(sbuf, p - r + 1, r);
1232 while(XPending(dpy)) {
1233 XNextEvent(dpy, &ev);
1234 if(handler[ev.type])
1235 (handler[ev.type])(&ev); /* call handler */
1242 unsigned int i, num;
1243 Window d1, d2, *wins = NULL;
1244 XWindowAttributes wa;
1246 if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1247 for(i = 0; i < num; i++) {
1248 if(!XGetWindowAttributes(dpy, wins[i], &wa)
1249 || wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1251 if(wa.map_state == IsViewable || getstate(wins[i]) == IconicState)
1252 manage(wins[i], &wa);
1254 for(i = 0; i < num; i++) { /* now the transients */
1255 if(!XGetWindowAttributes(dpy, wins[i], &wa))
1257 if(XGetTransientForHint(dpy, wins[i], &d1)
1258 && (wa.map_state == IsViewable || getstate(wins[i]) == IconicState))
1259 manage(wins[i], &wa);
1267 setclientstate(Client *c, long state) {
1268 long data[] = {state, None};
1270 XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1271 PropModeReplace, (unsigned char *)data, 2);
1275 setlayout(const Arg *arg) {
1276 if(!arg || !arg->v || arg->v != lt[sellt])
1279 lt[sellt] = (Layout *)arg->v;
1286 /* arg > 1.0 will set mfact absolutly */
1288 setmfact(const Arg *arg) {
1291 if(!arg || !lt[sellt]->arrange)
1293 f = arg->f < 1.0 ? arg->f + mfact : arg->f - 1.0;
1294 if(f < 0.1 || f > 0.9)
1304 XSetWindowAttributes wa;
1307 screen = DefaultScreen(dpy);
1308 root = RootWindow(dpy, screen);
1312 sw = DisplayWidth(dpy, screen);
1313 sh = DisplayHeight(dpy, screen);
1314 bh = dc.h = dc.font.height + 2;
1315 lt[0] = &layouts[0];
1316 lt[1] = &layouts[1 % LENGTH(layouts)];
1320 wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1321 wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1322 wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1323 netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1324 netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1327 wa.cursor = cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1328 cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1329 cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1331 /* init appearance */
1332 dc.norm[ColBorder] = getcolor(normbordercolor);
1333 dc.norm[ColBG] = getcolor(normbgcolor);
1334 dc.norm[ColFG] = getcolor(normfgcolor);
1335 dc.sel[ColBorder] = getcolor(selbordercolor);
1336 dc.sel[ColBG] = getcolor(selbgcolor);
1337 dc.sel[ColFG] = getcolor(selfgcolor);
1338 dc.drawable = XCreatePixmap(dpy, root, DisplayWidth(dpy, screen), bh, DefaultDepth(dpy, screen));
1339 dc.gc = XCreateGC(dpy, root, 0, 0);
1340 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
1342 XSetFont(dpy, dc.gc, dc.font.xfont->fid);
1345 for(blw = i = 0; LENGTH(layouts) > 1 && i < LENGTH(layouts); i++) {
1346 w = TEXTW(layouts[i].symbol);
1350 wa.override_redirect = 1;
1351 wa.background_pixmap = ParentRelative;
1352 wa.event_mask = ButtonPressMask|ExposureMask;
1354 barwin = XCreateWindow(dpy, root, wx, by, ww, bh, 0, DefaultDepth(dpy, screen),
1355 CopyFromParent, DefaultVisual(dpy, screen),
1356 CWOverrideRedirect|CWBackPixmap|CWEventMask, &wa);
1357 XDefineCursor(dpy, barwin, cursor[CurNormal]);
1358 XMapRaised(dpy, barwin);
1359 strcpy(stext, "dwm-"VERSION);
1362 /* EWMH support per view */
1363 XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1364 PropModeReplace, (unsigned char *) netatom, NetLast);
1366 /* select for events */
1367 wa.event_mask = SubstructureRedirectMask|SubstructureNotifyMask|ButtonPressMask
1368 |EnterWindowMask|LeaveWindowMask|StructureNotifyMask;
1369 XChangeWindowAttributes(dpy, root, CWEventMask|CWCursor, &wa);
1370 XSelectInput(dpy, root, wa.event_mask);
1376 showhide(Client *c) {
1379 if(ISVISIBLE(c)) { /* show clients top down */
1380 XMoveWindow(dpy, c->win, c->x, c->y);
1381 if(!lt[sellt]->arrange || c->isfloating)
1382 resize(c, c->x, c->y, c->w, c->h, True);
1385 else { /* hide clients bottom up */
1387 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
1392 spawn(const Arg *arg) {
1393 /* The double-fork construct avoids zombie processes and keeps the code
1394 * clean from stupid signal handlers. */
1398 close(ConnectionNumber(dpy));
1400 execvp(((char **)arg->v)[0], (char **)arg->v);
1401 fprintf(stderr, "dwm: execvp %s", ((char **)arg->v)[0]);
1410 tag(const Arg *arg) {
1411 if(sel && arg->ui & TAGMASK) {
1412 sel->tags = arg->ui & TAGMASK;
1418 textnw(const char *text, unsigned int len) {
1422 XmbTextExtents(dc.font.set, text, len, NULL, &r);
1425 return XTextWidth(dc.font.xfont, text, len);
1434 for(n = 0, c = nexttiled(clients); c; c = nexttiled(c->next), n++);
1439 c = nexttiled(clients);
1441 resize(c, wx, wy, (n == 1 ? ww : mw) - 2 * c->bw, wh - 2 * c->bw, resizehints);
1447 x = (wx + mw > c->x + c->w) ? c->x + c->w + 2 * c->bw : wx + mw;
1449 w = (wx + mw > c->x + c->w) ? wx + ww - x : ww - mw;
1454 for(i = 0, c = nexttiled(c->next); c; c = nexttiled(c->next), i++) {
1455 resize(c, x, y, w - 2 * c->bw, /* remainder */ ((i + 1 == n)
1456 ? wy + wh - y - 2 * c->bw : h - 2 * c->bw), resizehints);
1458 y = c->y + HEIGHT(c);
1463 togglebar(const Arg *arg) {
1471 togglefloating(const Arg *arg) {
1474 sel->isfloating = !sel->isfloating || sel->isfixed;
1476 resize(sel, sel->x, sel->y, sel->w, sel->h, True);
1481 toggletag(const Arg *arg) {
1487 mask = sel->tags ^ (arg->ui & TAGMASK);
1495 toggleview(const Arg *arg) {
1496 unsigned int mask = tagset[seltags] ^ (arg->ui & TAGMASK);
1499 tagset[seltags] = mask;
1505 unmanage(Client *c) {
1508 wc.border_width = c->oldbw;
1509 /* The server grab construct avoids race conditions. */
1511 XSetErrorHandler(xerrordummy);
1512 XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
1517 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1518 setclientstate(c, WithdrawnState);
1521 XSetErrorHandler(xerror);
1527 unmapnotify(XEvent *e) {
1529 XUnmapEvent *ev = &e->xunmap;
1531 if((c = getclient(ev->window)))
1537 if(dc.drawable != 0)
1538 XFreePixmap(dpy, dc.drawable);
1539 dc.drawable = XCreatePixmap(dpy, root, ww, bh, DefaultDepth(dpy, screen));
1540 XMoveResizeWindow(dpy, barwin, wx, by, ww, bh);
1547 XineramaScreenInfo *info = NULL;
1549 /* window area geometry */
1550 if(XineramaIsActive(dpy) && (info = XineramaQueryScreens(dpy, &n))) {
1555 if(XQueryPointer(dpy, root, &dummy, &dummy, &x, &y, &di, &di, &dui))
1556 for(i = 0; i < n; i++)
1557 if(INRECT(x, y, info[i].x_org, info[i].y_org, info[i].width, info[i].height))
1561 wy = showbar && topbar ? info[i].y_org + bh : info[i].y_org;
1563 wh = showbar ? info[i].height - bh : info[i].height;
1570 wy = showbar && topbar ? sy + bh : sy;
1572 wh = showbar ? sh - bh : sh;
1576 by = showbar ? (topbar ? wy - bh : wy + wh) : -bh;
1580 updatenumlockmask(void) {
1582 XModifierKeymap *modmap;
1585 modmap = XGetModifierMapping(dpy);
1586 for(i = 0; i < 8; i++)
1587 for(j = 0; j < modmap->max_keypermod; j++)
1588 if(modmap->modifiermap[i * modmap->max_keypermod + j] == XKeysymToKeycode(dpy, XK_Num_Lock))
1589 numlockmask = (1 << i);
1590 XFreeModifiermap(modmap);
1594 updatesizehints(Client *c) {
1598 if(!XGetWMNormalHints(dpy, c->win, &size, &msize))
1599 /* size is uninitialized, ensure that size.flags aren't used */
1601 if(size.flags & PBaseSize) {
1602 c->basew = size.base_width;
1603 c->baseh = size.base_height;
1605 else if(size.flags & PMinSize) {
1606 c->basew = size.min_width;
1607 c->baseh = size.min_height;
1610 c->basew = c->baseh = 0;
1611 if(size.flags & PResizeInc) {
1612 c->incw = size.width_inc;
1613 c->inch = size.height_inc;
1616 c->incw = c->inch = 0;
1617 if(size.flags & PMaxSize) {
1618 c->maxw = size.max_width;
1619 c->maxh = size.max_height;
1622 c->maxw = c->maxh = 0;
1623 if(size.flags & PMinSize) {
1624 c->minw = size.min_width;
1625 c->minh = size.min_height;
1627 else if(size.flags & PBaseSize) {
1628 c->minw = size.base_width;
1629 c->minh = size.base_height;
1632 c->minw = c->minh = 0;
1633 if(size.flags & PAspect) {
1634 c->mina = (float)size.min_aspect.y / (float)size.min_aspect.x;
1635 c->maxa = (float)size.max_aspect.x / (float)size.max_aspect.y;
1638 c->maxa = c->mina = 0.0;
1639 c->isfixed = (c->maxw && c->minw && c->maxh && c->minh
1640 && c->maxw == c->minw && c->maxh == c->minh);
1644 updatetitle(Client *c) {
1645 if(!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
1646 gettextprop(c->win, XA_WM_NAME, c->name, sizeof c->name);
1650 updatewmhints(Client *c) {
1653 if((wmh = XGetWMHints(dpy, c->win))) {
1654 if(ISVISIBLE(c) && wmh->flags & XUrgencyHint) {
1655 wmh->flags &= ~XUrgencyHint;
1656 XSetWMHints(dpy, c->win, wmh);
1659 c->isurgent = (wmh->flags & XUrgencyHint) ? True : False;
1666 view(const Arg *arg) {
1667 if((arg->ui & TAGMASK) == tagset[seltags])
1669 seltags ^= 1; /* toggle sel tagset */
1670 if(arg->ui & TAGMASK)
1671 tagset[seltags] = arg->ui & TAGMASK;
1675 /* There's no way to check accesses to destroyed windows, thus those cases are
1676 * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
1677 * default error handler, which may call exit. */
1679 xerror(Display *dpy, XErrorEvent *ee) {
1680 if(ee->error_code == BadWindow
1681 || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1682 || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1683 || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1684 || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1685 || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1686 || (ee->request_code == X_GrabButton && ee->error_code == BadAccess)
1687 || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1688 || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1690 fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1691 ee->request_code, ee->error_code);
1692 return xerrorxlib(dpy, ee); /* may call exit */
1696 xerrordummy(Display *dpy, XErrorEvent *ee) {
1700 /* Startup Error handler to check if another window manager
1701 * is already running. */
1703 xerrorstart(Display *dpy, XErrorEvent *ee) {
1709 zoom(const Arg *arg) {
1712 if(!lt[sellt]->arrange || lt[sellt]->arrange == monocle || (sel && sel->isfloating))
1714 if(c == nexttiled(clients))
1715 if(!c || !(c = nexttiled(c->next)))
1724 main(int argc, char *argv[]) {
1725 if(argc == 2 && !strcmp("-v", argv[1]))
1726 die("dwm-"VERSION", © 2006-2008 dwm engineers, see LICENSE for details\n");
1728 die("usage: dwm [-v]\n");
1730 if(!setlocale(LC_CTYPE, "") || !XSupportsLocale())
1731 fprintf(stderr, "warning: no locale support\n");
1733 if(!(dpy = XOpenDisplay(0)))
1734 die("dwm: cannot open display\n");