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[selmon->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))
51 #define MOUSEMASK (BUTTONMASK|PointerMotionMask)
52 #define WIDTH(x) ((x)->w + 2 * (x)->bw)
53 #define HEIGHT(x) ((x)->h + 2 * (x)->bw)
54 #define TAGMASK ((int)((1LL << LENGTH(tags)) - 1))
55 #define TEXTW(x) (textnw(x, strlen(x)) + dc.font.height)
58 enum { CurNormal, CurResize, CurMove, CurLast }; /* cursor */
59 enum { ColBorder, ColFG, ColBG, ColLast }; /* color */
60 enum { NetSupported, NetWMName, NetLast }; /* EWMH atoms */
61 enum { WMProtocols, WMDelete, WMState, WMLast }; /* default atoms */
62 enum { ClkTagBar, ClkLtSymbol, ClkStatusText, ClkWinTitle,
63 ClkClientWin, ClkRootWin, ClkLast }; /* clicks */
76 void (*func)(const Arg *arg);
80 typedef struct Client Client;
85 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 unsigned int seltags;
130 const char *instance;
136 /* function declarations */
137 static void applyrules(Client *c);
138 static Bool applysizehints(Client *c, int *x, int *y, int *w, int *h);
139 static void arrange(void);
140 static void attach(Client *c);
141 static void attachstack(Client *c);
142 static void buttonpress(XEvent *e);
143 static void checkotherwm(void);
144 static void cleanup(void);
145 static void clearurgent(Client *c);
146 static void configure(Client *c);
147 static void configurenotify(XEvent *e);
148 static void configurerequest(XEvent *e);
149 static void destroynotify(XEvent *e);
150 static void detach(Client *c);
151 static void detachstack(Client *c);
152 static void die(const char *errstr, ...);
153 static void drawbar(void);
154 static void drawsquare(Bool filled, Bool empty, Bool invert, unsigned long col[ColLast]);
155 static void drawtext(const char *text, unsigned long col[ColLast], Bool invert);
156 static void enternotify(XEvent *e);
157 static void expose(XEvent *e);
158 static void focus(Client *c);
159 static void focusin(XEvent *e);
160 static void focusstack(const Arg *arg);
161 static Client *getclient(Window w);
162 static unsigned long getcolor(const char *colstr);
163 static long getstate(Window w);
164 static Bool gettextprop(Window w, Atom atom, char *text, unsigned int size);
165 static void grabbuttons(Client *c, Bool focused);
166 static void grabkeys(void);
167 static void initfont(const char *fontstr);
168 static Bool isprotodel(Client *c);
169 static void keypress(XEvent *e);
170 static void killclient(const Arg *arg);
171 static void manage(Window w, XWindowAttributes *wa);
172 static void mappingnotify(XEvent *e);
173 static void maprequest(XEvent *e);
174 static void monocle(void);
175 static void movemouse(const Arg *arg);
176 static Client *nexttiled(Client *c);
177 static void propertynotify(XEvent *e);
178 static void quit(const Arg *arg);
179 static void resize(Client *c, int x, int y, int w, int h);
180 static void resizemouse(const Arg *arg);
181 static void restack(void);
182 static void run(void);
183 static void scan(void);
184 static void setclientstate(Client *c, long state);
185 static void setlayout(const Arg *arg);
186 static void setmfact(const Arg *arg);
187 static void setup(void);
188 static void showhide(Client *c);
189 static void sigchld(int signal);
190 static void spawn(const Arg *arg);
191 static void tag(const Arg *arg);
192 static int textnw(const char *text, unsigned int len);
193 static void tile(void);
194 static void togglebar(const Arg *arg);
195 static void togglefloating(const Arg *arg);
196 static void toggletag(const Arg *arg);
197 static void toggleview(const Arg *arg);
198 static void unmanage(Client *c);
199 static void unmapnotify(XEvent *e);
200 static void updatebar(void);
201 static void updategeom(void);
202 static void updatenumlockmask(void);
203 static void updatesizehints(Client *c);
204 static void updatestatus(void);
205 static void updatetitle(Client *c);
206 static void updatewmhints(Client *c);
207 static void view(const Arg *arg);
208 static int xerror(Display *dpy, XErrorEvent *ee);
209 static int xerrordummy(Display *dpy, XErrorEvent *ee);
210 static int xerrorstart(Display *dpy, XErrorEvent *ee);
211 static void zoom(const Arg *arg);
214 static char stext[256];
216 static int sx, sy, sw, sh; /* X display screen geometry x, y, width, height */
217 static int by, bh, blw; /* bar geometry y, height and layout symbol width */
218 static int (*xerrorxlib)(Display *, XErrorEvent *);
219 static unsigned int numlockmask = 0;
220 static void (*handler[LASTEvent]) (XEvent *) = {
221 [ButtonPress] = buttonpress,
222 [ConfigureRequest] = configurerequest,
223 [ConfigureNotify] = configurenotify,
224 [DestroyNotify] = destroynotify,
225 [EnterNotify] = enternotify,
228 [KeyPress] = keypress,
229 [MappingNotify] = mappingnotify,
230 [MapRequest] = maprequest,
231 [PropertyNotify] = propertynotify,
232 [UnmapNotify] = unmapnotify
234 static Atom wmatom[WMLast], netatom[NetLast];
236 static Bool running = True;
237 static Client *clients = NULL;
238 static Client *sel = NULL;
239 static Client *stack = NULL;
240 static Cursor cursor[CurLast];
243 static Layout *lt[] = { NULL, NULL };
244 static Monitor *mon = NULL, *selmon = NULL;
245 static unsigned int nmons;
246 static Window root, barwin;
247 /* configuration, allows nested code to access above variables */
250 /* compile-time check if all tags fit into an unsigned int bit array. */
251 struct NumTags { char limitexceeded[sizeof(unsigned int) * 8 < LENGTH(tags) ? -1 : 1]; };
253 /* function implementations */
255 applyrules(Client *c) {
258 XClassHint ch = { 0 };
261 c->isfloating = c->tags = 0;
262 if(XGetClassHint(dpy, c->win, &ch)) {
263 for(i = 0; i < LENGTH(rules); i++) {
265 if((!r->title || strstr(c->name, r->title))
266 && (!r->class || (ch.res_class && strstr(ch.res_class, r->class)))
267 && (!r->instance || (ch.res_name && strstr(ch.res_name, r->instance)))) {
268 c->isfloating = r->isfloating;
277 c->tags = c->tags & TAGMASK ? c->tags & TAGMASK : tagset[mon[c->mon].seltags];
281 applysizehints(Client *c, int *x, int *y, int *w, int *h) {
284 /* set minimum possible */
292 if(*x + *w + 2 * c->bw < sx)
294 if(*y + *h + 2 * c->bw < sy)
301 if(resizehints || c->isfloating) {
302 /* see last two sentences in ICCCM 4.1.2.3 */
303 baseismin = c->basew == c->minw && c->baseh == c->minh;
305 if(!baseismin) { /* temporarily remove base dimensions */
310 /* adjust for aspect limits */
311 if(c->mina > 0 && c->maxa > 0) {
312 if(c->maxa < (float)*w / *h)
314 else if(c->mina < (float)*h / *w)
318 if(baseismin) { /* increment calculation requires this */
323 /* adjust for increment value */
329 /* restore base dimensions */
333 *w = MAX(*w, c->minw);
334 *h = MAX(*h, c->minh);
337 *w = MIN(*w, c->maxw);
340 *h = MIN(*h, c->maxh);
342 return *x != c->x || *y != c->y || *w != c->w || *h != c->h;
349 if(lt[selmon->sellt]->arrange)
350 lt[selmon->sellt]->arrange();
361 attachstack(Client *c) {
367 buttonpress(XEvent *e) {
368 unsigned int i, x, click;
371 XButtonPressedEvent *ev = &e->xbutton;
374 if(ev->window == barwin) {
376 do x += TEXTW(tags[i]); while(ev->x >= x && ++i < LENGTH(tags));
377 if(i < LENGTH(tags)) {
381 else if(ev->x < x + blw)
383 else if(ev->x > selmon->wx + selmon->ww - TEXTW(stext))
384 click = ClkStatusText;
388 else if((c = getclient(ev->window))) {
390 click = ClkClientWin;
393 for(i = 0; i < LENGTH(buttons); i++)
394 if(click == buttons[i].click && buttons[i].func && buttons[i].button == ev->button
395 && CLEANMASK(buttons[i].mask) == CLEANMASK(ev->state))
396 buttons[i].func(click == ClkTagBar && buttons[i].arg.i == 0 ? &arg : &buttons[i].arg);
402 xerrorxlib = XSetErrorHandler(xerrorstart);
404 /* this causes an error if some other window manager is running */
405 XSelectInput(dpy, DefaultRootWindow(dpy), SubstructureRedirectMask);
408 die("dwm: another window manager is already running\n");
409 XSetErrorHandler(xerror);
416 Layout foo = { "", NULL };
419 lt[selmon->sellt] = &foo;
423 XFreeFontSet(dpy, dc.font.set);
425 XFreeFont(dpy, dc.font.xfont);
426 XUngrabKey(dpy, AnyKey, AnyModifier, root);
427 XFreePixmap(dpy, dc.drawable);
429 XFreeCursor(dpy, cursor[CurNormal]);
430 XFreeCursor(dpy, cursor[CurResize]);
431 XFreeCursor(dpy, cursor[CurMove]);
432 XDestroyWindow(dpy, barwin);
434 XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime);
438 clearurgent(Client *c) {
442 if(!(wmh = XGetWMHints(dpy, c->win)))
444 wmh->flags &= ~XUrgencyHint;
445 XSetWMHints(dpy, c->win, wmh);
450 configure(Client *c) {
453 ce.type = ConfigureNotify;
461 ce.border_width = c->bw;
463 ce.override_redirect = False;
464 XSendEvent(dpy, c->win, False, StructureNotifyMask, (XEvent *)&ce);
468 configurenotify(XEvent *e) {
469 XConfigureEvent *ev = &e->xconfigure;
471 if(ev->window == root && (ev->width != sw || ev->height != sh)) {
481 configurerequest(XEvent *e) {
483 XConfigureRequestEvent *ev = &e->xconfigurerequest;
486 if((c = getclient(ev->window))) {
487 if(ev->value_mask & CWBorderWidth)
488 c->bw = ev->border_width;
489 else if(c->isfloating || !lt[selmon->sellt]->arrange) {
490 if(ev->value_mask & CWX)
492 if(ev->value_mask & CWY)
494 if(ev->value_mask & CWWidth)
496 if(ev->value_mask & CWHeight)
498 if((c->x - sx + c->w) > sw && c->isfloating)
499 c->x = sx + (sw / 2 - c->w / 2); /* center in x direction */
500 if((c->y - sy + c->h) > sh && c->isfloating)
501 c->y = sy + (sh / 2 - c->h / 2); /* center in y direction */
502 if((ev->value_mask & (CWX|CWY)) && !(ev->value_mask & (CWWidth|CWHeight)))
505 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h);
513 wc.width = ev->width;
514 wc.height = ev->height;
515 wc.border_width = ev->border_width;
516 wc.sibling = ev->above;
517 wc.stack_mode = ev->detail;
518 XConfigureWindow(dpy, ev->window, ev->value_mask, &wc);
524 destroynotify(XEvent *e) {
526 XDestroyWindowEvent *ev = &e->xdestroywindow;
528 if((c = getclient(ev->window)))
536 for(tc = &clients; *tc && *tc != c; tc = &(*tc)->next);
541 detachstack(Client *c) {
544 for(tc = &stack; *tc && *tc != c; tc = &(*tc)->snext);
549 die(const char *errstr, ...) {
552 va_start(ap, errstr);
553 vfprintf(stderr, errstr, ap);
561 unsigned int i, occ = 0, urg = 0;
565 for(c = clients; c; c = c->next) {
572 for(i = 0; i < LENGTH(tags); i++) {
573 dc.w = TEXTW(tags[i]);
574 col = tagset[selmon->seltags] & 1 << i ? dc.sel : dc.norm;
575 drawtext(tags[i], col, urg & 1 << i);
576 drawsquare(sel && sel->tags & 1 << i, occ & 1 << i, urg & 1 << i, col);
581 drawtext(lt[selmon->sellt]->symbol, dc.norm, False);
587 dc.x = selmon->ww - dc.w;
590 dc.w = selmon->ww - x;
592 drawtext(stext, dc.norm, False);
593 if((dc.w = dc.x - x) > bh) {
596 drawtext(sel->name, dc.sel, False);
597 drawsquare(sel->isfixed, sel->isfloating, False, dc.sel);
600 drawtext(NULL, dc.norm, False);
602 XCopyArea(dpy, dc.drawable, barwin, dc.gc, 0, 0, selmon->ww, bh, 0, 0);
607 drawsquare(Bool filled, Bool empty, Bool invert, unsigned long col[ColLast]) {
610 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
612 gcv.foreground = col[invert ? ColBG : ColFG];
613 XChangeGC(dpy, dc.gc, GCForeground, &gcv);
614 x = (dc.font.ascent + dc.font.descent + 2) / 4;
618 r.width = r.height = x + 1;
619 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
622 r.width = r.height = x;
623 XDrawRectangles(dpy, dc.drawable, dc.gc, &r, 1);
628 drawtext(const char *text, unsigned long col[ColLast], Bool invert) {
630 int i, x, y, h, len, olen;
631 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
633 XSetForeground(dpy, dc.gc, col[invert ? ColFG : ColBG]);
634 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
638 h = dc.font.ascent + dc.font.descent;
639 y = dc.y + (dc.h / 2) - (h / 2) + dc.font.ascent;
641 /* shorten text if necessary */
642 for(len = MIN(olen, sizeof buf); len && textnw(text, len) > dc.w - h; len--);
645 memcpy(buf, text, len);
647 for(i = len; i && i > len - 3; buf[--i] = '.');
648 XSetForeground(dpy, dc.gc, col[invert ? ColBG : ColFG]);
650 XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
652 XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
656 enternotify(XEvent *e) {
658 XCrossingEvent *ev = &e->xcrossing;
660 if((ev->mode != NotifyNormal || ev->detail == NotifyInferior) && ev->window != root)
662 if((c = getclient(ev->window)))
670 XExposeEvent *ev = &e->xexpose;
672 if(ev->count == 0 && (ev->window == barwin))
678 if(!c || !ISVISIBLE(c))
679 for(c = stack; c && !ISVISIBLE(c); c = c->snext);
680 if(sel && sel != c) {
681 grabbuttons(sel, False);
682 XSetWindowBorder(dpy, sel->win, dc.norm[ColBorder]);
689 grabbuttons(c, True);
690 XSetWindowBorder(dpy, c->win, dc.sel[ColBorder]);
691 XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
694 XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
700 focusin(XEvent *e) { /* there are some broken focus acquiring clients */
701 XFocusChangeEvent *ev = &e->xfocus;
703 if(sel && ev->window != sel->win)
704 XSetInputFocus(dpy, sel->win, RevertToPointerRoot, CurrentTime);
708 focusstack(const Arg *arg) {
709 Client *c = NULL, *i;
714 for(c = sel->next; c && !ISVISIBLE(c); c = c->next);
716 for(c = clients; c && !ISVISIBLE(c); c = c->next);
719 for(i = clients; i != sel; i = i->next)
723 for(; i; i = i->next)
734 getclient(Window w) {
737 for(c = clients; c && c->win != w; c = c->next);
742 getcolor(const char *colstr) {
743 Colormap cmap = DefaultColormap(dpy, screen);
746 if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
747 die("error, cannot allocate color '%s'\n", colstr);
755 unsigned char *p = NULL;
756 unsigned long n, extra;
759 status = XGetWindowProperty(dpy, w, wmatom[WMState], 0L, 2L, False, wmatom[WMState],
760 &real, &format, &n, &extra, (unsigned char **)&p);
761 if(status != Success)
770 gettextprop(Window w, Atom atom, char *text, unsigned int size) {
775 if(!text || size == 0)
778 XGetTextProperty(dpy, w, &name, atom);
781 if(name.encoding == XA_STRING)
782 strncpy(text, (char *)name.value, size - 1);
784 if(XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success
786 strncpy(text, *list, size - 1);
787 XFreeStringList(list);
790 text[size - 1] = '\0';
796 grabbuttons(Client *c, Bool focused) {
800 unsigned int modifiers[] = { 0, LockMask, numlockmask, numlockmask|LockMask };
801 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
803 for(i = 0; i < LENGTH(buttons); i++)
804 if(buttons[i].click == ClkClientWin)
805 for(j = 0; j < LENGTH(modifiers); j++)
806 XGrabButton(dpy, buttons[i].button,
807 buttons[i].mask | modifiers[j],
808 c->win, False, BUTTONMASK,
809 GrabModeAsync, GrabModeSync, None, None);
811 XGrabButton(dpy, AnyButton, AnyModifier, c->win, False,
812 BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
821 unsigned int modifiers[] = { 0, LockMask, numlockmask, numlockmask|LockMask };
824 XUngrabKey(dpy, AnyKey, AnyModifier, root);
825 for(i = 0; i < LENGTH(keys); i++) {
826 if((code = XKeysymToKeycode(dpy, keys[i].keysym)))
827 for(j = 0; j < LENGTH(modifiers); j++)
828 XGrabKey(dpy, code, keys[i].mod | modifiers[j], root,
829 True, GrabModeAsync, GrabModeAsync);
835 initfont(const char *fontstr) {
836 char *def, **missing;
840 dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
843 fprintf(stderr, "dwm: missing fontset: %s\n", missing[n]);
844 XFreeStringList(missing);
847 XFontSetExtents *font_extents;
848 XFontStruct **xfonts;
850 dc.font.ascent = dc.font.descent = 0;
851 font_extents = XExtentsOfFontSet(dc.font.set);
852 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
853 for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
854 dc.font.ascent = MAX(dc.font.ascent, (*xfonts)->ascent);
855 dc.font.descent = MAX(dc.font.descent,(*xfonts)->descent);
860 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr))
861 && !(dc.font.xfont = XLoadQueryFont(dpy, "fixed")))
862 die("error, cannot load font: '%s'\n", fontstr);
863 dc.font.ascent = dc.font.xfont->ascent;
864 dc.font.descent = dc.font.xfont->descent;
866 dc.font.height = dc.font.ascent + dc.font.descent;
870 isprotodel(Client *c) {
875 if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
876 for(i = 0; !ret && i < n; i++)
877 if(protocols[i] == wmatom[WMDelete])
885 keypress(XEvent *e) {
891 keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
892 for(i = 0; i < LENGTH(keys); i++)
893 if(keysym == keys[i].keysym
894 && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state)
896 keys[i].func(&(keys[i].arg));
900 killclient(const Arg *arg) {
905 if(isprotodel(sel)) {
906 ev.type = ClientMessage;
907 ev.xclient.window = sel->win;
908 ev.xclient.message_type = wmatom[WMProtocols];
909 ev.xclient.format = 32;
910 ev.xclient.data.l[0] = wmatom[WMDelete];
911 ev.xclient.data.l[1] = CurrentTime;
912 XSendEvent(dpy, sel->win, False, NoEventMask, &ev);
915 XKillClient(dpy, sel->win);
919 manage(Window w, XWindowAttributes *wa) {
921 Client *c, *t = NULL;
925 if(!(c = malloc(sizeof(Client))))
926 die("fatal: could not malloc() %u bytes\n", sizeof(Client));
929 for(c->mon = 0; selmon != &mon[c->mon]; c->mon++);
936 c->oldbw = wa->border_width;
937 if(c->w == sw && c->h == sh) {
943 if(c->x + WIDTH(c) > sx + sw)
944 c->x = sx + sw - WIDTH(c);
945 if(c->y + HEIGHT(c) > sy + sh)
946 c->y = sy + sh - HEIGHT(c);
947 c->x = MAX(c->x, sx);
948 /* only fix client y-offset, if the client center might cover the bar */
949 /* TODO: is c always attached to selmon? */
950 c->y = MAX(c->y, ((by == 0) && (c->x + (c->w / 2) >= selmon->wx)
951 && (c->x + (c->w / 2) < selmon->wx + selmon->ww)) ? bh : sy);
955 wc.border_width = c->bw;
956 XConfigureWindow(dpy, w, CWBorderWidth, &wc);
957 XSetWindowBorder(dpy, w, dc.norm[ColBorder]);
958 configure(c); /* propagates border_width, if size doesn't change */
960 XSelectInput(dpy, w, EnterWindowMask|FocusChangeMask|PropertyChangeMask|StructureNotifyMask);
961 grabbuttons(c, False);
963 if(XGetTransientForHint(dpy, w, &trans))
964 t = getclient(trans);
970 c->isfloating = trans != None || c->isfixed;
972 XRaiseWindow(dpy, c->win);
975 XMoveResizeWindow(dpy, c->win, c->x + 2 * sw, c->y, c->w, c->h); /* some windows require this */
976 XMapWindow(dpy, c->win);
977 setclientstate(c, NormalState);
982 mappingnotify(XEvent *e) {
983 XMappingEvent *ev = &e->xmapping;
985 XRefreshKeyboardMapping(ev);
986 if(ev->request == MappingKeyboard)
991 maprequest(XEvent *e) {
992 static XWindowAttributes wa;
993 XMapRequestEvent *ev = &e->xmaprequest;
995 if(!XGetWindowAttributes(dpy, ev->window, &wa))
997 if(wa.override_redirect)
999 if(!getclient(ev->window))
1000 manage(ev->window, &wa);
1008 for(c = nexttiled(clients); c; c = nexttiled(c->next)) {
1010 resize(c, m->wx, m->wy, m->ww - 2 * c->bw, m->wh - 2 * c->bw);
1015 movemouse(const Arg *arg) {
1016 int x, y, ocx, ocy, di, nx, ny;
1027 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1028 None, cursor[CurMove], CurrentTime) != GrabSuccess)
1030 XQueryPointer(dpy, root, &dummy, &dummy, &x, &y, &di, &di, &dui);
1032 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
1034 case ConfigureRequest:
1037 handler[ev.type](&ev);
1040 nx = ocx + (ev.xmotion.x - x);
1041 ny = ocy + (ev.xmotion.y - y);
1042 if(snap && nx >= selmon->wx && nx <= selmon->wx + selmon->ww
1043 && ny >= selmon->wy && ny <= selmon->wy + selmon->wh) {
1044 if(abs(selmon->wx - nx) < snap)
1046 else if(abs((selmon->wx + selmon->ww) - (nx + WIDTH(c))) < snap)
1047 nx = selmon->wx + selmon->ww - WIDTH(c);
1048 if(abs(selmon->wy - ny) < snap)
1050 else if(abs((selmon->wy + selmon->wh) - (ny + HEIGHT(c))) < snap)
1051 ny = selmon->wy + selmon->wh - HEIGHT(c);
1052 if(!c->isfloating && lt[selmon->sellt]->arrange
1053 && (abs(nx - c->x) > snap || abs(ny - c->y) > snap))
1054 togglefloating(NULL);
1056 if(!lt[selmon->sellt]->arrange || c->isfloating)
1057 resize(c, nx, ny, c->w, c->h);
1061 while(ev.type != ButtonRelease);
1062 XUngrabPointer(dpy, CurrentTime);
1066 nexttiled(Client *c) {
1067 for(; c && (c->isfloating || !ISVISIBLE(c)); c = c->next);
1072 propertynotify(XEvent *e) {
1075 XPropertyEvent *ev = &e->xproperty;
1077 if((ev->window == root) && (ev->atom == XA_WM_NAME))
1079 else if(ev->state == PropertyDelete)
1080 return; /* ignore */
1081 else if((c = getclient(ev->window))) {
1084 case XA_WM_TRANSIENT_FOR:
1085 XGetTransientForHint(dpy, c->win, &trans);
1086 if(!c->isfloating && (c->isfloating = (getclient(trans) != NULL)))
1089 case XA_WM_NORMAL_HINTS:
1097 if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
1106 quit(const Arg *arg) {
1111 resize(Client *c, int x, int y, int w, int h) {
1114 if(applysizehints(c, &x, &y, &w, &h)) {
1117 c->w = wc.width = w;
1118 c->h = wc.height = h;
1119 wc.border_width = c->bw;
1120 XConfigureWindow(dpy, c->win,
1121 CWX|CWY|CWWidth|CWHeight|CWBorderWidth, &wc);
1128 resizemouse(const Arg *arg) {
1139 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1140 None, cursor[CurResize], CurrentTime) != GrabSuccess)
1142 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->bw - 1, c->h + c->bw - 1);
1144 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
1146 case ConfigureRequest:
1149 handler[ev.type](&ev);
1152 nw = MAX(ev.xmotion.x - ocx - 2 * c->bw + 1, 1);
1153 nh = MAX(ev.xmotion.y - ocy - 2 * c->bw + 1, 1);
1155 if(snap && nw >= selmon->wx && nw <= selmon->wx + selmon->ww
1156 && nh >= selmon->wy && nh <= selmon->wy + selmon->wh) {
1157 if(!c->isfloating && lt[selmon->sellt]->arrange
1158 && (abs(nw - c->w) > snap || abs(nh - c->h) > snap))
1159 togglefloating(NULL);
1161 if(!lt[selmon->sellt]->arrange || c->isfloating)
1162 resize(c, c->x, c->y, nw, nh);
1166 while(ev.type != ButtonRelease);
1167 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->bw - 1, c->h + c->bw - 1);
1168 XUngrabPointer(dpy, CurrentTime);
1169 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1181 if(sel->isfloating || !lt[selmon->sellt]->arrange)
1182 XRaiseWindow(dpy, sel->win);
1183 if(lt[selmon->sellt]->arrange) {
1184 wc.stack_mode = Below;
1185 wc.sibling = barwin;
1186 for(c = stack; c; c = c->snext)
1187 if(!c->isfloating && ISVISIBLE(c)) {
1188 XConfigureWindow(dpy, c->win, CWSibling|CWStackMode, &wc);
1189 wc.sibling = c->win;
1193 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1200 /* main event loop */
1202 while(running && !XNextEvent(dpy, &ev)) {
1203 if(handler[ev.type])
1204 (handler[ev.type])(&ev); /* call handler */
1210 unsigned int i, num;
1211 Window d1, d2, *wins = NULL;
1212 XWindowAttributes wa;
1214 if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1215 for(i = 0; i < num; i++) {
1216 if(!XGetWindowAttributes(dpy, wins[i], &wa)
1217 || wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1219 if(wa.map_state == IsViewable || getstate(wins[i]) == IconicState)
1220 manage(wins[i], &wa);
1222 for(i = 0; i < num; i++) { /* now the transients */
1223 if(!XGetWindowAttributes(dpy, wins[i], &wa))
1225 if(XGetTransientForHint(dpy, wins[i], &d1)
1226 && (wa.map_state == IsViewable || getstate(wins[i]) == IconicState))
1227 manage(wins[i], &wa);
1235 setclientstate(Client *c, long state) {
1236 long data[] = {state, None};
1238 XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1239 PropModeReplace, (unsigned char *)data, 2);
1243 setlayout(const Arg *arg) {
1244 if(!arg || !arg->v || arg->v != lt[selmon->sellt])
1247 lt[selmon->sellt] = (Layout *)arg->v;
1254 /* arg > 1.0 will set mfact absolutly */
1256 setmfact(const Arg *arg) {
1259 if(!arg || !lt[selmon->sellt]->arrange)
1261 f = arg->f < 1.0 ? arg->f + mfact : arg->f - 1.0;
1262 if(f < 0.1 || f > 0.9)
1272 XSetWindowAttributes wa;
1275 screen = DefaultScreen(dpy);
1276 root = RootWindow(dpy, screen);
1280 sw = DisplayWidth(dpy, screen);
1281 sh = DisplayHeight(dpy, screen);
1282 bh = dc.h = dc.font.height + 2;
1283 lt[0] = &layouts[0];
1284 lt[1] = &layouts[1 % LENGTH(layouts)];
1288 wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1289 wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1290 wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1291 netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1292 netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1295 wa.cursor = cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1296 cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1297 cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1299 /* init appearance */
1300 dc.norm[ColBorder] = getcolor(normbordercolor);
1301 dc.norm[ColBG] = getcolor(normbgcolor);
1302 dc.norm[ColFG] = getcolor(normfgcolor);
1303 dc.sel[ColBorder] = getcolor(selbordercolor);
1304 dc.sel[ColBG] = getcolor(selbgcolor);
1305 dc.sel[ColFG] = getcolor(selfgcolor);
1306 dc.drawable = XCreatePixmap(dpy, root, DisplayWidth(dpy, screen), bh, DefaultDepth(dpy, screen));
1307 dc.gc = XCreateGC(dpy, root, 0, NULL);
1308 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
1310 XSetFont(dpy, dc.gc, dc.font.xfont->fid);
1313 for(blw = i = 0; LENGTH(layouts) > 1 && i < LENGTH(layouts); i++) {
1314 w = TEXTW(layouts[i].symbol);
1318 wa.override_redirect = True;
1319 wa.background_pixmap = ParentRelative;
1320 wa.event_mask = ButtonPressMask|ExposureMask;
1322 barwin = XCreateWindow(dpy, root, selmon->wx, by, selmon->ww, bh, 0, DefaultDepth(dpy, screen),
1323 CopyFromParent, DefaultVisual(dpy, screen),
1324 CWOverrideRedirect|CWBackPixmap|CWEventMask, &wa);
1325 XDefineCursor(dpy, barwin, cursor[CurNormal]);
1326 XMapRaised(dpy, barwin);
1329 /* EWMH support per view */
1330 XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1331 PropModeReplace, (unsigned char *) netatom, NetLast);
1333 /* select for events */
1334 wa.event_mask = SubstructureRedirectMask|SubstructureNotifyMask|ButtonPressMask
1335 |EnterWindowMask|LeaveWindowMask|StructureNotifyMask
1336 |PropertyChangeMask;
1337 XChangeWindowAttributes(dpy, root, CWEventMask|CWCursor, &wa);
1338 XSelectInput(dpy, root, wa.event_mask);
1344 showhide(Client *c) {
1347 if(ISVISIBLE(c)) { /* show clients top down */
1348 XMoveWindow(dpy, c->win, c->x, c->y);
1349 if(!lt[selmon->sellt]->arrange || c->isfloating)
1350 resize(c, c->x, c->y, c->w, c->h);
1353 else { /* hide clients bottom up */
1355 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
1361 sigchld(int signal) {
1362 while(0 < waitpid(-1, NULL, WNOHANG));
1366 spawn(const Arg *arg) {
1367 signal(SIGCHLD, sigchld);
1370 close(ConnectionNumber(dpy));
1372 execvp(((char **)arg->v)[0], (char **)arg->v);
1373 fprintf(stderr, "dwm: execvp %s", ((char **)arg->v)[0]);
1380 tag(const Arg *arg) {
1381 if(sel && arg->ui & TAGMASK) {
1382 sel->tags = arg->ui & TAGMASK;
1388 textnw(const char *text, unsigned int len) {
1392 XmbTextExtents(dc.font.set, text, len, NULL, &r);
1395 return XTextWidth(dc.font.xfont, text, len);
1405 for(n = 0, c = nexttiled(clients); c; c = nexttiled(c->next), n++);
1410 c = nexttiled(clients);
1413 resize(c, m->wx, m->wy, (n == 1 ? m->ww : mw) - 2 * c->bw, m->wh - 2 * c->bw);
1419 x = (m->wx + mw > c->x + c->w) ? c->x + c->w + 2 * c->bw : m->wx + mw;
1421 w = (m->wx + mw > c->x + c->w) ? m->wx + m->ww - x : m->ww - mw;
1426 for(i = 0, c = nexttiled(c->next); c; c = nexttiled(c->next), i++) {
1427 resize(c, x, y, w - 2 * c->bw, /* remainder */ ((i + 1 == n)
1428 ? m->wy + m->wh - y - 2 * c->bw : h - 2 * c->bw));
1430 y = c->y + HEIGHT(c);
1435 togglebar(const Arg *arg) {
1443 togglefloating(const Arg *arg) {
1446 sel->isfloating = !sel->isfloating || sel->isfixed;
1448 resize(sel, sel->x, sel->y, sel->w, sel->h);
1453 toggletag(const Arg *arg) {
1459 mask = sel->tags ^ (arg->ui & TAGMASK);
1467 toggleview(const Arg *arg) {
1468 unsigned int mask = tagset[selmon->seltags] ^ (arg->ui & TAGMASK);
1471 tagset[selmon->seltags] = mask;
1477 unmanage(Client *c) {
1480 wc.border_width = c->oldbw;
1481 /* The server grab construct avoids race conditions. */
1483 XSetErrorHandler(xerrordummy);
1484 XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
1489 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1490 setclientstate(c, WithdrawnState);
1493 XSetErrorHandler(xerror);
1499 unmapnotify(XEvent *e) {
1501 XUnmapEvent *ev = &e->xunmap;
1503 if((c = getclient(ev->window)))
1509 if(dc.drawable != 0)
1510 XFreePixmap(dpy, dc.drawable);
1511 dc.drawable = XCreatePixmap(dpy, root, selmon->ww, bh, DefaultDepth(dpy, screen));
1512 XMoveResizeWindow(dpy, barwin, selmon->wx, by, selmon->ww, bh);
1519 unsigned int dui, i = 0;
1523 XineramaScreenInfo *info = NULL;
1525 /* window area geometry */
1526 if(XineramaIsActive(dpy) && (info = XineramaQueryScreens(dpy, &n))) {
1527 nmons = (unsigned int)n;
1528 for(c = clients; c; c = c->next)
1531 if(!(mon = (Monitor *)realloc(mon, sizeof(Monitor) * nmons)))
1532 die("fatal: could not realloc() %u bytes\n", sizeof(Monitor) * nmons);
1533 pquery = XQueryPointer(dpy, root, &dummy, &dummy, &x, &y, &di, &di, &dui);
1534 for(i = 0; i < nmons; i++) {
1535 /* TODO: consider re-using XineramaScreenInfo */
1536 mon[i].wx = info[i].x_org;
1537 mon[i].wy = info[i].y_org;
1538 mon[i].ww = info[i].width;
1539 mon[i].wh = info[i].height;
1542 if(pquery && INRECT(x, y, info[i].x_org, info[i].y_org, info[i].width, info[i].height))
1545 /* bar adjustments of selmon */
1546 selmon->wy = showbar && topbar ? selmon->wy + bh : selmon->wy;
1547 selmon->wh = showbar ? selmon->wh - bh : selmon->wh;
1554 if(!(mon = (Monitor *)realloc(mon, sizeof(Monitor))))
1555 die("fatal: could not realloc() %u bytes\n", sizeof(Monitor));
1558 mon[0].wy = showbar && topbar ? sy + bh : sy;
1560 mon[0].wh = showbar ? sh - bh : sh;
1566 by = showbar ? (topbar ? selmon->wy - bh : selmon->wy + selmon->wh) : -bh;
1570 updatenumlockmask(void) {
1572 XModifierKeymap *modmap;
1575 modmap = XGetModifierMapping(dpy);
1576 for(i = 0; i < 8; i++)
1577 for(j = 0; j < modmap->max_keypermod; j++)
1578 if(modmap->modifiermap[i * modmap->max_keypermod + j]
1579 == XKeysymToKeycode(dpy, XK_Num_Lock))
1580 numlockmask = (1 << i);
1581 XFreeModifiermap(modmap);
1585 updatesizehints(Client *c) {
1589 if(!XGetWMNormalHints(dpy, c->win, &size, &msize))
1590 /* size is uninitialized, ensure that size.flags aren't used */
1592 if(size.flags & PBaseSize) {
1593 c->basew = size.base_width;
1594 c->baseh = size.base_height;
1596 else if(size.flags & PMinSize) {
1597 c->basew = size.min_width;
1598 c->baseh = size.min_height;
1601 c->basew = c->baseh = 0;
1602 if(size.flags & PResizeInc) {
1603 c->incw = size.width_inc;
1604 c->inch = size.height_inc;
1607 c->incw = c->inch = 0;
1608 if(size.flags & PMaxSize) {
1609 c->maxw = size.max_width;
1610 c->maxh = size.max_height;
1613 c->maxw = c->maxh = 0;
1614 if(size.flags & PMinSize) {
1615 c->minw = size.min_width;
1616 c->minh = size.min_height;
1618 else if(size.flags & PBaseSize) {
1619 c->minw = size.base_width;
1620 c->minh = size.base_height;
1623 c->minw = c->minh = 0;
1624 if(size.flags & PAspect) {
1625 c->mina = (float)size.min_aspect.y / (float)size.min_aspect.x;
1626 c->maxa = (float)size.max_aspect.x / (float)size.max_aspect.y;
1629 c->maxa = c->mina = 0.0;
1630 c->isfixed = (c->maxw && c->minw && c->maxh && c->minh
1631 && c->maxw == c->minw && c->maxh == c->minh);
1635 updatetitle(Client *c) {
1636 if(!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
1637 gettextprop(c->win, XA_WM_NAME, c->name, sizeof c->name);
1642 if(!gettextprop(root, XA_WM_NAME, stext, sizeof(stext)))
1643 strcpy(stext, "dwm-"VERSION);
1648 updatewmhints(Client *c) {
1651 if((wmh = XGetWMHints(dpy, c->win))) {
1652 if(c == sel && wmh->flags & XUrgencyHint) {
1653 wmh->flags &= ~XUrgencyHint;
1654 XSetWMHints(dpy, c->win, wmh);
1657 c->isurgent = (wmh->flags & XUrgencyHint) ? True : False;
1664 view(const Arg *arg) {
1665 if((arg->ui & TAGMASK) == tagset[selmon->seltags])
1667 selmon->seltags ^= 1; /* toggle sel tagset */
1668 if(arg->ui & TAGMASK)
1669 tagset[selmon->seltags] = arg->ui & TAGMASK;
1673 /* There's no way to check accesses to destroyed windows, thus those cases are
1674 * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
1675 * default error handler, which may call exit. */
1677 xerror(Display *dpy, XErrorEvent *ee) {
1678 if(ee->error_code == BadWindow
1679 || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1680 || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1681 || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1682 || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1683 || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1684 || (ee->request_code == X_GrabButton && ee->error_code == BadAccess)
1685 || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1686 || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1688 fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1689 ee->request_code, ee->error_code);
1690 return xerrorxlib(dpy, ee); /* may call exit */
1694 xerrordummy(Display *dpy, XErrorEvent *ee) {
1698 /* Startup Error handler to check if another window manager
1699 * is already running. */
1701 xerrorstart(Display *dpy, XErrorEvent *ee) {
1707 zoom(const Arg *arg) {
1710 if(!lt[selmon->sellt]->arrange || lt[selmon->sellt]->arrange == monocle || (sel && sel->isfloating))
1712 if(c == nexttiled(clients))
1713 if(!c || !(c = nexttiled(c->next)))
1722 main(int argc, char *argv[]) {
1723 if(argc == 2 && !strcmp("-v", argv[1]))
1724 die("dwm-"VERSION", © 2006-2009 dwm engineers, see LICENSE for details\n");
1726 die("usage: dwm [-v]\n");
1728 if(!setlocale(LC_CTYPE, "") || !XSupportsLocale())
1729 fputs("warning: no locale support\n", stderr);
1731 if(!(dpy = XOpenDisplay(NULL)))
1732 die("dwm: cannot open display\n");