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 MAX(a, b) ((a) > (b) ? (a) : (b))
48 #define MIN(a, b) ((a) < (b) ? (a) : (b))
49 #define BUTTONMASK (ButtonPressMask|ButtonReleaseMask)
50 #define CLEANMASK(mask) (mask & ~(numlockmask|LockMask))
51 #define LENGTH(x) (sizeof x / sizeof x[0])
53 #define MOUSEMASK (BUTTONMASK|PointerMotionMask)
54 #define SHCMD(cmd) { .v = (char*[]){ "/bin/sh", "-c", cmd, NULL } }
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 */
65 typedef unsigned int uint;
66 typedef unsigned long ulong;
67 typedef struct Client Client;
71 int basew, baseh, incw, inch, maxw, maxh, minw, minh;
74 Bool isbanned, isfixed, isfloating, ismoved, isurgent;
94 } DC; /* draw context */
106 void (*func)(const Arg *);
112 void (*arrange)(void);
117 const char *instance;
123 /* function declarations */
124 static void applyrules(Client *c);
125 static void arrange(void);
126 static void attach(Client *c);
127 static void attachstack(Client *c);
128 static void buttonpress(XEvent *e);
129 static void checkotherwm(void);
130 static void cleanup(void);
131 static void configure(Client *c);
132 static void configurenotify(XEvent *e);
133 static void configurerequest(XEvent *e);
134 static void destroynotify(XEvent *e);
135 static void detach(Client *c);
136 static void detachstack(Client *c);
137 static void drawbar(void);
138 static void drawsquare(Bool filled, Bool empty, Bool invert, ulong col[ColLast]);
139 static void drawtext(const char *text, ulong col[ColLast], Bool invert);
140 static void enternotify(XEvent *e);
141 static void eprint(const char *errstr, ...);
142 static void expose(XEvent *e);
143 static void focus(Client *c);
144 static void focusin(XEvent *e);
145 static void focusstack(const Arg *arg);
146 static Client *getclient(Window w);
147 static ulong getcolor(const char *colstr);
148 static long getstate(Window w);
149 static Bool gettextprop(Window w, Atom atom, char *text, uint size);
150 static void grabbuttons(Client *c, Bool focused);
151 static void grabkeys(void);
152 static void initfont(const char *fontstr);
153 static Bool isoccupied(uint t);
154 static Bool isprotodel(Client *c);
155 static Bool isurgent(uint t);
156 static void keypress(XEvent *e);
157 static void killclient(const Arg *arg);
158 static void manage(Window w, XWindowAttributes *wa);
159 static void mappingnotify(XEvent *e);
160 static void maprequest(XEvent *e);
161 static void movemouse(Client *c);
162 static Client *nexttiled(Client *c);
163 static void propertynotify(XEvent *e);
164 static void quit(const Arg *arg);
165 static void resize(Client *c, int x, int y, int w, int h, Bool sizehints);
166 static void resizemouse(Client *c);
167 static void restack(void);
168 static void run(void);
169 static void scan(void);
170 static void setclientstate(Client *c, long state);
171 static void setmfact(const Arg *arg);
172 static void setup(void);
173 static void spawn(const Arg *arg);
174 static void tag(const Arg *arg);
175 static int textnw(const char *text, uint len);
176 static void tile(void);
177 static void togglebar(const Arg *arg);
178 static void togglefloating(const Arg *arg);
179 static void togglelayout(const Arg *arg);
180 static void togglemax(const Arg *arg);
181 static void toggletag(const Arg *arg);
182 static void toggleview(const Arg *arg);
183 static void unmanage(Client *c);
184 static void unmapnotify(XEvent *e);
185 static void updatebar(void);
186 static void updategeom(void);
187 static void updatesizehints(Client *c);
188 static void updatetitle(Client *c);
189 static void updatewmhints(Client *c);
190 static void view(const Arg *arg);
191 static int xerror(Display *dpy, XErrorEvent *ee);
192 static int xerrordummy(Display *dpy, XErrorEvent *ee);
193 static int xerrorstart(Display *dpy, XErrorEvent *ee);
194 static void zoom(const Arg *arg);
197 static char stext[256];
198 static int screen, sx, sy, sw, sh;
199 static int by, bh, blw, wx, wy, ww, wh;
200 static uint seltags = 0;
201 static int (*xerrorxlib)(Display *, XErrorEvent *);
202 static uint numlockmask = 0;
203 static void (*handler[LASTEvent]) (XEvent *) = {
204 [ButtonPress] = buttonpress,
205 [ConfigureRequest] = configurerequest,
206 [ConfigureNotify] = configurenotify,
207 [DestroyNotify] = destroynotify,
208 [EnterNotify] = enternotify,
211 [KeyPress] = keypress,
212 [MappingNotify] = mappingnotify,
213 [MapRequest] = maprequest,
214 [PropertyNotify] = propertynotify,
215 [UnmapNotify] = unmapnotify
217 static Atom wmatom[WMLast], netatom[NetLast];
218 static Bool ismax = False;
219 static Bool otherwm, readin;
220 static Bool running = True;
221 static uint tagset[] = {1, 1}; /* after start, first tag is selected */
222 static Client *clients = NULL;
223 static Client *sel = NULL;
224 static Client *stack = NULL;
225 static Cursor cursor[CurLast];
228 static Window root, barwin;
230 /* configuration, allows nested code to access above variables */
233 static Layout *lt = layouts;
235 /* compile-time check if all tags fit into an uint bit array. */
236 struct NumTags { char limitexceeded[sizeof(uint) * 8 < LENGTH(tags) ? -1 : 1]; };
238 /* function implementations */
240 applyrules(Client *c) {
243 XClassHint ch = { 0 };
246 XGetClassHint(dpy, c->win, &ch);
247 for(i = 0; i < LENGTH(rules); i++) {
249 if((!r->title || strstr(c->name, r->title))
250 && (!r->class || (ch.res_class && strstr(ch.res_class, r->class)))
251 && (!r->instance || (ch.res_name && strstr(ch.res_name, r->instance)))) {
252 c->isfloating = r->isfloating;
253 c->tags |= r->tags & TAGMASK;
261 c->tags = tagset[seltags];
268 for(c = clients; c; c = c->next)
269 if(c->tags & tagset[seltags]) { /* is visible */
270 if(ismax && !c->isfixed) {
271 XMoveResizeWindow(dpy, c->win, wx, wy, ww - 2 * c->bw, wh - 2 * c->bw);
274 else if(!lt->arrange || c->isfloating)
275 resize(c, c->x, c->y, c->w, c->h, True);
278 else if(!c->isbanned) {
279 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
280 c->isbanned = c->ismoved = True;
284 if(lt->arrange && !ismax)
296 attachstack(Client *c) {
302 buttonpress(XEvent *e) {
306 XButtonPressedEvent *ev = &e->xbutton;
308 if(ev->window == barwin) {
310 for(i = 0; i < LENGTH(tags); i++) {
314 if(ev->button == Button1) {
315 if(ev->state & MODKEY)
320 else if(ev->button == Button3) {
321 if(ev->state & MODKEY)
322 toggletag((Arg*)&mask);
324 toggleview((Arg*)&mask);
329 if(ev->x < x + blw) {
330 if(ev->button == Button1)
332 else if(ev->button == Button3)
336 else if((c = getclient(ev->window))) {
338 if(CLEANMASK(ev->state) != MODKEY || (ismax && !c->isfixed))
340 if(ev->button == Button1)
342 else if(ev->button == Button2)
343 togglefloating(NULL);
344 else if(ev->button == Button3 && !c->isfixed)
352 XSetErrorHandler(xerrorstart);
354 /* this causes an error if some other window manager is running */
355 XSelectInput(dpy, DefaultRootWindow(dpy), SubstructureRedirectMask);
358 eprint("dwm: another window manager is already running\n");
359 XSetErrorHandler(NULL);
360 xerrorxlib = XSetErrorHandler(xerror);
367 Layout foo = { "", NULL };
375 XFreeFontSet(dpy, dc.font.set);
377 XFreeFont(dpy, dc.font.xfont);
378 XUngrabKey(dpy, AnyKey, AnyModifier, root);
379 XFreePixmap(dpy, dc.drawable);
381 XFreeCursor(dpy, cursor[CurNormal]);
382 XFreeCursor(dpy, cursor[CurResize]);
383 XFreeCursor(dpy, cursor[CurMove]);
384 XDestroyWindow(dpy, barwin);
386 XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime);
390 configure(Client *c) {
393 ce.type = ConfigureNotify;
401 ce.border_width = c->bw;
403 ce.override_redirect = False;
404 XSendEvent(dpy, c->win, False, StructureNotifyMask, (XEvent *)&ce);
408 configurenotify(XEvent *e) {
409 XConfigureEvent *ev = &e->xconfigure;
411 if(ev->window == root && (ev->width != sw || ev->height != sh)) {
421 configurerequest(XEvent *e) {
423 XConfigureRequestEvent *ev = &e->xconfigurerequest;
426 if((c = getclient(ev->window))) {
427 if(ev->value_mask & CWBorderWidth)
428 c->bw = ev->border_width;
429 if(ismax && !c->isbanned && !c->isfixed)
430 XMoveResizeWindow(dpy, c->win, wx, wy, ww - 2 * c->bw, wh + 2 * c->bw);
431 else if(c->isfloating || !lt->arrange) {
432 if(ev->value_mask & CWX)
434 if(ev->value_mask & CWY)
436 if(ev->value_mask & CWWidth)
438 if(ev->value_mask & CWHeight)
440 if((c->x - sx + c->w) > sw && c->isfloating)
441 c->x = sx + (sw / 2 - c->w / 2); /* center in x direction */
442 if((c->y - sy + c->h) > sh && c->isfloating)
443 c->y = sy + (sh / 2 - c->h / 2); /* center in y direction */
444 if((ev->value_mask & (CWX|CWY))
445 && !(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)))
480 for(i = clients; i->next != c; i = i->next);
490 detachstack(Client *c) {
493 for(tc = &stack; *tc && *tc != c; tc = &(*tc)->snext);
503 for(c = stack; c && c->isbanned; c = c->snext);
504 for(i = 0; i < LENGTH(tags); i++) {
505 dc.w = TEXTW(tags[i]);
506 if(tagset[seltags] & 1 << i) {
507 drawtext(tags[i], dc.sel, isurgent(i));
508 drawsquare(c && c->tags & 1 << i, isoccupied(i), isurgent(i), dc.sel);
511 drawtext(tags[i], dc.norm, isurgent(i));
512 drawsquare(c && c->tags & 1 << i, isoccupied(i), isurgent(i), dc.norm);
518 drawtext(lt->symbol, dc.norm, ismax);
529 drawtext(stext, dc.norm, False);
530 if((dc.w = dc.x - x) > bh) {
533 drawtext(c->name, dc.sel, False);
534 drawsquare(c->isfixed, c->isfloating, False, dc.sel);
537 drawtext(NULL, dc.norm, False);
539 XCopyArea(dpy, dc.drawable, barwin, dc.gc, 0, 0, ww, bh, 0, 0);
544 drawsquare(Bool filled, Bool empty, Bool invert, ulong col[ColLast]) {
547 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
549 gcv.foreground = col[invert ? ColBG : ColFG];
550 XChangeGC(dpy, dc.gc, GCForeground, &gcv);
551 x = (dc.font.ascent + dc.font.descent + 2) / 4;
555 r.width = r.height = x + 1;
556 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
559 r.width = r.height = x;
560 XDrawRectangles(dpy, dc.drawable, dc.gc, &r, 1);
565 drawtext(const char *text, ulong col[ColLast], Bool invert) {
566 int i, x, y, h, len, olen;
567 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
570 XSetForeground(dpy, dc.gc, col[invert ? ColFG : ColBG]);
571 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
575 len = MIN(olen, sizeof buf);
576 memcpy(buf, text, len);
577 h = dc.font.ascent + dc.font.descent;
578 y = dc.y + (dc.h / 2) - (h / 2) + dc.font.ascent;
580 /* shorten text if necessary */
581 for(; len && (i = textnw(buf, len)) > dc.w - h; len--);
585 for(i = len; i && i > len - 3; buf[--i] = '.');
586 XSetForeground(dpy, dc.gc, col[invert ? ColBG : ColFG]);
588 XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
590 XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
594 enternotify(XEvent *e) {
596 XCrossingEvent *ev = &e->xcrossing;
598 if((ev->mode != NotifyNormal || ev->detail == NotifyInferior) && ev->window != root)
600 if((c = getclient(ev->window)))
607 eprint(const char *errstr, ...) {
610 va_start(ap, errstr);
611 vfprintf(stderr, errstr, ap);
618 XExposeEvent *ev = &e->xexpose;
620 if(ev->count == 0 && (ev->window == barwin))
626 if(!c || c->isbanned)
627 for(c = stack; c && c->isbanned; c = c->snext);
628 if(sel && sel != c) {
629 grabbuttons(sel, False);
630 XSetWindowBorder(dpy, sel->win, dc.norm[ColBorder]);
635 grabbuttons(c, True);
636 XSetWindowBorder(dpy, c->win, dc.sel[ColBorder]);
637 XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
640 XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
646 focusin(XEvent *e) { /* there are some broken focus acquiring clients */
647 XFocusChangeEvent *ev = &e->xfocus;
649 if(sel && ev->window != sel->win)
650 XSetInputFocus(dpy, sel->win, RevertToPointerRoot, CurrentTime);
654 focusstack(const Arg *arg) {
655 Client *c = NULL, *i;
660 for(c = sel->next; c && c->isbanned; c = c->next);
662 for(c = clients; c && c->isbanned; c = c->next);
665 for(i = clients; i != sel; i = i->next)
669 for(; i; i = i->next)
680 getclient(Window w) {
683 for(c = clients; c && c->win != w; c = c->next);
688 getcolor(const char *colstr) {
689 Colormap cmap = DefaultColormap(dpy, screen);
692 if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
693 eprint("error, cannot allocate color '%s'\n", colstr);
701 unsigned char *p = NULL;
705 status = XGetWindowProperty(dpy, w, wmatom[WMState], 0L, 2L, False, wmatom[WMState],
706 &real, &format, &n, &extra, (unsigned char **)&p);
707 if(status != Success)
716 gettextprop(Window w, Atom atom, char *text, uint size) {
721 if(!text || size == 0)
724 XGetTextProperty(dpy, w, &name, atom);
727 if(name.encoding == XA_STRING)
728 strncpy(text, (char *)name.value, size - 1);
730 if(XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success
732 strncpy(text, *list, size - 1);
733 XFreeStringList(list);
736 text[size - 1] = '\0';
742 grabbuttons(Client *c, Bool focused) {
744 uint buttons[] = { Button1, Button2, Button3 };
745 uint modifiers[] = { MODKEY, MODKEY|LockMask, MODKEY|numlockmask, MODKEY|numlockmask|LockMask };
747 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
749 for(i = 0; i < LENGTH(buttons); i++)
750 for(j = 0; j < LENGTH(modifiers); j++)
751 XGrabButton(dpy, buttons[i], modifiers[j], c->win, False,
752 BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
754 XGrabButton(dpy, AnyButton, AnyModifier, c->win, False,
755 BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
762 XModifierKeymap *modmap;
764 /* init modifier map */
765 modmap = XGetModifierMapping(dpy);
766 for(i = 0; i < 8; i++)
767 for(j = 0; j < modmap->max_keypermod; j++) {
768 if(modmap->modifiermap[i * modmap->max_keypermod + j] == XKeysymToKeycode(dpy, XK_Num_Lock))
769 numlockmask = (1 << i);
771 XFreeModifiermap(modmap);
773 XUngrabKey(dpy, AnyKey, AnyModifier, root);
774 for(i = 0; i < LENGTH(keys); i++) {
775 code = XKeysymToKeycode(dpy, keys[i].keysym);
776 XGrabKey(dpy, code, keys[i].mod, root, True,
777 GrabModeAsync, GrabModeAsync);
778 XGrabKey(dpy, code, keys[i].mod|LockMask, root, True,
779 GrabModeAsync, GrabModeAsync);
780 XGrabKey(dpy, code, keys[i].mod|numlockmask, root, True,
781 GrabModeAsync, GrabModeAsync);
782 XGrabKey(dpy, code, keys[i].mod|numlockmask|LockMask, root, True,
783 GrabModeAsync, GrabModeAsync);
788 initfont(const char *fontstr) {
789 char *def, **missing;
794 XFreeFontSet(dpy, dc.font.set);
795 dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
798 fprintf(stderr, "dwm: missing fontset: %s\n", missing[n]);
799 XFreeStringList(missing);
802 XFontSetExtents *font_extents;
803 XFontStruct **xfonts;
805 dc.font.ascent = dc.font.descent = 0;
806 font_extents = XExtentsOfFontSet(dc.font.set);
807 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
808 for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
809 dc.font.ascent = MAX(dc.font.ascent, (*xfonts)->ascent);
810 dc.font.descent = MAX(dc.font.descent,(*xfonts)->descent);
816 XFreeFont(dpy, dc.font.xfont);
817 dc.font.xfont = NULL;
818 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr))
819 && !(dc.font.xfont = XLoadQueryFont(dpy, "fixed")))
820 eprint("error, cannot load font: '%s'\n", fontstr);
821 dc.font.ascent = dc.font.xfont->ascent;
822 dc.font.descent = dc.font.xfont->descent;
824 dc.font.height = dc.font.ascent + dc.font.descent;
831 for(c = clients; c; c = c->next)
838 isprotodel(Client *c) {
843 if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
844 for(i = 0; !ret && i < n; i++)
845 if(protocols[i] == wmatom[WMDelete])
856 for(c = clients; c; c = c->next)
857 if(c->isurgent && c->tags & 1 << t)
863 keypress(XEvent *e) {
869 keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
870 for(i = 0; i < LENGTH(keys); i++)
871 if(keysym == keys[i].keysym
872 && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state)
874 keys[i].func(&(keys[i].arg));
878 killclient(const Arg *arg) {
883 if(isprotodel(sel)) {
884 ev.type = ClientMessage;
885 ev.xclient.window = sel->win;
886 ev.xclient.message_type = wmatom[WMProtocols];
887 ev.xclient.format = 32;
888 ev.xclient.data.l[0] = wmatom[WMDelete];
889 ev.xclient.data.l[1] = CurrentTime;
890 XSendEvent(dpy, sel->win, False, NoEventMask, &ev);
893 XKillClient(dpy, sel->win);
897 manage(Window w, XWindowAttributes *wa) {
898 Client *c, *t = NULL;
903 if(!(c = calloc(1, sizeof(Client))))
904 eprint("fatal: could not calloc() %u bytes\n", sizeof(Client));
912 c->oldbw = wa->border_width;
913 if(c->w == sw && c->h == sh) {
916 c->bw = wa->border_width;
919 if(c->x + c->w + 2 * c->bw > sx + sw)
920 c->x = sx + sw - c->w - 2 * c->bw;
921 if(c->y + c->h + 2 * c->bw > sy + sh)
922 c->y = sy + sh - c->h - 2 * c->bw;
923 c->x = MAX(c->x, sx);
924 c->y = MAX(c->y, by == 0 ? bh : sy);
928 wc.border_width = c->bw;
929 XConfigureWindow(dpy, w, CWBorderWidth, &wc);
930 XSetWindowBorder(dpy, w, dc.norm[ColBorder]);
931 configure(c); /* propagates border_width, if size doesn't change */
933 XSelectInput(dpy, w, EnterWindowMask|FocusChangeMask|PropertyChangeMask|StructureNotifyMask);
934 grabbuttons(c, False);
936 if((rettrans = XGetTransientForHint(dpy, w, &trans) == Success))
937 for(t = clients; t && t->win != trans; t = t->next);
943 c->isfloating = (rettrans == Success) || c->isfixed;
945 XRaiseWindow(dpy, c->win);
948 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h); /* some windows require this */
949 XMapWindow(dpy, c->win);
950 setclientstate(c, NormalState);
955 mappingnotify(XEvent *e) {
956 XMappingEvent *ev = &e->xmapping;
958 XRefreshKeyboardMapping(ev);
959 if(ev->request == MappingKeyboard)
964 maprequest(XEvent *e) {
965 static XWindowAttributes wa;
966 XMapRequestEvent *ev = &e->xmaprequest;
968 if(!XGetWindowAttributes(dpy, ev->window, &wa))
970 if(wa.override_redirect)
972 if(!getclient(ev->window))
973 manage(ev->window, &wa);
977 movemouse(Client *c) {
978 int x1, y1, ocx, ocy, di, nx, ny;
986 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
987 None, cursor[CurMove], CurrentTime) != GrabSuccess)
989 XQueryPointer(dpy, root, &dummy, &dummy, &x1, &y1, &di, &di, &dui);
991 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
994 XUngrabPointer(dpy, CurrentTime);
996 case ConfigureRequest:
999 handler[ev.type](&ev);
1003 nx = ocx + (ev.xmotion.x - x1);
1004 ny = ocy + (ev.xmotion.y - y1);
1005 if(snap && nx >= wx && nx <= wx + ww
1006 && ny >= wy && ny <= wy + wh) {
1007 if(abs(wx - nx) < snap)
1009 else if(abs((wx + ww) - (nx + c->w + 2 * c->bw)) < snap)
1010 nx = wx + ww - c->w - 2 * c->bw;
1011 if(abs(wy - ny) < snap)
1013 else if(abs((wy + wh) - (ny + c->h + 2 * c->bw)) < snap)
1014 ny = wy + wh - c->h - 2 * c->bw;
1015 if(!c->isfloating && lt->arrange && (abs(nx - c->x) > snap || abs(ny - c->y) > snap))
1016 togglefloating(NULL);
1018 if(!lt->arrange || c->isfloating)
1019 resize(c, nx, ny, c->w, c->h, False);
1026 nexttiled(Client *c) {
1027 for(; c && (c->isfloating || c->isbanned); c = c->next);
1032 propertynotify(XEvent *e) {
1035 XPropertyEvent *ev = &e->xproperty;
1037 if(ev->state == PropertyDelete)
1038 return; /* ignore */
1039 if((c = getclient(ev->window))) {
1042 case XA_WM_TRANSIENT_FOR:
1043 XGetTransientForHint(dpy, c->win, &trans);
1044 if(!c->isfloating && (c->isfloating = (getclient(trans) != NULL)))
1047 case XA_WM_NORMAL_HINTS:
1055 if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
1064 quit(const Arg *arg) {
1065 readin = running = False;
1069 resize(Client *c, int x, int y, int w, int h, Bool sizehints) {
1073 /* set minimum possible */
1077 /* temporarily remove base dimensions */
1081 /* adjust for aspect limits */
1082 if(c->mina > 0 && c->maxa > 0) {
1083 if(c->maxa < (float) w/h)
1085 else if(c->mina > (float) h/w)
1089 /* adjust for increment value */
1095 /* restore base dimensions */
1099 w = MAX(w, c->minw);
1100 h = MAX(h, c->minh);
1103 w = MIN(w, c->maxw);
1106 h = MIN(h, c->maxh);
1108 if(w <= 0 || h <= 0)
1111 x = sw - w - 2 * c->bw;
1113 y = sh - h - 2 * c->bw;
1114 if(x + w + 2 * c->bw < sx)
1116 if(y + h + 2 * c->bw < sy)
1122 if(c->x != x || c->y != y || c->w != w || c->h != h || c->ismoved) {
1126 c->w = wc.width = w;
1127 c->h = wc.height = h;
1128 wc.border_width = c->bw;
1129 XConfigureWindow(dpy, c->win,
1130 CWX|CWY|CWWidth|CWHeight|CWBorderWidth, &wc);
1137 resizemouse(Client *c) {
1145 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1146 None, cursor[CurResize], CurrentTime) != GrabSuccess)
1148 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->bw - 1, c->h + c->bw - 1);
1150 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask , &ev);
1153 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0,
1154 c->w + c->bw - 1, c->h + c->bw - 1);
1155 XUngrabPointer(dpy, CurrentTime);
1156 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1158 case ConfigureRequest:
1161 handler[ev.type](&ev);
1165 nw = MAX(ev.xmotion.x - ocx - 2 * c->bw + 1, 1);
1166 nh = MAX(ev.xmotion.y - ocy - 2 * c->bw + 1, 1);
1168 if(snap && nw >= wx && nw <= wx + ww
1169 && nh >= wy && nh <= wy + wh) {
1170 if(!c->isfloating && lt->arrange
1171 && (abs(nw - c->w) > snap || abs(nh - c->h) > snap))
1172 togglefloating(NULL);
1174 if(!lt->arrange || c->isfloating)
1175 resize(c, c->x, c->y, nw, nh, True);
1190 if(ismax || sel->isfloating || !lt->arrange)
1191 XRaiseWindow(dpy, sel->win);
1192 if(!ismax && lt->arrange) {
1193 wc.stack_mode = Below;
1194 wc.sibling = barwin;
1195 for(c = stack; c; c = c->snext)
1196 if(!c->isfloating && !c->isbanned) {
1197 XConfigureWindow(dpy, c->win, CWSibling|CWStackMode, &wc);
1198 wc.sibling = c->win;
1202 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1208 char sbuf[sizeof stext];
1214 /* main event loop, also reads status text from stdin */
1216 xfd = ConnectionNumber(dpy);
1219 len = sizeof stext - 1;
1220 sbuf[len] = stext[len] = '\0'; /* 0-terminator is never touched */
1224 FD_SET(STDIN_FILENO, &rd);
1226 if(select(xfd + 1, &rd, NULL, NULL, NULL) == -1) {
1229 eprint("select failed\n");
1231 if(FD_ISSET(STDIN_FILENO, &rd)) {
1232 switch((r = read(STDIN_FILENO, sbuf + offset, len - offset))) {
1234 strncpy(stext, strerror(errno), len);
1238 strncpy(stext, "EOF", 4);
1242 for(p = sbuf + offset; r > 0; p++, r--, offset++)
1243 if(*p == '\n' || *p == '\0') {
1245 strncpy(stext, sbuf, len);
1246 p += r - 1; /* p is sbuf + offset + r - 1 */
1247 for(r = 0; *(p - r) && *(p - r) != '\n'; r++);
1250 memmove(sbuf, p - r + 1, r);
1257 while(XPending(dpy)) {
1258 XNextEvent(dpy, &ev);
1259 if(handler[ev.type])
1260 (handler[ev.type])(&ev); /* call handler */
1268 Window *wins, d1, d2;
1269 XWindowAttributes wa;
1272 if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1273 for(i = 0; i < num; i++) {
1274 if(!XGetWindowAttributes(dpy, wins[i], &wa)
1275 || wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1277 if(wa.map_state == IsViewable || getstate(wins[i]) == IconicState)
1278 manage(wins[i], &wa);
1280 for(i = 0; i < num; i++) { /* now the transients */
1281 if(!XGetWindowAttributes(dpy, wins[i], &wa))
1283 if(XGetTransientForHint(dpy, wins[i], &d1)
1284 && (wa.map_state == IsViewable || getstate(wins[i]) == IconicState))
1285 manage(wins[i], &wa);
1293 setclientstate(Client *c, long state) {
1294 long data[] = {state, None};
1296 XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1297 PropModeReplace, (unsigned char *)data, 2);
1300 /* arg > 1.0 will set mfact absolutly */
1302 setmfact(const Arg *arg) {
1305 if(!arg || !lt->arrange)
1307 f = arg->f < 1.0 ? arg->f + mfact : arg->f - 1.0;
1308 if(f < 0.1 || f > 0.9)
1318 XSetWindowAttributes wa;
1321 screen = DefaultScreen(dpy);
1322 root = RootWindow(dpy, screen);
1326 sw = DisplayWidth(dpy, screen);
1327 sh = DisplayHeight(dpy, screen);
1328 bh = dc.font.height + 2;
1332 wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1333 wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1334 wmatom[WMName] = XInternAtom(dpy, "WM_NAME", False);
1335 wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1336 netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1337 netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1340 wa.cursor = cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1341 cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1342 cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1344 /* init appearance */
1345 dc.norm[ColBorder] = getcolor(NORMBORDERCOLOR);
1346 dc.norm[ColBG] = getcolor(NORMBGCOLOR);
1347 dc.norm[ColFG] = getcolor(NORMFGCOLOR);
1348 dc.sel[ColBorder] = getcolor(SELBORDERCOLOR);
1349 dc.sel[ColBG] = getcolor(SELBGCOLOR);
1350 dc.sel[ColFG] = getcolor(SELFGCOLOR);
1353 dc.drawable = XCreatePixmap(dpy, root, DisplayWidth(dpy, screen), bh, DefaultDepth(dpy, screen));
1354 dc.gc = XCreateGC(dpy, root, 0, 0);
1355 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
1357 XSetFont(dpy, dc.gc, dc.font.xfont->fid);
1360 for(blw = i = 0; LENGTH(layouts) > 1 && i < LENGTH(layouts); i++) {
1361 w = TEXTW(layouts[i].symbol);
1365 wa.override_redirect = 1;
1366 wa.background_pixmap = ParentRelative;
1367 wa.event_mask = ButtonPressMask|ExposureMask;
1369 barwin = XCreateWindow(dpy, root, wx, by, ww, bh, 0, DefaultDepth(dpy, screen),
1370 CopyFromParent, DefaultVisual(dpy, screen),
1371 CWOverrideRedirect|CWBackPixmap|CWEventMask, &wa);
1372 XDefineCursor(dpy, barwin, cursor[CurNormal]);
1373 XMapRaised(dpy, barwin);
1374 strcpy(stext, "dwm-"VERSION);
1377 /* EWMH support per view */
1378 XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1379 PropModeReplace, (unsigned char *) netatom, NetLast);
1381 /* select for events */
1382 wa.event_mask = SubstructureRedirectMask|SubstructureNotifyMask
1383 |EnterWindowMask|LeaveWindowMask|StructureNotifyMask;
1384 XChangeWindowAttributes(dpy, root, CWEventMask|CWCursor, &wa);
1385 XSelectInput(dpy, root, wa.event_mask);
1393 spawn(const Arg *arg) {
1394 /* The double-fork construct avoids zombie processes and keeps the code
1395 * clean from stupid signal handlers. */
1399 close(ConnectionNumber(dpy));
1401 execvp(((char **)arg->v)[0], (char **)arg->v);
1402 fprintf(stderr, "dwm: execvp %s", ((char **)arg->v)[0]);
1411 tag(const Arg *arg) {
1412 if(sel && arg->ui & TAGMASK) {
1413 sel->tags = arg->ui & TAGMASK;
1419 textnw(const char *text, uint len) {
1423 XmbTextExtents(dc.font.set, text, len, NULL, &r);
1426 return XTextWidth(dc.font.xfont, text, len);
1435 for(n = 0, c = nexttiled(clients); c; c = nexttiled(c->next), n++);
1440 c = nexttiled(clients);
1442 resize(c, wx, wy, (n == 1 ? ww : mw) - 2 * c->bw, wh - 2 * c->bw, resizehints);
1448 x = (wx + mw > c->x + c->w) ? c->x + c->w + 2 * c->bw : wx + mw;
1450 w = (wx + mw > c->x + c->w) ? wx + ww - x : ww - mw;
1455 for(i = 0, c = nexttiled(c->next); c; c = nexttiled(c->next), i++) {
1456 resize(c, x, y, w - 2 * c->bw, /* remainder */ ((i + 1 == n)
1457 ? (wy + wh) - y : h) - 2 * c->bw, resizehints);
1459 y = c->y + c->h + 2 * c->bw;
1464 togglebar(const Arg *arg) {
1472 togglefloating(const Arg *arg) {
1475 sel->isfloating = !sel->isfloating || sel->isfixed;
1477 resize(sel, sel->x, sel->y, sel->w, sel->h, True);
1482 togglelayout(const Arg *arg) {
1484 lt = (Layout *)arg->v;
1485 else if(++lt == &layouts[LENGTH(layouts)])
1494 togglemax(const Arg *arg) {
1500 toggletag(const Arg *arg) {
1501 if(sel && (sel->tags ^= (arg->ui & TAGMASK)))
1506 toggleview(const Arg *arg) {
1507 if((tagset[seltags] ^= (arg->ui & TAGMASK)))
1512 unmanage(Client *c) {
1515 wc.border_width = c->oldbw;
1516 /* The server grab construct avoids race conditions. */
1518 XSetErrorHandler(xerrordummy);
1519 XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
1524 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1525 setclientstate(c, WithdrawnState);
1528 XSetErrorHandler(xerror);
1534 unmapnotify(XEvent *e) {
1536 XUnmapEvent *ev = &e->xunmap;
1538 if((c = getclient(ev->window)))
1544 if(dc.drawable != 0)
1545 XFreePixmap(dpy, dc.drawable);
1546 dc.drawable = XCreatePixmap(dpy, root, ww, bh, DefaultDepth(dpy, screen));
1547 XMoveResizeWindow(dpy, barwin, wx, by, ww, bh);
1554 XineramaScreenInfo *info = NULL;
1556 /* window area geometry */
1557 if(XineramaIsActive(dpy)) {
1558 info = XineramaQueryScreens(dpy, &i);
1560 wy = showbar && topbar ? info[0].y_org + bh : info[0].y_org;
1562 wh = showbar ? info[0].height - bh : info[0].height;
1569 wy = showbar && topbar ? sy + bh : sy;
1571 wh = showbar ? sh - bh : sh;
1575 by = showbar ? (topbar ? wy - bh : wy + wh) : -bh;
1579 updatesizehints(Client *c) {
1583 XGetWMNormalHints(dpy, c->win, &size, &msize);
1584 if(size.flags & PBaseSize) {
1585 c->basew = size.base_width;
1586 c->baseh = size.base_height;
1588 else if(size.flags & PMinSize) {
1589 c->basew = size.min_width;
1590 c->baseh = size.min_height;
1593 c->basew = c->baseh = 0;
1594 if(size.flags & PResizeInc) {
1595 c->incw = size.width_inc;
1596 c->inch = size.height_inc;
1599 c->incw = c->inch = 0;
1600 if(size.flags & PMaxSize) {
1601 c->maxw = size.max_width;
1602 c->maxh = size.max_height;
1605 c->maxw = c->maxh = 0;
1606 if(size.flags & PMinSize) {
1607 c->minw = size.min_width;
1608 c->minh = size.min_height;
1610 else if(size.flags & PBaseSize) {
1611 c->minw = size.base_width;
1612 c->minh = size.base_height;
1615 c->minw = c->minh = 0;
1616 if(size.flags & PAspect) {
1617 c->mina = (float)size.min_aspect.y / (float)size.min_aspect.x;
1618 c->maxa = (float)size.max_aspect.x / (float)size.max_aspect.y;
1621 c->maxa = c->mina = 0.0;
1622 c->isfixed = (c->maxw && c->minw && c->maxh && c->minh
1623 && c->maxw == c->minw && c->maxh == c->minh);
1627 updatetitle(Client *c) {
1628 if(!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
1629 gettextprop(c->win, wmatom[WMName], c->name, sizeof c->name);
1633 updatewmhints(Client *c) {
1636 if((wmh = XGetWMHints(dpy, c->win))) {
1638 sel->isurgent = False;
1640 c->isurgent = (wmh->flags & XUrgencyHint) ? True : False;
1646 view(const Arg *arg) {
1647 seltags ^= 1; /* toggle sel tagset */
1648 if(arg && (arg->ui & TAGMASK))
1649 tagset[seltags] = arg->i & TAGMASK;
1653 /* There's no way to check accesses to destroyed windows, thus those cases are
1654 * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
1655 * default error handler, which may call exit. */
1657 xerror(Display *dpy, XErrorEvent *ee) {
1658 if(ee->error_code == BadWindow
1659 || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1660 || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1661 || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1662 || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1663 || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1664 || (ee->request_code == X_GrabButton && ee->error_code == BadAccess)
1665 || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1666 || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1668 fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1669 ee->request_code, ee->error_code);
1670 return xerrorxlib(dpy, ee); /* may call exit */
1674 xerrordummy(Display *dpy, XErrorEvent *ee) {
1678 /* Startup Error handler to check if another window manager
1679 * is already running. */
1681 xerrorstart(Display *dpy, XErrorEvent *ee) {
1687 zoom(const Arg *arg) {
1690 if(ismax || !lt->arrange || (sel && sel->isfloating))
1692 if(c == nexttiled(clients))
1693 if(!c || !(c = nexttiled(c->next)))
1702 main(int argc, char *argv[]) {
1703 if(argc == 2 && !strcmp("-v", argv[1]))
1704 eprint("dwm-"VERSION", © 2006-2008 dwm engineers, see LICENSE for details\n");
1706 eprint("usage: dwm [-v]\n");
1708 setlocale(LC_CTYPE, "");
1709 if(!(dpy = XOpenDisplay(0)))
1710 eprint("dwm: cannot open display\n");