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 * The event handlers of dwm are organized in an array which is accessed
10 * whenever a new event has been fetched. This allows event dispatching
13 * Each child of the root window is called a client, except windows which have
14 * set the override_redirect flag. Clients are organized in a global
15 * linked client list, the focus history is remembered through a global
16 * stack list. Each client contains a bit array to indicate the tags of a
19 * Keys and tagging rules are organized as arrays and defined in config.h.
21 * To understand everything else, start reading main().
31 #include <sys/types.h>
33 #include <X11/cursorfont.h>
34 #include <X11/keysym.h>
35 #include <X11/Xatom.h>
37 #include <X11/Xproto.h>
38 #include <X11/Xutil.h>
40 #include <X11/extensions/Xinerama.h>
44 #define BUTTONMASK (ButtonPressMask|ButtonReleaseMask)
45 #define CLEANMASK(mask) (mask & ~(numlockmask|LockMask))
46 #define INRECT(X,Y,RX,RY,RW,RH) ((X) >= (RX) && (X) < (RX) + (RW) && (Y) >= (RY) && (Y) < (RY) + (RH))
47 #define ISVISIBLE(x) (x->tags & tagset[seltags])
48 #define LENGTH(x) (sizeof x / sizeof x[0])
49 #define MAX(a, b) ((a) > (b) ? (a) : (b))
50 #define MIN(a, b) ((a) < (b) ? (a) : (b))
52 #define MOUSEMASK (BUTTONMASK|PointerMotionMask)
53 #define WIDTH(x) ((x)->w + 2 * (x)->bw)
54 #define HEIGHT(x) ((x)->h + 2 * (x)->bw)
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, 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 applysizehints(Client *c, int *w, int *h);
133 static void arrange(void);
134 static void attach(Client *c);
135 static void attachstack(Client *c);
136 static void buttonpress(XEvent *e);
137 static void checkotherwm(void);
138 static void cleanup(void);
139 static void clearurgent(Client *c);
140 static void configure(Client *c);
141 static void configurenotify(XEvent *e);
142 static void configurerequest(XEvent *e);
143 static void destroynotify(XEvent *e);
144 static void detach(Client *c);
145 static void detachstack(Client *c);
146 static void die(const char *errstr, ...);
147 static void drawbar(void);
148 static void drawsquare(Bool filled, Bool empty, Bool invert, unsigned long col[ColLast]);
149 static void drawtext(const char *text, unsigned long col[ColLast], Bool invert);
150 static void enternotify(XEvent *e);
151 static void expose(XEvent *e);
152 static void focus(Client *c);
153 static void focusin(XEvent *e);
154 static void focusstack(const Arg *arg);
155 static Client *getclient(Window w);
156 static unsigned long getcolor(const char *colstr);
157 static long getstate(Window w);
158 static Bool gettextprop(Window w, Atom atom, char *text, unsigned int size);
159 static void grabbuttons(Client *c, Bool focused);
160 static void grabkeys(void);
161 static void initfont(const char *fontstr);
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 showhide(Client *c, unsigned int ntiled);
183 static void sigchld(int signal);
184 static void spawn(const Arg *arg);
185 static void tag(const Arg *arg);
186 static int textnw(const char *text, unsigned int len);
187 static void tile(void);
188 static void togglebar(const Arg *arg);
189 static void togglefloating(const Arg *arg);
190 static void toggletag(const Arg *arg);
191 static void toggleview(const Arg *arg);
192 static void unmanage(Client *c);
193 static void unmapnotify(XEvent *e);
194 static void updatebar(void);
195 static void updategeom(void);
196 static void updatenumlockmask(void);
197 static void updatesizehints(Client *c);
198 static void updatestatus(void);
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 ? r->tags & TAGMASK : tagset[seltags];
271 c->tags = tagset[seltags];
275 applysizehints(Client *c, int *w, int *h) {
278 /* see last two sentences in ICCCM 4.1.2.3 */
279 baseismin = c->basew == c->minw && c->baseh == c->minh;
281 /* set minimum possible */
285 if(!baseismin) { /* temporarily remove base dimensions */
290 /* adjust for aspect limits */
291 if(c->mina > 0 && c->maxa > 0) {
292 if(c->maxa < (float)*w / *h)
294 else if(c->mina < (float)*h / *w)
298 if(baseismin) { /* increment calculation requires this */
303 /* adjust for increment value */
309 /* restore base dimensions */
313 *w = MAX(*w, c->minw);
314 *h = MAX(*h, c->minh);
317 *w = MIN(*w, c->maxw);
320 *h = MIN(*h, c->maxh);
328 for(nt = 0, c = nexttiled(clients); c; c = nexttiled(c->next), nt++);
331 if(lt[sellt]->arrange)
332 lt[sellt]->arrange();
343 attachstack(Client *c) {
349 buttonpress(XEvent *e) {
350 unsigned int i, x, click;
353 XButtonPressedEvent *ev = &e->xbutton;
356 if(ev->window == barwin) {
358 do x += TEXTW(tags[i]); while(ev->x >= x && ++i < LENGTH(tags));
359 if(i < LENGTH(tags)) {
363 else if(ev->x < x + blw)
365 else if(ev->x > wx + ww - TEXTW(stext))
366 click = ClkStatusText;
370 else if((c = getclient(ev->window))) {
372 click = ClkClientWin;
375 for(i = 0; i < LENGTH(buttons); i++)
376 if(click == buttons[i].click && buttons[i].func && buttons[i].button == ev->button
377 && CLEANMASK(buttons[i].mask) == CLEANMASK(ev->state))
378 buttons[i].func(click == ClkTagBar && buttons[i].arg.i == 0 ? &arg : &buttons[i].arg);
384 xerrorxlib = XSetErrorHandler(xerrorstart);
386 /* this causes an error if some other window manager is running */
387 XSelectInput(dpy, DefaultRootWindow(dpy), SubstructureRedirectMask);
390 die("dwm: another window manager is already running\n");
391 XSetErrorHandler(xerror);
398 Layout foo = { "", NULL };
405 XFreeFontSet(dpy, dc.font.set);
407 XFreeFont(dpy, dc.font.xfont);
408 XUngrabKey(dpy, AnyKey, AnyModifier, root);
409 XFreePixmap(dpy, dc.drawable);
411 XFreeCursor(dpy, cursor[CurNormal]);
412 XFreeCursor(dpy, cursor[CurResize]);
413 XFreeCursor(dpy, cursor[CurMove]);
414 XDestroyWindow(dpy, barwin);
416 XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime);
420 clearurgent(Client *c) {
424 if(!(wmh = XGetWMHints(dpy, c->win)))
426 wmh->flags &= ~XUrgencyHint;
427 XSetWMHints(dpy, c->win, wmh);
432 configure(Client *c) {
435 ce.type = ConfigureNotify;
443 ce.border_width = c->bw;
445 ce.override_redirect = False;
446 XSendEvent(dpy, c->win, False, StructureNotifyMask, (XEvent *)&ce);
450 configurenotify(XEvent *e) {
451 XConfigureEvent *ev = &e->xconfigure;
453 if(ev->window == root && (ev->width != sw || ev->height != sh)) {
463 configurerequest(XEvent *e) {
465 XConfigureRequestEvent *ev = &e->xconfigurerequest;
468 if((c = getclient(ev->window))) {
469 if(ev->value_mask & CWBorderWidth)
470 c->bw = ev->border_width;
471 else if(c->isfloating || !lt[sellt]->arrange) {
472 if(ev->value_mask & CWX)
474 if(ev->value_mask & CWY)
476 if(ev->value_mask & CWWidth)
478 if(ev->value_mask & CWHeight)
480 if((c->x - sx + c->w) > sw && c->isfloating)
481 c->x = sx + (sw / 2 - c->w / 2); /* center in x direction */
482 if((c->y - sy + c->h) > sh && c->isfloating)
483 c->y = sy + (sh / 2 - c->h / 2); /* center in y direction */
484 if((ev->value_mask & (CWX|CWY)) && !(ev->value_mask & (CWWidth|CWHeight)))
487 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h);
495 wc.width = ev->width;
496 wc.height = ev->height;
497 wc.border_width = ev->border_width;
498 wc.sibling = ev->above;
499 wc.stack_mode = ev->detail;
500 XConfigureWindow(dpy, ev->window, ev->value_mask, &wc);
506 destroynotify(XEvent *e) {
508 XDestroyWindowEvent *ev = &e->xdestroywindow;
510 if((c = getclient(ev->window)))
518 for(tc = &clients; *tc && *tc != c; tc = &(*tc)->next);
523 detachstack(Client *c) {
526 for(tc = &stack; *tc && *tc != c; tc = &(*tc)->snext);
531 die(const char *errstr, ...) {
534 va_start(ap, errstr);
535 vfprintf(stderr, errstr, ap);
543 unsigned int i, occ = 0, urg = 0;
547 for(c = clients; c; c = c->next) {
554 for(i = 0; i < LENGTH(tags); i++) {
555 dc.w = TEXTW(tags[i]);
556 col = tagset[seltags] & 1 << i ? dc.sel : dc.norm;
557 drawtext(tags[i], col, urg & 1 << i);
558 drawsquare(sel && sel->tags & 1 << i, occ & 1 << i, urg & 1 << i, col);
563 drawtext(lt[sellt]->symbol, dc.norm, False);
574 drawtext(stext, dc.norm, False);
575 if((dc.w = dc.x - x) > bh) {
578 drawtext(sel->name, dc.sel, False);
579 drawsquare(sel->isfixed, sel->isfloating, False, dc.sel);
582 drawtext(NULL, dc.norm, False);
584 XCopyArea(dpy, dc.drawable, barwin, dc.gc, 0, 0, ww, bh, 0, 0);
589 drawsquare(Bool filled, Bool empty, Bool invert, unsigned long col[ColLast]) {
592 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
594 gcv.foreground = col[invert ? ColBG : ColFG];
595 XChangeGC(dpy, dc.gc, GCForeground, &gcv);
596 x = (dc.font.ascent + dc.font.descent + 2) / 4;
600 r.width = r.height = x + 1;
601 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
604 r.width = r.height = x;
605 XDrawRectangles(dpy, dc.drawable, dc.gc, &r, 1);
610 drawtext(const char *text, unsigned long col[ColLast], Bool invert) {
612 int i, x, y, h, len, olen;
613 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
615 XSetForeground(dpy, dc.gc, col[invert ? ColFG : ColBG]);
616 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
620 h = dc.font.ascent + dc.font.descent;
621 y = dc.y + (dc.h / 2) - (h / 2) + dc.font.ascent;
623 /* shorten text if necessary */
624 for(len = MIN(olen, sizeof buf); len && textnw(text, len) > dc.w - h; len--);
627 memcpy(buf, text, len);
629 for(i = len; i && i > len - 3; buf[--i] = '.');
630 XSetForeground(dpy, dc.gc, col[invert ? ColBG : ColFG]);
632 XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
634 XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
638 enternotify(XEvent *e) {
640 XCrossingEvent *ev = &e->xcrossing;
642 if((ev->mode != NotifyNormal || ev->detail == NotifyInferior) && ev->window != root)
644 if((c = getclient(ev->window)))
652 XExposeEvent *ev = &e->xexpose;
654 if(ev->count == 0 && (ev->window == barwin))
660 if(!c || !ISVISIBLE(c))
661 for(c = stack; c && !ISVISIBLE(c); c = c->snext);
662 if(sel && sel != c) {
663 grabbuttons(sel, False);
664 XSetWindowBorder(dpy, sel->win, dc.norm[ColBorder]);
671 grabbuttons(c, True);
672 XSetWindowBorder(dpy, c->win, dc.sel[ColBorder]);
673 XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
676 XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
682 focusin(XEvent *e) { /* there are some broken focus acquiring clients */
683 XFocusChangeEvent *ev = &e->xfocus;
685 if(sel && ev->window != sel->win)
686 XSetInputFocus(dpy, sel->win, RevertToPointerRoot, CurrentTime);
690 focusstack(const Arg *arg) {
691 Client *c = NULL, *i;
696 for(c = sel->next; c && !ISVISIBLE(c); c = c->next);
698 for(c = clients; c && !ISVISIBLE(c); c = c->next);
701 for(i = clients; i != sel; i = i->next)
705 for(; i; i = i->next)
716 getclient(Window w) {
719 for(c = clients; c && c->win != w; c = c->next);
724 getcolor(const char *colstr) {
725 Colormap cmap = DefaultColormap(dpy, screen);
728 if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
729 die("error, cannot allocate color '%s'\n", colstr);
737 unsigned char *p = NULL;
738 unsigned long n, extra;
741 status = XGetWindowProperty(dpy, w, wmatom[WMState], 0L, 2L, False, wmatom[WMState],
742 &real, &format, &n, &extra, (unsigned char **)&p);
743 if(status != Success)
752 gettextprop(Window w, Atom atom, char *text, unsigned int size) {
757 if(!text || size == 0)
760 XGetTextProperty(dpy, w, &name, atom);
763 if(name.encoding == XA_STRING)
764 strncpy(text, (char *)name.value, size - 1);
766 if(XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success
768 strncpy(text, *list, size - 1);
769 XFreeStringList(list);
772 text[size - 1] = '\0';
778 grabbuttons(Client *c, Bool focused) {
782 unsigned int modifiers[] = { 0, LockMask, numlockmask, numlockmask|LockMask };
783 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
785 for(i = 0; i < LENGTH(buttons); i++)
786 if(buttons[i].click == ClkClientWin)
787 for(j = 0; j < LENGTH(modifiers); j++)
788 XGrabButton(dpy, buttons[i].button, buttons[i].mask | modifiers[j], c->win, False, BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
790 XGrabButton(dpy, AnyButton, AnyModifier, c->win, False,
791 BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
800 unsigned int modifiers[] = { 0, LockMask, numlockmask, numlockmask|LockMask };
803 XUngrabKey(dpy, AnyKey, AnyModifier, root);
804 for(i = 0; i < LENGTH(keys); i++) {
805 if((code = XKeysymToKeycode(dpy, keys[i].keysym)))
806 for(j = 0; j < LENGTH(modifiers); j++)
807 XGrabKey(dpy, code, keys[i].mod | modifiers[j], root,
808 True, GrabModeAsync, GrabModeAsync);
814 initfont(const char *fontstr) {
815 char *def, **missing;
819 dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
822 fprintf(stderr, "dwm: missing fontset: %s\n", missing[n]);
823 XFreeStringList(missing);
826 XFontSetExtents *font_extents;
827 XFontStruct **xfonts;
829 dc.font.ascent = dc.font.descent = 0;
830 font_extents = XExtentsOfFontSet(dc.font.set);
831 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
832 for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
833 dc.font.ascent = MAX(dc.font.ascent, (*xfonts)->ascent);
834 dc.font.descent = MAX(dc.font.descent,(*xfonts)->descent);
839 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr))
840 && !(dc.font.xfont = XLoadQueryFont(dpy, "fixed")))
841 die("error, cannot load font: '%s'\n", fontstr);
842 dc.font.ascent = dc.font.xfont->ascent;
843 dc.font.descent = dc.font.xfont->descent;
845 dc.font.height = dc.font.ascent + dc.font.descent;
849 isprotodel(Client *c) {
854 if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
855 for(i = 0; !ret && i < n; i++)
856 if(protocols[i] == wmatom[WMDelete])
864 keypress(XEvent *e) {
870 keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
871 for(i = 0; i < LENGTH(keys); i++)
872 if(keysym == keys[i].keysym
873 && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state)
875 keys[i].func(&(keys[i].arg));
879 killclient(const Arg *arg) {
884 if(isprotodel(sel)) {
885 ev.type = ClientMessage;
886 ev.xclient.window = sel->win;
887 ev.xclient.message_type = wmatom[WMProtocols];
888 ev.xclient.format = 32;
889 ev.xclient.data.l[0] = wmatom[WMDelete];
890 ev.xclient.data.l[1] = CurrentTime;
891 XSendEvent(dpy, sel->win, False, NoEventMask, &ev);
894 XKillClient(dpy, sel->win);
898 manage(Window w, XWindowAttributes *wa) {
900 Client *c, *t = NULL;
904 if(!(c = malloc(sizeof(Client))))
905 die("fatal: could not malloc() %u bytes\n", sizeof(Client));
914 c->oldbw = wa->border_width;
915 if(c->w == sw && c->h == sh) {
921 if(c->x + WIDTH(c) > sx + sw)
922 c->x = sx + sw - WIDTH(c);
923 if(c->y + HEIGHT(c) > sy + sh)
924 c->y = sy + sh - HEIGHT(c);
925 c->x = MAX(c->x, sx);
926 /* only fix client y-offset, if the client center might cover the bar */
927 c->y = MAX(c->y, ((by == 0) && (c->x + (c->w / 2) >= wx) && (c->x + (c->w / 2) < wx + ww)) ? bh : sy);
931 wc.border_width = c->bw;
932 XConfigureWindow(dpy, w, CWBorderWidth, &wc);
933 XSetWindowBorder(dpy, w, dc.norm[ColBorder]);
934 configure(c); /* propagates border_width, if size doesn't change */
936 XSelectInput(dpy, w, EnterWindowMask|FocusChangeMask|PropertyChangeMask|StructureNotifyMask);
937 grabbuttons(c, False);
939 if(XGetTransientForHint(dpy, w, &trans))
940 t = getclient(trans);
946 c->isfloating = trans != None || c->isfixed;
948 XRaiseWindow(dpy, c->win);
951 XMoveResizeWindow(dpy, c->win, c->x + 2 * sw, c->y, c->w, c->h); /* some windows require this */
952 XMapWindow(dpy, c->win);
953 setclientstate(c, NormalState);
958 mappingnotify(XEvent *e) {
959 XMappingEvent *ev = &e->xmapping;
961 XRefreshKeyboardMapping(ev);
962 if(ev->request == MappingKeyboard)
967 maprequest(XEvent *e) {
968 static XWindowAttributes wa;
969 XMapRequestEvent *ev = &e->xmaprequest;
971 if(!XGetWindowAttributes(dpy, ev->window, &wa))
973 if(wa.override_redirect)
975 if(!getclient(ev->window))
976 manage(ev->window, &wa);
983 for(c = nexttiled(clients); c; c = nexttiled(c->next)) {
984 resize(c, wx, wy, ww - 2 * c->bw, wh - 2 * c->bw, resizehints);
989 movemouse(const Arg *arg) {
990 int x, y, ocx, ocy, di, nx, ny;
1001 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1002 None, cursor[CurMove], CurrentTime) != GrabSuccess)
1004 XQueryPointer(dpy, root, &dummy, &dummy, &x, &y, &di, &di, &dui);
1008 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
1010 case ConfigureRequest:
1013 handler[ev.type](&ev);
1016 nx = ocx + (ev.xmotion.x - x);
1017 ny = ocy + (ev.xmotion.y - y);
1018 if(snap && nx >= wx && nx <= wx + ww
1019 && ny >= wy && ny <= wy + wh) {
1020 if(abs(wx - nx) < snap)
1022 else if(abs((wx + ww) - (nx + WIDTH(c))) < snap)
1023 nx = wx + ww - WIDTH(c);
1024 if(abs(wy - ny) < snap)
1026 else if(abs((wy + wh) - (ny + HEIGHT(c))) < snap)
1027 ny = wy + wh - HEIGHT(c);
1028 if(!c->isfloating && lt[sellt]->arrange && (abs(nx - c->x) > snap || abs(ny - c->y) > snap))
1029 togglefloating(NULL);
1031 if(!lt[sellt]->arrange || c->isfloating)
1032 resize(c, nx, ny, c->w, c->h, False);
1036 while(ev.type != ButtonRelease);
1039 XUngrabPointer(dpy, CurrentTime);
1043 nexttiled(Client *c) {
1044 for(; c && (c->isfloating || !ISVISIBLE(c)); c = c->next);
1049 propertynotify(XEvent *e) {
1052 XPropertyEvent *ev = &e->xproperty;
1054 if((ev->window == root) && (ev->atom == XA_WM_NAME))
1056 else if(ev->state == PropertyDelete)
1057 return; /* ignore */
1058 else if((c = getclient(ev->window))) {
1061 case XA_WM_TRANSIENT_FOR:
1062 XGetTransientForHint(dpy, c->win, &trans);
1063 if(!c->isfloating && (c->isfloating = (getclient(trans) != NULL)))
1066 case XA_WM_NORMAL_HINTS:
1074 if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
1083 quit(const Arg *arg) {
1088 resize(Client *c, int x, int y, int w, int h, Bool sizehints) {
1092 applysizehints(c, &w, &h);
1093 if(w <= 0 || h <= 0)
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);
1139 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
1141 case ConfigureRequest:
1144 handler[ev.type](&ev);
1147 nw = MAX(ev.xmotion.x - ocx - 2 * c->bw + 1, 1);
1148 nh = MAX(ev.xmotion.y - ocy - 2 * c->bw + 1, 1);
1150 if(snap && nw >= wx && nw <= wx + ww
1151 && nh >= wy && nh <= wy + wh) {
1152 if(!c->isfloating && lt[sellt]->arrange
1153 && (abs(nw - c->w) > snap || abs(nh - c->h) > snap))
1154 togglefloating(NULL);
1156 if(!lt[sellt]->arrange || c->isfloating)
1157 resize(c, c->x, c->y, nw, nh, True);
1161 while(ev.type != ButtonRelease);
1164 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->bw - 1, c->h + c->bw - 1);
1165 XUngrabPointer(dpy, CurrentTime);
1166 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1178 if(sel->isfloating || !lt[sellt]->arrange)
1179 XRaiseWindow(dpy, sel->win);
1180 if(lt[sellt]->arrange) {
1181 wc.stack_mode = Below;
1182 wc.sibling = barwin;
1183 for(c = stack; c; c = c->snext)
1184 if(!c->isfloating && ISVISIBLE(c)) {
1185 XConfigureWindow(dpy, c->win, CWSibling|CWStackMode, &wc);
1186 wc.sibling = c->win;
1190 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1197 /* main event loop */
1199 while(running && !XNextEvent(dpy, &ev)) {
1200 if(handler[ev.type])
1201 (handler[ev.type])(&ev); /* call handler */
1207 unsigned int i, num;
1208 Window d1, d2, *wins = NULL;
1209 XWindowAttributes wa;
1211 if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1212 for(i = 0; i < num; i++) {
1213 if(!XGetWindowAttributes(dpy, wins[i], &wa)
1214 || wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1216 if(wa.map_state == IsViewable || getstate(wins[i]) == IconicState)
1217 manage(wins[i], &wa);
1219 for(i = 0; i < num; i++) { /* now the transients */
1220 if(!XGetWindowAttributes(dpy, wins[i], &wa))
1222 if(XGetTransientForHint(dpy, wins[i], &d1)
1223 && (wa.map_state == IsViewable || getstate(wins[i]) == IconicState))
1224 manage(wins[i], &wa);
1232 setclientstate(Client *c, long state) {
1233 long data[] = {state, None};
1235 XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1236 PropModeReplace, (unsigned char *)data, 2);
1240 setlayout(const Arg *arg) {
1241 if(!arg || !arg->v || arg->v != lt[sellt])
1244 lt[sellt] = (Layout *)arg->v;
1251 /* arg > 1.0 will set mfact absolutly */
1253 setmfact(const Arg *arg) {
1256 if(!arg || !lt[sellt]->arrange)
1258 f = arg->f < 1.0 ? arg->f + mfact : arg->f - 1.0;
1259 if(f < 0.1 || f > 0.9)
1269 XSetWindowAttributes wa;
1272 screen = DefaultScreen(dpy);
1273 root = RootWindow(dpy, screen);
1277 sw = DisplayWidth(dpy, screen);
1278 sh = DisplayHeight(dpy, screen);
1279 bh = dc.h = dc.font.height + 2;
1280 lt[0] = &layouts[0];
1281 lt[1] = &layouts[1 % LENGTH(layouts)];
1285 wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1286 wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1287 wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1288 netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1289 netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1292 wa.cursor = cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1293 cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1294 cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1296 /* init appearance */
1297 dc.norm[ColBorder] = getcolor(normbordercolor);
1298 dc.norm[ColBG] = getcolor(normbgcolor);
1299 dc.norm[ColFG] = getcolor(normfgcolor);
1300 dc.sel[ColBorder] = getcolor(selbordercolor);
1301 dc.sel[ColBG] = getcolor(selbgcolor);
1302 dc.sel[ColFG] = getcolor(selfgcolor);
1303 dc.drawable = XCreatePixmap(dpy, root, DisplayWidth(dpy, screen), bh, DefaultDepth(dpy, screen));
1304 dc.gc = XCreateGC(dpy, root, 0, NULL);
1305 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
1307 XSetFont(dpy, dc.gc, dc.font.xfont->fid);
1310 for(blw = i = 0; LENGTH(layouts) > 1 && i < LENGTH(layouts); i++) {
1311 w = TEXTW(layouts[i].symbol);
1315 wa.override_redirect = True;
1316 wa.background_pixmap = ParentRelative;
1317 wa.event_mask = ButtonPressMask|ExposureMask;
1319 barwin = XCreateWindow(dpy, root, wx, by, ww, bh, 0, DefaultDepth(dpy, screen),
1320 CopyFromParent, DefaultVisual(dpy, screen),
1321 CWOverrideRedirect|CWBackPixmap|CWEventMask, &wa);
1322 XDefineCursor(dpy, barwin, cursor[CurNormal]);
1323 XMapRaised(dpy, barwin);
1326 /* EWMH support per view */
1327 XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1328 PropModeReplace, (unsigned char *) netatom, NetLast);
1330 /* select for events */
1331 wa.event_mask = SubstructureRedirectMask|SubstructureNotifyMask|ButtonPressMask
1332 |EnterWindowMask|LeaveWindowMask|StructureNotifyMask
1333 |PropertyChangeMask;
1334 XChangeWindowAttributes(dpy, root, CWEventMask|CWCursor, &wa);
1335 XSelectInput(dpy, root, wa.event_mask);
1341 showhide(Client *c, unsigned int ntiled) {
1344 if(ISVISIBLE(c)) { /* show clients top down */
1345 XMoveWindow(dpy, c->win, c->x, c->y);
1346 if(!lt[sellt]->arrange || c->isfloating)
1347 resize(c, c->x, c->y, c->w, c->h, True);
1348 showhide(c->snext, ntiled);
1350 else { /* hide clients bottom up */
1351 showhide(c->snext, ntiled);
1352 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
1358 sigchld(int signal) {
1359 while(0 < waitpid(-1, NULL, WNOHANG));
1363 spawn(const Arg *arg) {
1364 signal(SIGCHLD, sigchld);
1367 close(ConnectionNumber(dpy));
1369 execvp(((char **)arg->v)[0], (char **)arg->v);
1370 fprintf(stderr, "dwm: execvp %s", ((char **)arg->v)[0]);
1377 tag(const Arg *arg) {
1378 if(sel && arg->ui & TAGMASK) {
1379 sel->tags = arg->ui & TAGMASK;
1385 textnw(const char *text, unsigned int len) {
1389 XmbTextExtents(dc.font.set, text, len, NULL, &r);
1392 return XTextWidth(dc.font.xfont, text, len);
1401 for(n = 0, c = nexttiled(clients); c; c = nexttiled(c->next), n++);
1406 c = nexttiled(clients);
1408 resize(c, wx, wy, (n == 1 ? ww : mw) - 2 * c->bw, wh - 2 * c->bw, resizehints);
1414 x = (wx + mw > c->x + c->w) ? c->x + c->w + 2 * c->bw : wx + mw;
1416 w = (wx + mw > c->x + c->w) ? wx + ww - x : ww - mw;
1421 for(i = 0, c = nexttiled(c->next); c; c = nexttiled(c->next), i++) {
1422 resize(c, x, y, w - 2 * c->bw, /* remainder */ ((i + 1 == n)
1423 ? wy + wh - y - 2 * c->bw : h - 2 * c->bw), resizehints);
1425 y = c->y + HEIGHT(c);
1430 togglebar(const Arg *arg) {
1438 togglefloating(const Arg *arg) {
1441 sel->isfloating = !sel->isfloating || sel->isfixed;
1443 resize(sel, sel->x, sel->y, sel->w, sel->h, True);
1448 toggletag(const Arg *arg) {
1454 mask = sel->tags ^ (arg->ui & TAGMASK);
1462 toggleview(const Arg *arg) {
1463 unsigned int mask = tagset[seltags] ^ (arg->ui & TAGMASK);
1466 tagset[seltags] = mask;
1472 unmanage(Client *c) {
1475 wc.border_width = c->oldbw;
1476 /* The server grab construct avoids race conditions. */
1478 XSetErrorHandler(xerrordummy);
1479 XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
1484 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1485 setclientstate(c, WithdrawnState);
1488 XSetErrorHandler(xerror);
1494 unmapnotify(XEvent *e) {
1496 XUnmapEvent *ev = &e->xunmap;
1498 if((c = getclient(ev->window)))
1504 if(dc.drawable != 0)
1505 XFreePixmap(dpy, dc.drawable);
1506 dc.drawable = XCreatePixmap(dpy, root, ww, bh, DefaultDepth(dpy, screen));
1507 XMoveResizeWindow(dpy, barwin, wx, by, ww, bh);
1514 XineramaScreenInfo *info = NULL;
1516 /* window area geometry */
1517 if(XineramaIsActive(dpy) && (info = XineramaQueryScreens(dpy, &n))) {
1522 if(XQueryPointer(dpy, root, &dummy, &dummy, &x, &y, &di, &di, &dui))
1523 for(i = 0; i < n; i++)
1524 if(INRECT(x, y, info[i].x_org, info[i].y_org, info[i].width, info[i].height))
1528 wy = showbar && topbar ? info[i].y_org + bh : info[i].y_org;
1530 wh = showbar ? info[i].height - bh : info[i].height;
1537 wy = showbar && topbar ? sy + bh : sy;
1539 wh = showbar ? sh - bh : sh;
1543 by = showbar ? (topbar ? wy - bh : wy + wh) : -bh;
1547 updatenumlockmask(void) {
1549 XModifierKeymap *modmap;
1552 modmap = XGetModifierMapping(dpy);
1553 for(i = 0; i < 8; i++)
1554 for(j = 0; j < modmap->max_keypermod; j++)
1555 if(modmap->modifiermap[i * modmap->max_keypermod + j] == XKeysymToKeycode(dpy, XK_Num_Lock))
1556 numlockmask = (1 << i);
1557 XFreeModifiermap(modmap);
1561 updatesizehints(Client *c) {
1565 if(!XGetWMNormalHints(dpy, c->win, &size, &msize))
1566 /* size is uninitialized, ensure that size.flags aren't used */
1568 if(size.flags & PBaseSize) {
1569 c->basew = size.base_width;
1570 c->baseh = size.base_height;
1572 else if(size.flags & PMinSize) {
1573 c->basew = size.min_width;
1574 c->baseh = size.min_height;
1577 c->basew = c->baseh = 0;
1578 if(size.flags & PResizeInc) {
1579 c->incw = size.width_inc;
1580 c->inch = size.height_inc;
1583 c->incw = c->inch = 0;
1584 if(size.flags & PMaxSize) {
1585 c->maxw = size.max_width;
1586 c->maxh = size.max_height;
1589 c->maxw = c->maxh = 0;
1590 if(size.flags & PMinSize) {
1591 c->minw = size.min_width;
1592 c->minh = size.min_height;
1594 else if(size.flags & PBaseSize) {
1595 c->minw = size.base_width;
1596 c->minh = size.base_height;
1599 c->minw = c->minh = 0;
1600 if(size.flags & PAspect) {
1601 c->mina = (float)size.min_aspect.y / (float)size.min_aspect.x;
1602 c->maxa = (float)size.max_aspect.x / (float)size.max_aspect.y;
1605 c->maxa = c->mina = 0.0;
1606 c->isfixed = (c->maxw && c->minw && c->maxh && c->minh
1607 && c->maxw == c->minw && c->maxh == c->minh);
1611 updatetitle(Client *c) {
1612 if(!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
1613 gettextprop(c->win, XA_WM_NAME, c->name, sizeof c->name);
1618 if(!gettextprop(root, XA_WM_NAME, stext, sizeof(stext)))
1619 strcpy(stext, "dwm-"VERSION);
1624 updatewmhints(Client *c) {
1627 if((wmh = XGetWMHints(dpy, c->win))) {
1628 if(c == sel && wmh->flags & XUrgencyHint) {
1629 wmh->flags &= ~XUrgencyHint;
1630 XSetWMHints(dpy, c->win, wmh);
1633 c->isurgent = (wmh->flags & XUrgencyHint) ? True : False;
1640 view(const Arg *arg) {
1641 if((arg->ui & TAGMASK) == tagset[seltags])
1643 seltags ^= 1; /* toggle sel tagset */
1644 if(arg->ui & TAGMASK)
1645 tagset[seltags] = arg->ui & TAGMASK;
1649 /* There's no way to check accesses to destroyed windows, thus those cases are
1650 * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
1651 * default error handler, which may call exit. */
1653 xerror(Display *dpy, XErrorEvent *ee) {
1654 if(ee->error_code == BadWindow
1655 || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1656 || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1657 || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1658 || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1659 || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1660 || (ee->request_code == X_GrabButton && ee->error_code == BadAccess)
1661 || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1662 || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1664 fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1665 ee->request_code, ee->error_code);
1666 return xerrorxlib(dpy, ee); /* may call exit */
1670 xerrordummy(Display *dpy, XErrorEvent *ee) {
1674 /* Startup Error handler to check if another window manager
1675 * is already running. */
1677 xerrorstart(Display *dpy, XErrorEvent *ee) {
1683 zoom(const Arg *arg) {
1686 if(!lt[sellt]->arrange || lt[sellt]->arrange == monocle || (sel && sel->isfloating))
1688 if(c == nexttiled(clients))
1689 if(!c || !(c = nexttiled(c->next)))
1698 main(int argc, char *argv[]) {
1699 if(argc == 2 && !strcmp("-v", argv[1]))
1700 die("dwm-"VERSION", © 2006-2009 dwm engineers, see LICENSE for details\n");
1702 die("usage: dwm [-v]\n");
1704 if(!setlocale(LC_CTYPE, "") || !XSupportsLocale())
1705 fputs("warning: no locale support\n", stderr);
1707 if(!(dpy = XOpenDisplay(NULL)))
1708 die("dwm: cannot open display\n");