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().
32 #include <sys/select.h>
33 #include <sys/types.h>
35 #include <X11/cursorfont.h>
36 #include <X11/keysym.h>
37 #include <X11/Xatom.h>
39 #include <X11/Xproto.h>
40 #include <X11/Xutil.h>
42 #include <X11/extensions/Xinerama.h>
46 #define BUTTONMASK (ButtonPressMask|ButtonReleaseMask)
47 #define CLEANMASK(mask) (mask & ~(numlockmask|LockMask))
48 #define INRECT(X,Y,RX,RY,RW,RH) ((X) >= (RX) && (X) < (RX) + (RW) && (Y) >= (RY) && (Y) < (RY) + (RH))
49 #define ISVISIBLE(x) (x->tags & tagset[seltags])
50 #define LENGTH(x) (sizeof x / sizeof x[0])
51 #define MAX(a, b) ((a) > (b) ? (a) : (b))
52 #define MIN(a, b) ((a) < (b) ? (a) : (b))
54 #define MOUSEMASK (BUTTONMASK|PointerMotionMask)
55 #define TAGMASK ((int)((1LL << LENGTH(tags)) - 1))
56 #define TEXTW(x) (textnw(x, strlen(x)) + dc.font.height)
59 enum { CurNormal, CurResize, CurMove, CurLast }; /* cursor */
60 enum { ColBorder, ColFG, ColBG, ColLast }; /* color */
61 enum { NetSupported, NetWMName, NetLast }; /* EWMH atoms */
62 enum { WMProtocols, WMDelete, WMName, WMState, WMLast };/* default atoms */
63 enum { ClkTagBar, ClkLtSymbol, ClkStatusText, ClkWinTitle,
64 ClkClientWin, ClkRootWin, ClkLast }; /* clicks */
77 void (*func)(const Arg *arg);
81 typedef struct Client Client;
86 int basew, baseh, incw, inch, maxw, maxh, minw, minh;
89 Bool isfixed, isfloating, isurgent;
97 unsigned long norm[ColLast];
98 unsigned long sel[ColLast];
108 } DC; /* draw context */
113 void (*func)(const Arg *);
119 void (*arrange)(void);
124 const char *instance;
130 /* function declarations */
131 static void applyrules(Client *c);
132 static void arrange(void);
133 static void attach(Client *c);
134 static void attachstack(Client *c);
135 static void buttonpress(XEvent *e);
136 static void checkotherwm(void);
137 static void cleanup(void);
138 static void clearurgent(void);
139 static void configure(Client *c);
140 static void configurenotify(XEvent *e);
141 static void configurerequest(XEvent *e);
142 static void destroynotify(XEvent *e);
143 static void detach(Client *c);
144 static void detachstack(Client *c);
145 static void die(const char *errstr, ...);
146 static void drawbar(void);
147 static void drawsquare(Bool filled, Bool empty, Bool invert, unsigned long col[ColLast]);
148 static void drawtext(const char *text, unsigned long col[ColLast], Bool invert);
149 static void enternotify(XEvent *e);
150 static void expose(XEvent *e);
151 static void focus(Client *c);
152 static void focusin(XEvent *e);
153 static void focusstack(const Arg *arg);
154 static Client *getclient(Window w);
155 static unsigned long getcolor(const char *colstr);
156 static long getstate(Window w);
157 static Bool gettextprop(Window w, Atom atom, char *text, unsigned int size);
158 static void grabbuttons(Client *c, Bool focused);
159 static void grabkeys(void);
160 static void initfont(const char *fontstr);
161 static void initmodmap(void);
162 static Bool isprotodel(Client *c);
163 static void keypress(XEvent *e);
164 static void killclient(const Arg *arg);
165 static void manage(Window w, XWindowAttributes *wa);
166 static void mappingnotify(XEvent *e);
167 static void maprequest(XEvent *e);
168 static void monocle(void);
169 static void movemouse(const Arg *arg);
170 static Client *nexttiled(Client *c);
171 static void propertynotify(XEvent *e);
172 static void quit(const Arg *arg);
173 static void resize(Client *c, int x, int y, int w, int h, Bool sizehints);
174 static void resizemouse(const Arg *arg);
175 static void restack(void);
176 static void run(void);
177 static void scan(void);
178 static void setclientstate(Client *c, long state);
179 static void setlayout(const Arg *arg);
180 static void setmfact(const Arg *arg);
181 static void setup(void);
182 static void spawn(const Arg *arg);
183 static void tag(const Arg *arg);
184 static int textnw(const char *text, unsigned int len);
185 static void tile(void);
186 static void togglebar(const Arg *arg);
187 static void togglefloating(const Arg *arg);
188 static void toggletag(const Arg *arg);
189 static void toggleview(const Arg *arg);
190 static void unmanage(Client *c);
191 static void unmapnotify(XEvent *e);
192 static void updatebar(void);
193 static void updategeom(void);
194 static void updatesizehints(Client *c);
195 static void updatetitle(Client *c);
196 static void updatewmhints(Client *c);
197 static void view(const Arg *arg);
198 static int xerror(Display *dpy, XErrorEvent *ee);
199 static int xerrordummy(Display *dpy, XErrorEvent *ee);
200 static int xerrorstart(Display *dpy, XErrorEvent *ee);
201 static void zoom(const Arg *arg);
204 static char stext[256];
206 static int sx, sy, sw, sh; /* X display screen geometry x, y, width, height */
207 static int by, bh, blw; /* bar geometry y, height and layout symbol width */
208 static int wx, wy, ww, wh; /* window area geometry x, y, width, height, bar excluded */
209 static unsigned int seltags = 0, sellt = 0;
210 static int (*xerrorxlib)(Display *, XErrorEvent *);
211 static unsigned int numlockmask = 0;
212 static void (*handler[LASTEvent]) (XEvent *) = {
213 [ButtonPress] = buttonpress,
214 [ConfigureRequest] = configurerequest,
215 [ConfigureNotify] = configurenotify,
216 [DestroyNotify] = destroynotify,
217 [EnterNotify] = enternotify,
220 [KeyPress] = keypress,
221 [MappingNotify] = mappingnotify,
222 [MapRequest] = maprequest,
223 [PropertyNotify] = propertynotify,
224 [UnmapNotify] = unmapnotify
226 static Atom wmatom[WMLast], netatom[NetLast];
228 static Bool running = True;
229 static unsigned int tagset[] = {1, 1}; /* after start, first tag is selected */
230 static Client *clients = NULL;
231 static Client *sel = NULL;
232 static Client *stack = NULL;
233 static Cursor cursor[CurLast];
236 static Layout *lt[] = { NULL, NULL };
237 static Window root, barwin;
238 /* configuration, allows nested code to access above variables */
241 /* compile-time check if all tags fit into an unsigned int bit array. */
242 struct NumTags { char limitexceeded[sizeof(unsigned int) * 8 < LENGTH(tags) ? -1 : 1]; };
244 /* function implementations */
246 applyrules(Client *c) {
249 XClassHint ch = { 0 };
252 XGetClassHint(dpy, c->win, &ch);
253 for(i = 0; i < LENGTH(rules); i++) {
255 if((!r->title || strstr(c->name, r->title))
256 && (!r->class || (ch.res_class && strstr(ch.res_class, r->class)))
257 && (!r->instance || (ch.res_name && strstr(ch.res_name, r->instance)))) {
258 c->isfloating = r->isfloating;
259 c->tags |= r->tags & TAGMASK;
267 c->tags = tagset[seltags];
274 for(c = clients; c; c = c->next)
276 XMoveWindow(dpy, c->win, c->x, c->y);
277 if(!lt[sellt]->arrange || c->isfloating)
278 resize(c, c->x, c->y, c->w, c->h, True);
281 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
285 if(lt[sellt]->arrange)
286 lt[sellt]->arrange();
297 attachstack(Client *c) {
303 buttonpress(XEvent *e) {
304 unsigned int i, x, click;
307 XButtonPressedEvent *ev = &e->xbutton;
310 if(ev->window == barwin) {
312 do x += TEXTW(tags[i]); while(ev->x >= x && ++i < LENGTH(tags));
313 if(i < LENGTH(tags)) {
317 else if(ev->x < x + blw)
319 else if(ev->x > wx + ww - TEXTW(stext))
320 click = ClkStatusText;
324 else if((c = getclient(ev->window))) {
326 click = ClkClientWin;
329 for(i = 0; i < LENGTH(buttons); i++)
330 if(click == buttons[i].click && buttons[i].func && buttons[i].button == ev->button
331 && CLEANMASK(buttons[i].mask) == CLEANMASK(ev->state))
332 buttons[i].func(click == ClkTagBar ? &arg : &buttons[i].arg);
338 XSetErrorHandler(xerrorstart);
340 /* this causes an error if some other window manager is running */
341 XSelectInput(dpy, DefaultRootWindow(dpy), SubstructureRedirectMask);
344 die("dwm: another window manager is already running\n");
345 XSetErrorHandler(NULL);
346 xerrorxlib = XSetErrorHandler(xerror);
353 Layout foo = { "", NULL };
361 XFreeFontSet(dpy, dc.font.set);
363 XFreeFont(dpy, dc.font.xfont);
364 XUngrabKey(dpy, AnyKey, AnyModifier, root);
365 XFreePixmap(dpy, dc.drawable);
367 XFreeCursor(dpy, cursor[CurNormal]);
368 XFreeCursor(dpy, cursor[CurResize]);
369 XFreeCursor(dpy, cursor[CurMove]);
370 XDestroyWindow(dpy, barwin);
372 XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime);
380 for(c = clients; c; c = c->next)
381 if(ISVISIBLE(c) && c->isurgent) {
383 if (!(wmh = XGetWMHints(dpy, c->win)))
386 wmh->flags &= ~XUrgencyHint;
387 XSetWMHints(dpy, c->win, wmh);
393 configure(Client *c) {
396 ce.type = ConfigureNotify;
404 ce.border_width = c->bw;
406 ce.override_redirect = False;
407 XSendEvent(dpy, c->win, False, StructureNotifyMask, (XEvent *)&ce);
411 configurenotify(XEvent *e) {
412 XConfigureEvent *ev = &e->xconfigure;
414 if(ev->window == root && (ev->width != sw || ev->height != sh)) {
424 configurerequest(XEvent *e) {
426 XConfigureRequestEvent *ev = &e->xconfigurerequest;
429 if((c = getclient(ev->window))) {
430 if(ev->value_mask & CWBorderWidth)
431 c->bw = ev->border_width;
432 else if(c->isfloating || !lt[sellt]->arrange) {
433 if(ev->value_mask & CWX)
435 if(ev->value_mask & CWY)
437 if(ev->value_mask & CWWidth)
439 if(ev->value_mask & CWHeight)
441 if((c->x - sx + c->w) > sw && c->isfloating)
442 c->x = sx + (sw / 2 - c->w / 2); /* center in x direction */
443 if((c->y - sy + c->h) > sh && c->isfloating)
444 c->y = sy + (sh / 2 - c->h / 2); /* center in y direction */
445 if((ev->value_mask & (CWX|CWY)) && !(ev->value_mask & (CWWidth|CWHeight)))
448 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h);
456 wc.width = ev->width;
457 wc.height = ev->height;
458 wc.border_width = ev->border_width;
459 wc.sibling = ev->above;
460 wc.stack_mode = ev->detail;
461 XConfigureWindow(dpy, ev->window, ev->value_mask, &wc);
467 destroynotify(XEvent *e) {
469 XDestroyWindowEvent *ev = &e->xdestroywindow;
471 if((c = getclient(ev->window)))
479 for(tc = &clients; *tc && *tc != c; tc = &(*tc)->next);
484 detachstack(Client *c) {
487 for(tc = &stack; *tc && *tc != c; tc = &(*tc)->snext);
492 die(const char *errstr, ...) {
495 va_start(ap, errstr);
496 vfprintf(stderr, errstr, ap);
504 unsigned int i, occ = 0, urg = 0;
508 for(c = clients; c; c = c->next) {
515 for(i = 0; i < LENGTH(tags); i++) {
516 dc.w = TEXTW(tags[i]);
517 col = tagset[seltags] & 1 << i ? dc.sel : dc.norm;
518 drawtext(tags[i], col, urg & 1 << i);
519 drawsquare(sel && sel->tags & 1 << i, occ & 1 << i, urg & 1 << i, col);
524 drawtext(lt[sellt]->symbol, dc.norm, False);
535 drawtext(stext, dc.norm, False);
536 if((dc.w = dc.x - x) > bh) {
539 drawtext(sel->name, dc.sel, False);
540 drawsquare(sel->isfixed, sel->isfloating, False, dc.sel);
543 drawtext(NULL, dc.norm, False);
545 XCopyArea(dpy, dc.drawable, barwin, dc.gc, 0, 0, ww, bh, 0, 0);
550 drawsquare(Bool filled, Bool empty, Bool invert, unsigned long col[ColLast]) {
553 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
555 gcv.foreground = col[invert ? ColBG : ColFG];
556 XChangeGC(dpy, dc.gc, GCForeground, &gcv);
557 x = (dc.font.ascent + dc.font.descent + 2) / 4;
561 r.width = r.height = x + 1;
562 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
565 r.width = r.height = x;
566 XDrawRectangles(dpy, dc.drawable, dc.gc, &r, 1);
571 drawtext(const char *text, unsigned long col[ColLast], Bool invert) {
573 int i, x, y, h, len, olen;
574 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
576 XSetForeground(dpy, dc.gc, col[invert ? ColFG : ColBG]);
577 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
581 h = dc.font.ascent + dc.font.descent;
582 y = dc.y + (dc.h / 2) - (h / 2) + dc.font.ascent;
584 /* shorten text if necessary */
585 for(len = MIN(olen, sizeof buf); len && textnw(text, len) > dc.w - h; len--);
588 memcpy(buf, text, len);
590 for(i = len; i && i > len - 3; buf[--i] = '.');
591 XSetForeground(dpy, dc.gc, col[invert ? ColBG : ColFG]);
593 XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
595 XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
599 enternotify(XEvent *e) {
601 XCrossingEvent *ev = &e->xcrossing;
603 if((ev->mode != NotifyNormal || ev->detail == NotifyInferior) && ev->window != root)
605 if((c = getclient(ev->window)))
613 XExposeEvent *ev = &e->xexpose;
615 if(ev->count == 0 && (ev->window == barwin))
621 if(!c || !ISVISIBLE(c))
622 for(c = stack; c && !ISVISIBLE(c); c = c->snext);
623 if(sel && sel != c) {
624 grabbuttons(sel, False);
625 XSetWindowBorder(dpy, sel->win, dc.norm[ColBorder]);
630 grabbuttons(c, True);
631 XSetWindowBorder(dpy, c->win, dc.sel[ColBorder]);
632 XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
635 XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
641 focusin(XEvent *e) { /* there are some broken focus acquiring clients */
642 XFocusChangeEvent *ev = &e->xfocus;
644 if(sel && ev->window != sel->win)
645 XSetInputFocus(dpy, sel->win, RevertToPointerRoot, CurrentTime);
649 focusstack(const Arg *arg) {
650 Client *c = NULL, *i;
655 for(c = sel->next; c && !ISVISIBLE(c); c = c->next);
657 for(c = clients; c && !ISVISIBLE(c); c = c->next);
660 for(i = clients; i != sel; i = i->next)
664 for(; i; i = i->next)
675 getclient(Window w) {
678 for(c = clients; c && c->win != w; c = c->next);
683 getcolor(const char *colstr) {
684 Colormap cmap = DefaultColormap(dpy, screen);
687 if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
688 die("error, cannot allocate color '%s'\n", colstr);
696 unsigned char *p = NULL;
697 unsigned long n, extra;
700 status = XGetWindowProperty(dpy, w, wmatom[WMState], 0L, 2L, False, wmatom[WMState],
701 &real, &format, &n, &extra, (unsigned char **)&p);
702 if(status != Success)
711 gettextprop(Window w, Atom atom, char *text, unsigned int size) {
716 if(!text || size == 0)
719 XGetTextProperty(dpy, w, &name, atom);
722 if(name.encoding == XA_STRING)
723 strncpy(text, (char *)name.value, size - 1);
725 if(XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success
727 strncpy(text, *list, size - 1);
728 XFreeStringList(list);
731 text[size - 1] = '\0';
737 grabbuttons(Client *c, Bool focused) {
739 unsigned int modifiers[] = { 0, LockMask, numlockmask, numlockmask|LockMask };
741 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
743 for(i = 0; i < LENGTH(buttons); i++)
744 if(buttons[i].click == ClkClientWin)
745 for(j = 0; j < LENGTH(modifiers); j++)
746 XGrabButton(dpy, buttons[i].button, buttons[i].mask | modifiers[j], c->win, False, BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
748 XGrabButton(dpy, AnyButton, AnyModifier, c->win, False,
749 BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
755 unsigned int modifiers[] = { 0, LockMask, numlockmask, numlockmask|LockMask };
758 XUngrabKey(dpy, AnyKey, AnyModifier, root);
759 for(i = 0; i < LENGTH(keys); i++) {
760 code = XKeysymToKeycode(dpy, keys[i].keysym);
761 for(j = 0; j < LENGTH(modifiers); j++)
762 XGrabKey(dpy, code, keys[i].mod | modifiers[j], root, True,
763 GrabModeAsync, GrabModeAsync);
768 initfont(const char *fontstr) {
769 char *def, **missing;
774 XFreeFontSet(dpy, dc.font.set);
775 dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
778 fprintf(stderr, "dwm: missing fontset: %s\n", missing[n]);
779 XFreeStringList(missing);
782 XFontSetExtents *font_extents;
783 XFontStruct **xfonts;
785 dc.font.ascent = dc.font.descent = 0;
786 font_extents = XExtentsOfFontSet(dc.font.set);
787 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
788 for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
789 dc.font.ascent = MAX(dc.font.ascent, (*xfonts)->ascent);
790 dc.font.descent = MAX(dc.font.descent,(*xfonts)->descent);
796 XFreeFont(dpy, dc.font.xfont);
797 dc.font.xfont = NULL;
798 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr))
799 && !(dc.font.xfont = XLoadQueryFont(dpy, "fixed")))
800 die("error, cannot load font: '%s'\n", fontstr);
801 dc.font.ascent = dc.font.xfont->ascent;
802 dc.font.descent = dc.font.xfont->descent;
804 dc.font.height = dc.font.ascent + dc.font.descent;
810 XModifierKeymap *modmap;
812 modmap = XGetModifierMapping(dpy);
813 for(i = 0; i < 8; i++)
814 for(j = 0; j < modmap->max_keypermod; j++)
815 if(modmap->modifiermap[i * modmap->max_keypermod + j] == XKeysymToKeycode(dpy, XK_Num_Lock))
816 numlockmask = (1 << i);
817 XFreeModifiermap(modmap);
821 isprotodel(Client *c) {
826 if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
827 for(i = 0; !ret && i < n; i++)
828 if(protocols[i] == wmatom[WMDelete])
836 keypress(XEvent *e) {
842 keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
843 for(i = 0; i < LENGTH(keys); i++)
844 if(keysym == keys[i].keysym
845 && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state)
847 keys[i].func(&(keys[i].arg));
851 killclient(const Arg *arg) {
856 if(isprotodel(sel)) {
857 ev.type = ClientMessage;
858 ev.xclient.window = sel->win;
859 ev.xclient.message_type = wmatom[WMProtocols];
860 ev.xclient.format = 32;
861 ev.xclient.data.l[0] = wmatom[WMDelete];
862 ev.xclient.data.l[1] = CurrentTime;
863 XSendEvent(dpy, sel->win, False, NoEventMask, &ev);
866 XKillClient(dpy, sel->win);
870 manage(Window w, XWindowAttributes *wa) {
871 Client *c, *t = NULL;
875 if(!(c = calloc(1, sizeof(Client))))
876 die("fatal: could not calloc() %u bytes\n", sizeof(Client));
884 c->oldbw = wa->border_width;
885 if(c->w == sw && c->h == sh) {
891 if(c->x + c->w + 2 * c->bw > sx + sw)
892 c->x = sx + sw - c->w - 2 * c->bw;
893 if(c->y + c->h + 2 * c->bw > sy + sh)
894 c->y = sy + sh - c->h - 2 * c->bw;
895 c->x = MAX(c->x, sx);
896 /* only fix client y-offset, if the client center might cover the bar */
897 c->y = MAX(c->y, ((by == 0) && (c->x + (c->w / 2) >= wx) && (c->x + (c->w / 2) < wx + ww)) ? bh : sy);
901 wc.border_width = c->bw;
902 XConfigureWindow(dpy, w, CWBorderWidth, &wc);
903 XSetWindowBorder(dpy, w, dc.norm[ColBorder]);
904 configure(c); /* propagates border_width, if size doesn't change */
906 XSelectInput(dpy, w, EnterWindowMask|FocusChangeMask|PropertyChangeMask|StructureNotifyMask);
907 grabbuttons(c, False);
909 if(XGetTransientForHint(dpy, w, &trans))
910 t = getclient(trans);
916 c->isfloating = trans != None || c->isfixed;
918 XRaiseWindow(dpy, c->win);
921 XMoveResizeWindow(dpy, c->win, c->x + 2 * sw, c->y, c->w, c->h); /* some windows require this */
922 XMapWindow(dpy, c->win);
923 setclientstate(c, NormalState);
928 mappingnotify(XEvent *e) {
929 XMappingEvent *ev = &e->xmapping;
931 XRefreshKeyboardMapping(ev);
932 if(ev->request == MappingKeyboard) {
939 maprequest(XEvent *e) {
940 static XWindowAttributes wa;
941 XMapRequestEvent *ev = &e->xmaprequest;
943 if(!XGetWindowAttributes(dpy, ev->window, &wa))
945 if(wa.override_redirect)
947 if(!getclient(ev->window))
948 manage(ev->window, &wa);
955 for(c = nexttiled(clients); c; c = nexttiled(c->next))
956 resize(c, wx, wy, ww - 2 * c->bw, wh - 2 * c->bw, resizehints);
960 movemouse(const Arg *arg) {
961 int x, y, ocx, ocy, di, nx, ny;
972 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
973 None, cursor[CurMove], CurrentTime) != GrabSuccess)
975 XQueryPointer(dpy, root, &dummy, &dummy, &x, &y, &di, &di, &dui);
977 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
979 case ConfigureRequest:
982 handler[ev.type](&ev);
986 nx = ocx + (ev.xmotion.x - x);
987 ny = ocy + (ev.xmotion.y - y);
988 if(snap && nx >= wx && nx <= wx + ww
989 && ny >= wy && ny <= wy + wh) {
990 if(abs(wx - nx) < snap)
992 else if(abs((wx + ww) - (nx + c->w + 2 * c->bw)) < snap)
993 nx = wx + ww - c->w - 2 * c->bw;
994 if(abs(wy - ny) < snap)
996 else if(abs((wy + wh) - (ny + c->h + 2 * c->bw)) < snap)
997 ny = wy + wh - c->h - 2 * c->bw;
998 if(!c->isfloating && lt[sellt]->arrange && (abs(nx - c->x) > snap || abs(ny - c->y) > snap))
999 togglefloating(NULL);
1001 if(!lt[sellt]->arrange || c->isfloating)
1002 resize(c, nx, ny, c->w, c->h, False);
1006 while(ev.type != ButtonRelease);
1007 XUngrabPointer(dpy, CurrentTime);
1011 nexttiled(Client *c) {
1012 for(; c && (c->isfloating || !ISVISIBLE(c)); c = c->next);
1017 propertynotify(XEvent *e) {
1020 XPropertyEvent *ev = &e->xproperty;
1022 if(ev->state == PropertyDelete)
1023 return; /* ignore */
1024 if((c = getclient(ev->window))) {
1027 case XA_WM_TRANSIENT_FOR:
1028 XGetTransientForHint(dpy, c->win, &trans);
1029 if(!c->isfloating && (c->isfloating = (getclient(trans) != NULL)))
1032 case XA_WM_NORMAL_HINTS:
1040 if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
1049 quit(const Arg *arg) {
1050 readin = running = False;
1054 resize(Client *c, int x, int y, int w, int h, Bool sizehints) {
1058 /* set minimum possible */
1062 /* temporarily remove base dimensions */
1066 /* adjust for aspect limits */
1067 if(c->mina > 0 && c->maxa > 0) {
1068 if(c->maxa < (float) w/h)
1070 else if(c->mina > (float) h/w)
1074 /* adjust for increment value */
1080 /* restore base dimensions */
1084 w = MAX(w, c->minw);
1085 h = MAX(h, c->minh);
1088 w = MIN(w, c->maxw);
1091 h = MIN(h, c->maxh);
1093 if(w <= 0 || h <= 0)
1096 x = sw - w - 2 * c->bw;
1098 y = sh - h - 2 * c->bw;
1099 if(x + w + 2 * c->bw < sx)
1101 if(y + h + 2 * c->bw < sy)
1107 if(c->x != x || c->y != y || c->w != w || c->h != h) {
1110 c->w = wc.width = w;
1111 c->h = wc.height = h;
1112 wc.border_width = c->bw;
1113 XConfigureWindow(dpy, c->win,
1114 CWX|CWY|CWWidth|CWHeight|CWBorderWidth, &wc);
1121 resizemouse(const Arg *arg) {
1132 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1133 None, cursor[CurResize], CurrentTime) != GrabSuccess)
1135 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->bw - 1, c->h + c->bw - 1);
1137 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
1139 case ConfigureRequest:
1142 handler[ev.type](&ev);
1146 nw = MAX(ev.xmotion.x - ocx - 2 * c->bw + 1, 1);
1147 nh = MAX(ev.xmotion.y - ocy - 2 * c->bw + 1, 1);
1149 if(snap && nw >= wx && nw <= wx + ww
1150 && nh >= wy && nh <= wy + wh) {
1151 if(!c->isfloating && lt[sellt]->arrange
1152 && (abs(nw - c->w) > snap || abs(nh - c->h) > snap))
1153 togglefloating(NULL);
1155 if(!lt[sellt]->arrange || c->isfloating)
1156 resize(c, c->x, c->y, nw, nh, True);
1160 while(ev.type != ButtonRelease);
1161 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->bw - 1, c->h + c->bw - 1);
1162 XUngrabPointer(dpy, CurrentTime);
1163 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1175 if(sel->isfloating || !lt[sellt]->arrange)
1176 XRaiseWindow(dpy, sel->win);
1177 if(lt[sellt]->arrange) {
1178 wc.stack_mode = Below;
1179 wc.sibling = barwin;
1180 for(c = stack; c; c = c->snext)
1181 if(!c->isfloating && ISVISIBLE(c)) {
1182 XConfigureWindow(dpy, c->win, CWSibling|CWStackMode, &wc);
1183 wc.sibling = c->win;
1187 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1193 char sbuf[sizeof stext];
1196 unsigned int len, offset;
1199 /* main event loop, also reads status text from stdin */
1201 xfd = ConnectionNumber(dpy);
1203 len = sizeof stext - 1;
1204 sbuf[len] = stext[len] = '\0'; /* 0-terminator is never touched */
1208 FD_SET(STDIN_FILENO, &rd);
1210 if(select(xfd + 1, &rd, NULL, NULL, NULL) == -1) {
1213 die("select failed\n");
1215 if(FD_ISSET(STDIN_FILENO, &rd)) {
1216 switch((r = read(STDIN_FILENO, sbuf + offset, len - offset))) {
1218 strncpy(stext, strerror(errno), len);
1222 strncpy(stext, "EOF", 4);
1226 for(p = sbuf + offset; r > 0; p++, r--, offset++)
1227 if(*p == '\n' || *p == '\0') {
1229 strncpy(stext, sbuf, len);
1230 p += r - 1; /* p is sbuf + offset + r - 1 */
1231 for(r = 0; *(p - r) && *(p - r) != '\n'; r++);
1234 memmove(sbuf, p - r + 1, r);
1241 while(XPending(dpy)) {
1242 XNextEvent(dpy, &ev);
1243 if(handler[ev.type])
1244 (handler[ev.type])(&ev); /* call handler */
1251 unsigned int i, num;
1252 Window d1, d2, *wins = NULL;
1253 XWindowAttributes wa;
1255 if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1256 for(i = 0; i < num; i++) {
1257 if(!XGetWindowAttributes(dpy, wins[i], &wa)
1258 || wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1260 if(wa.map_state == IsViewable || getstate(wins[i]) == IconicState)
1261 manage(wins[i], &wa);
1263 for(i = 0; i < num; i++) { /* now the transients */
1264 if(!XGetWindowAttributes(dpy, wins[i], &wa))
1266 if(XGetTransientForHint(dpy, wins[i], &d1)
1267 && (wa.map_state == IsViewable || getstate(wins[i]) == IconicState))
1268 manage(wins[i], &wa);
1276 setclientstate(Client *c, long state) {
1277 long data[] = {state, None};
1279 XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1280 PropModeReplace, (unsigned char *)data, 2);
1284 setlayout(const Arg *arg) {
1285 if(!arg || !arg->v || arg->v != lt[sellt])
1288 lt[sellt] = (Layout *)arg->v;
1295 /* arg > 1.0 will set mfact absolutly */
1297 setmfact(const Arg *arg) {
1300 if(!arg || !lt[sellt]->arrange)
1302 f = arg->f < 1.0 ? arg->f + mfact : arg->f - 1.0;
1303 if(f < 0.1 || f > 0.9)
1313 XSetWindowAttributes wa;
1316 screen = DefaultScreen(dpy);
1317 root = RootWindow(dpy, screen);
1321 sw = DisplayWidth(dpy, screen);
1322 sh = DisplayHeight(dpy, screen);
1323 bh = dc.h = dc.font.height + 2;
1324 lt[0] = &layouts[0];
1325 lt[1] = &layouts[1 % LENGTH(layouts)];
1329 wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1330 wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1331 wmatom[WMName] = XInternAtom(dpy, "WM_NAME", False);
1332 wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1333 netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1334 netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1337 wa.cursor = cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1338 cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1339 cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1341 /* init appearance */
1342 dc.norm[ColBorder] = getcolor(normbordercolor);
1343 dc.norm[ColBG] = getcolor(normbgcolor);
1344 dc.norm[ColFG] = getcolor(normfgcolor);
1345 dc.sel[ColBorder] = getcolor(selbordercolor);
1346 dc.sel[ColBG] = getcolor(selbgcolor);
1347 dc.sel[ColFG] = getcolor(selfgcolor);
1348 dc.drawable = XCreatePixmap(dpy, root, DisplayWidth(dpy, screen), bh, DefaultDepth(dpy, screen));
1349 dc.gc = XCreateGC(dpy, root, 0, 0);
1350 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
1352 XSetFont(dpy, dc.gc, dc.font.xfont->fid);
1355 for(blw = i = 0; LENGTH(layouts) > 1 && i < LENGTH(layouts); i++) {
1356 w = TEXTW(layouts[i].symbol);
1360 wa.override_redirect = 1;
1361 wa.background_pixmap = ParentRelative;
1362 wa.event_mask = ButtonPressMask|ExposureMask;
1364 barwin = XCreateWindow(dpy, root, wx, by, ww, bh, 0, DefaultDepth(dpy, screen),
1365 CopyFromParent, DefaultVisual(dpy, screen),
1366 CWOverrideRedirect|CWBackPixmap|CWEventMask, &wa);
1367 XDefineCursor(dpy, barwin, cursor[CurNormal]);
1368 XMapRaised(dpy, barwin);
1369 strcpy(stext, "dwm-"VERSION);
1372 /* EWMH support per view */
1373 XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1374 PropModeReplace, (unsigned char *) netatom, NetLast);
1376 /* select for events */
1377 wa.event_mask = SubstructureRedirectMask|SubstructureNotifyMask|ButtonPressMask
1378 |EnterWindowMask|LeaveWindowMask|StructureNotifyMask;
1379 XChangeWindowAttributes(dpy, root, CWEventMask|CWCursor, &wa);
1380 XSelectInput(dpy, root, wa.event_mask);
1387 spawn(const Arg *arg) {
1388 /* The double-fork construct avoids zombie processes and keeps the code
1389 * clean from stupid signal handlers. */
1393 close(ConnectionNumber(dpy));
1395 execvp(((char **)arg->v)[0], (char **)arg->v);
1396 fprintf(stderr, "dwm: execvp %s", ((char **)arg->v)[0]);
1405 tag(const Arg *arg) {
1406 if(sel && arg->ui & TAGMASK) {
1407 sel->tags = arg->ui & TAGMASK;
1413 textnw(const char *text, unsigned int len) {
1417 XmbTextExtents(dc.font.set, text, len, NULL, &r);
1420 return XTextWidth(dc.font.xfont, text, len);
1429 for(n = 0, c = nexttiled(clients); c; c = nexttiled(c->next), n++);
1434 c = nexttiled(clients);
1436 resize(c, wx, wy, (n == 1 ? ww : mw) - 2 * c->bw, wh - 2 * c->bw, resizehints);
1442 x = (wx + mw > c->x + c->w) ? c->x + c->w + 2 * c->bw : wx + mw;
1444 w = (wx + mw > c->x + c->w) ? wx + ww - x : ww - mw;
1449 for(i = 0, c = nexttiled(c->next); c; c = nexttiled(c->next), i++) {
1450 resize(c, x, y, w - 2 * c->bw, /* remainder */ ((i + 1 == n)
1451 ? (wy + wh) - y : h) - 2 * c->bw, resizehints);
1453 y = c->y + c->h + 2 * c->bw;
1458 togglebar(const Arg *arg) {
1466 togglefloating(const Arg *arg) {
1469 sel->isfloating = !sel->isfloating || sel->isfixed;
1471 resize(sel, sel->x, sel->y, sel->w, sel->h, True);
1476 toggletag(const Arg *arg) {
1482 mask = sel->tags ^ (arg->ui & TAGMASK);
1490 toggleview(const Arg *arg) {
1491 unsigned int mask = tagset[seltags] ^ (arg->ui & TAGMASK);
1494 tagset[seltags] = mask;
1501 unmanage(Client *c) {
1504 wc.border_width = c->oldbw;
1505 /* The server grab construct avoids race conditions. */
1507 XSetErrorHandler(xerrordummy);
1508 XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
1513 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1514 setclientstate(c, WithdrawnState);
1517 XSetErrorHandler(xerror);
1523 unmapnotify(XEvent *e) {
1525 XUnmapEvent *ev = &e->xunmap;
1527 if((c = getclient(ev->window)))
1533 if(dc.drawable != 0)
1534 XFreePixmap(dpy, dc.drawable);
1535 dc.drawable = XCreatePixmap(dpy, root, ww, bh, DefaultDepth(dpy, screen));
1536 XMoveResizeWindow(dpy, barwin, wx, by, ww, bh);
1543 XineramaScreenInfo *info = NULL;
1545 /* window area geometry */
1546 if(XineramaIsActive(dpy) && (info = XineramaQueryScreens(dpy, &n))) {
1551 if(XQueryPointer(dpy, root, &dummy, &dummy, &x, &y, &di, &di, &dui))
1552 for(i = 0; i < n; i++)
1553 if(INRECT(x, y, info[i].x_org, info[i].y_org, info[i].width, info[i].height))
1557 wy = showbar && topbar ? info[i].y_org + bh : info[i].y_org;
1559 wh = showbar ? info[i].height - bh : info[i].height;
1566 wy = showbar && topbar ? sy + bh : sy;
1568 wh = showbar ? sh - bh : sh;
1572 by = showbar ? (topbar ? wy - bh : wy + wh) : -bh;
1576 updatesizehints(Client *c) {
1580 XGetWMNormalHints(dpy, c->win, &size, &msize);
1581 if(size.flags & PBaseSize) {
1582 c->basew = size.base_width;
1583 c->baseh = size.base_height;
1585 else if(size.flags & PMinSize) {
1586 c->basew = size.min_width;
1587 c->baseh = size.min_height;
1590 c->basew = c->baseh = 0;
1591 if(size.flags & PResizeInc) {
1592 c->incw = size.width_inc;
1593 c->inch = size.height_inc;
1596 c->incw = c->inch = 0;
1597 if(size.flags & PMaxSize) {
1598 c->maxw = size.max_width;
1599 c->maxh = size.max_height;
1602 c->maxw = c->maxh = 0;
1603 if(size.flags & PMinSize) {
1604 c->minw = size.min_width;
1605 c->minh = size.min_height;
1607 else if(size.flags & PBaseSize) {
1608 c->minw = size.base_width;
1609 c->minh = size.base_height;
1612 c->minw = c->minh = 0;
1613 if(size.flags & PAspect) {
1614 c->mina = (float)size.min_aspect.y / (float)size.min_aspect.x;
1615 c->maxa = (float)size.max_aspect.x / (float)size.max_aspect.y;
1618 c->maxa = c->mina = 0.0;
1619 c->isfixed = (c->maxw && c->minw && c->maxh && c->minh
1620 && c->maxw == c->minw && c->maxh == c->minh);
1624 updatetitle(Client *c) {
1625 if(!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
1626 gettextprop(c->win, wmatom[WMName], c->name, sizeof c->name);
1630 updatewmhints(Client *c) {
1633 if((wmh = XGetWMHints(dpy, c->win))) {
1634 if(ISVISIBLE(c) && wmh->flags & XUrgencyHint) {
1635 wmh->flags &= ~XUrgencyHint;
1636 XSetWMHints(dpy, c->win, wmh);
1639 c->isurgent = (wmh->flags & XUrgencyHint) ? True : False;
1646 view(const Arg *arg) {
1647 if((arg->ui & TAGMASK) == tagset[seltags])
1649 seltags ^= 1; /* toggle sel tagset */
1650 if(arg->ui & TAGMASK)
1651 tagset[seltags] = arg->ui & TAGMASK;
1656 /* There's no way to check accesses to destroyed windows, thus those cases are
1657 * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
1658 * default error handler, which may call exit. */
1660 xerror(Display *dpy, XErrorEvent *ee) {
1661 if(ee->error_code == BadWindow
1662 || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1663 || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1664 || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1665 || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1666 || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1667 || (ee->request_code == X_GrabButton && ee->error_code == BadAccess)
1668 || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1669 || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1671 fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1672 ee->request_code, ee->error_code);
1673 return xerrorxlib(dpy, ee); /* may call exit */
1677 xerrordummy(Display *dpy, XErrorEvent *ee) {
1681 /* Startup Error handler to check if another window manager
1682 * is already running. */
1684 xerrorstart(Display *dpy, XErrorEvent *ee) {
1690 zoom(const Arg *arg) {
1693 if(!lt[sellt]->arrange || lt[sellt]->arrange == monocle || (sel && sel->isfloating))
1695 if(c == nexttiled(clients))
1696 if(!c || !(c = nexttiled(c->next)))
1705 main(int argc, char *argv[]) {
1706 if(argc == 2 && !strcmp("-v", argv[1]))
1707 die("dwm-"VERSION", © 2006-2008 dwm engineers, see LICENSE for details\n");
1709 die("usage: dwm [-v]\n");
1711 if(!XSupportsLocale())
1712 fprintf(stderr, "warning: no locale support\n");
1714 if(!(dpy = XOpenDisplay(0)))
1715 die("dwm: cannot open display\n");