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 an array of Bools of the same size as the
20 * global tags array to indicate the tags of a client. For each client dwm
21 * creates a small title window, which is resized whenever the (_NET_)WM_NAME
22 * properties are updated or the client is moved/resized.
24 * Keys and tagging rules are organized as arrays and defined in the config.h
25 * file. These arrays are kept static in event.o and tag.o respectively,
26 * because no other part of dwm needs access to them. The current layout is
27 * represented by the lt pointer.
29 * To understand everything else, start reading main().
39 #include <sys/select.h>
41 #include <X11/cursorfont.h>
42 #include <X11/keysym.h>
43 #include <X11/Xatom.h>
44 #include <X11/Xproto.h>
45 #include <X11/Xutil.h>
48 #define BUTTONMASK (ButtonPressMask | ButtonReleaseMask)
49 #define CLEANMASK(mask) (mask & ~(numlockmask | LockMask))
50 #define MOUSEMASK (BUTTONMASK | PointerMotionMask)
53 enum { BarTop, BarBot, BarOff }; /* bar position */
54 enum { CurNormal, CurResize, CurMove, CurLast }; /* cursor */
55 enum { ColBorder, ColFG, ColBG, ColLast }; /* color */
56 enum { NetSupported, NetWMName, NetLast }; /* EWMH atoms */
57 enum { WMProtocols, WMDelete, WMName, WMState, WMLast };/* default atoms */
60 typedef struct Client Client;
64 int rx, ry, rw, rh; /* revert geometry */
65 int basew, baseh, incw, inch, maxw, maxh, minw, minh;
66 int minax, maxax, minay, maxay;
68 unsigned int border, oldborder;
69 Bool isbanned, isfixed, ismax, isfloating;
79 unsigned long norm[ColLast];
80 unsigned long sel[ColLast];
90 } DC; /* draw context */
95 void (*func)(const char *arg);
101 void (*arrange)(void);
115 /* forward declarations */
116 static void applyrules(Client *c);
117 static void arrange(void);
118 static void attach(Client *c);
119 static void attachstack(Client *c);
120 static void ban(Client *c);
121 static void buttonpress(XEvent *e);
122 static void checkotherwm(void);
123 static void cleanup(void);
124 static void compileregs(void);
125 static void configure(Client *c);
126 static void configurenotify(XEvent *e);
127 static void configurerequest(XEvent *e);
128 static void destroynotify(XEvent *e);
129 static void detach(Client *c);
130 static void detachstack(Client *c);
131 static void drawbar(void);
132 static void drawsquare(Bool filled, Bool empty, unsigned long col[ColLast]);
133 static void drawtext(const char *text, unsigned long col[ColLast]);
134 static void *emallocz(unsigned int size);
135 static void enternotify(XEvent *e);
136 static void eprint(const char *errstr, ...);
137 static void expose(XEvent *e);
138 static void floating(void); /* default floating layout */
139 static void focus(Client *c);
140 static void focusnext(const char *arg);
141 static void focusprev(const char *arg);
142 static Client *getclient(Window w);
143 static unsigned long getcolor(const char *colstr);
144 static long getstate(Window w);
145 static Bool gettextprop(Window w, Atom atom, char *text, unsigned int size);
146 static void grabbuttons(Client *c, Bool focused);
147 static unsigned int idxoftag(const char *tag);
148 static void initfont(const char *fontstr);
149 static Bool isarrange(void (*func)());
150 static Bool isoccupied(unsigned int t);
151 static Bool isprotodel(Client *c);
152 static Bool isvisible(Client *c);
153 static void keypress(XEvent *e);
154 static void killclient(const char *arg);
155 static void leavenotify(XEvent *e);
156 static void manage(Window w, XWindowAttributes *wa);
157 static void mappingnotify(XEvent *e);
158 static void maprequest(XEvent *e);
159 static void movemouse(Client *c);
160 static Client *nexttiled(Client *c);
161 static void propertynotify(XEvent *e);
162 static void quit(const char *arg);
163 static void resize(Client *c, int x, int y, int w, int h, Bool sizehints);
164 static void resizemouse(Client *c);
165 static void restack(void);
166 static void run(void);
167 static void scan(void);
168 static void setclientstate(Client *c, long state);
169 static void setlayout(const char *arg);
170 static void setmwfact(const char *arg);
171 static void setup(void);
172 static void spawn(const char *arg);
173 static void tag(const char *arg);
174 static unsigned int textnw(const char *text, unsigned int len);
175 static unsigned int textw(const char *text);
176 static void tile(void);
177 static void togglebar(const char *arg);
178 static void togglefloating(const char *arg);
179 static void togglemax(const char *arg);
180 static void toggletag(const char *arg);
181 static void toggleview(const char *arg);
182 static void unban(Client *c);
183 static void unmanage(Client *c);
184 static void unmapnotify(XEvent *e);
185 static void updatebarpos(void);
186 static void updatesizehints(Client *c);
187 static void updatetitle(Client *c);
188 static void view(const char *arg);
189 static int xerror(Display *dpy, XErrorEvent *ee);
190 static int xerrordummy(Display *dsply, XErrorEvent *ee);
191 static int xerrorstart(Display *dsply, XErrorEvent *ee);
192 static void zoom(const char *arg);
195 static char stext[256];
196 static double mwfact;
197 static int screen, sx, sy, sw, sh, wax, way, waw, wah;
198 static int (*xerrorxlib)(Display *, XErrorEvent *);
199 static unsigned int bh, bpos, ntags;
200 static unsigned int blw = 0;
201 static unsigned int ltidx = 0; /* default */
202 static unsigned int nlayouts = 0;
203 static unsigned int nrules = 0;
204 static unsigned int numlockmask = 0;
205 static void (*handler[LASTEvent]) (XEvent *) = {
206 [ButtonPress] = buttonpress,
207 [ConfigureRequest] = configurerequest,
208 [ConfigureNotify] = configurenotify,
209 [DestroyNotify] = destroynotify,
210 [EnterNotify] = enternotify,
211 [LeaveNotify] = leavenotify,
213 [KeyPress] = keypress,
214 [MappingNotify] = mappingnotify,
215 [MapRequest] = maprequest,
216 [PropertyNotify] = propertynotify,
217 [UnmapNotify] = unmapnotify
219 static Atom wmatom[WMLast], netatom[NetLast];
220 static Bool otherwm, readin;
221 static Bool running = True;
222 static Bool *seltags;
223 static Bool selscreen = True;
224 static Client *clients = NULL;
225 static Client *sel = NULL;
226 static Client *stack = NULL;
227 static Cursor cursor[CurLast];
230 static Window barwin, root;
231 static Regs *regs = NULL;
233 /* configuration, allows nested code to access above variables */
238 applyrules(Client *c) {
239 static char buf[512];
242 Bool matched = False;
243 XClassHint ch = { 0 };
246 XGetClassHint(dpy, c->win, &ch);
247 snprintf(buf, sizeof buf, "%s:%s:%s",
248 ch.res_class ? ch.res_class : "",
249 ch.res_name ? ch.res_name : "", c->name);
250 for(i = 0; i < nrules; i++)
251 if(regs[i].propregex && !regexec(regs[i].propregex, buf, 1, &tmp, 0)) {
252 c->isfloating = rules[i].isfloating;
253 for(j = 0; regs[i].tagregex && j < ntags; j++) {
254 if(!regexec(regs[i].tagregex, tags[j], 1, &tmp, 0)) {
265 for(i = 0; i < ntags; i++)
266 c->tags[i] = seltags[i];
273 for(c = clients; c; c = c->next)
278 layouts[ltidx].arrange();
292 attachstack(Client *c) {
301 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
306 buttonpress(XEvent *e) {
309 XButtonPressedEvent *ev = &e->xbutton;
311 if(barwin == ev->window) {
313 for(i = 0; i < ntags; i++) {
316 if(ev->button == Button1) {
317 if(ev->state & MODKEY)
322 else if(ev->button == Button3) {
323 if(ev->state & MODKEY)
331 if((ev->x < x + blw) && ev->button == Button1)
334 else if((c = getclient(ev->window))) {
336 if(CLEANMASK(ev->state) != MODKEY)
338 if(ev->button == Button1) {
339 if(!isarrange(floating) && !c->isfloating)
340 togglefloating(NULL);
345 else if(ev->button == Button2)
347 else if(ev->button == Button3 && !c->isfixed) {
348 if(!isarrange(floating) && !c->isfloating)
349 togglefloating(NULL);
360 XSetErrorHandler(xerrorstart);
362 /* this causes an error if some other window manager is running */
363 XSelectInput(dpy, root, SubstructureRedirectMask);
366 eprint("dwm: another window manager is already running\n");
368 XSetErrorHandler(NULL);
369 xerrorxlib = XSetErrorHandler(xerror);
381 XFreeFontSet(dpy, dc.font.set);
383 XFreeFont(dpy, dc.font.xfont);
384 XUngrabKey(dpy, AnyKey, AnyModifier, root);
385 XFreePixmap(dpy, dc.drawable);
387 XDestroyWindow(dpy, barwin);
388 XFreeCursor(dpy, cursor[CurNormal]);
389 XFreeCursor(dpy, cursor[CurResize]);
390 XFreeCursor(dpy, cursor[CurMove]);
391 XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime);
403 nrules = sizeof rules / sizeof rules[0];
404 regs = emallocz(nrules * sizeof(Regs));
405 for(i = 0; i < nrules; i++) {
407 reg = emallocz(sizeof(regex_t));
408 if(regcomp(reg, rules[i].prop, REG_EXTENDED))
411 regs[i].propregex = reg;
414 reg = emallocz(sizeof(regex_t));
415 if(regcomp(reg, rules[i].tags, REG_EXTENDED))
418 regs[i].tagregex = reg;
424 configure(Client *c) {
427 ce.type = ConfigureNotify;
435 ce.border_width = c->border;
437 ce.override_redirect = False;
438 XSendEvent(dpy, c->win, False, StructureNotifyMask, (XEvent *)&ce);
442 configurenotify(XEvent *e) {
443 XConfigureEvent *ev = &e->xconfigure;
445 if (ev->window == root && (ev->width != sw || ev->height != sh)) {
448 XFreePixmap(dpy, dc.drawable);
449 dc.drawable = XCreatePixmap(dpy, root, sw, bh, DefaultDepth(dpy, screen));
450 XResizeWindow(dpy, barwin, sw, bh);
457 configurerequest(XEvent *e) {
459 XConfigureRequestEvent *ev = &e->xconfigurerequest;
462 if((c = getclient(ev->window))) {
464 if(ev->value_mask & CWBorderWidth)
465 c->border = ev->border_width;
466 if(c->isfixed || c->isfloating || isarrange(floating)) {
467 if(ev->value_mask & CWX)
469 if(ev->value_mask & CWY)
471 if(ev->value_mask & CWWidth)
473 if(ev->value_mask & CWHeight)
475 if((c->x + c->w) > sw && c->isfloating)
476 c->x = sw / 2 - c->w / 2; /* center in x direction */
477 if((c->y + c->h) > sh && c->isfloating)
478 c->y = sh / 2 - c->h / 2; /* center in y direction */
479 if((ev->value_mask & (CWX | CWY))
480 && !(ev->value_mask & (CWWidth | CWHeight)))
483 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h);
491 wc.width = ev->width;
492 wc.height = ev->height;
493 wc.border_width = ev->border_width;
494 wc.sibling = ev->above;
495 wc.stack_mode = ev->detail;
496 XConfigureWindow(dpy, ev->window, ev->value_mask, &wc);
502 destroynotify(XEvent *e) {
504 XDestroyWindowEvent *ev = &e->xdestroywindow;
506 if((c = getclient(ev->window)))
513 c->prev->next = c->next;
515 c->next->prev = c->prev;
518 c->next = c->prev = NULL;
522 detachstack(Client *c) {
525 for(tc=&stack; *tc && *tc != c; tc=&(*tc)->snext);
534 for(i = 0; i < ntags; i++) {
535 dc.w = textw(tags[i]);
537 drawtext(tags[i], dc.sel);
538 drawsquare(sel && sel->tags[i], isoccupied(i), dc.sel);
541 drawtext(tags[i], dc.norm);
542 drawsquare(sel && sel->tags[i], isoccupied(i), dc.norm);
547 drawtext(layouts[ltidx].symbol, dc.norm);
555 drawtext(stext, dc.norm);
556 if((dc.w = dc.x - x) > bh) {
559 drawtext(sel->name, dc.sel);
560 drawsquare(sel->ismax, sel->isfloating, dc.sel);
563 drawtext(NULL, dc.norm);
565 XCopyArea(dpy, dc.drawable, barwin, dc.gc, 0, 0, sw, bh, 0, 0);
570 drawsquare(Bool filled, Bool empty, unsigned long col[ColLast]) {
573 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
575 gcv.foreground = col[ColFG];
576 XChangeGC(dpy, dc.gc, GCForeground, &gcv);
577 x = (dc.font.ascent + dc.font.descent + 2) / 4;
581 r.width = r.height = x + 1;
582 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
585 r.width = r.height = x;
586 XDrawRectangles(dpy, dc.drawable, dc.gc, &r, 1);
591 drawtext(const char *text, unsigned long col[ColLast]) {
593 static char buf[256];
594 unsigned int len, olen;
595 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
597 XSetForeground(dpy, dc.gc, col[ColBG]);
598 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
602 olen = len = strlen(text);
603 if(len >= sizeof buf)
604 len = sizeof buf - 1;
605 memcpy(buf, text, len);
607 h = dc.font.ascent + dc.font.descent;
608 y = dc.y + (dc.h / 2) - (h / 2) + dc.font.ascent;
610 /* shorten text if necessary */
611 while(len && (w = textnw(buf, len)) > dc.w - h)
622 return; /* too long */
623 XSetForeground(dpy, dc.gc, col[ColFG]);
625 XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
627 XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
631 emallocz(unsigned int size) {
632 void *res = calloc(1, size);
635 eprint("fatal: could not malloc() %u bytes\n", size);
640 enternotify(XEvent *e) {
642 XCrossingEvent *ev = &e->xcrossing;
644 if(ev->mode != NotifyNormal || ev->detail == NotifyInferior)
646 if((c = getclient(ev->window)))
648 else if(ev->window == root) {
655 eprint(const char *errstr, ...) {
658 va_start(ap, errstr);
659 vfprintf(stderr, errstr, ap);
666 XExposeEvent *ev = &e->xexpose;
669 if(barwin == ev->window)
675 floating(void) { /* default floating layout */
678 for(c = clients; c; c = c->next)
680 resize(c, c->x, c->y, c->w, c->h, True);
685 if((!c && selscreen) || (c && !isvisible(c)))
686 for(c = stack; c && !isvisible(c); c = c->snext);
687 if(sel && sel != c) {
688 grabbuttons(sel, False);
689 XSetWindowBorder(dpy, sel->win, dc.norm[ColBorder]);
694 grabbuttons(c, True);
701 XSetWindowBorder(dpy, c->win, dc.sel[ColBorder]);
702 XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
705 XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
709 focusnext(const char *arg) {
714 for(c = sel->next; c && !isvisible(c); c = c->next);
716 for(c = clients; c && !isvisible(c); c = c->next);
724 focusprev(const char *arg) {
729 for(c = sel->prev; c && !isvisible(c); c = c->prev);
731 for(c = clients; c && c->next; c = c->next);
732 for(; c && !isvisible(c); c = c->prev);
741 getclient(Window w) {
744 for(c = clients; c && c->win != w; c = c->next);
749 getcolor(const char *colstr) {
750 Colormap cmap = DefaultColormap(dpy, screen);
753 if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
754 eprint("error, cannot allocate color '%s'\n", colstr);
762 unsigned char *p = NULL;
763 unsigned long n, extra;
766 status = XGetWindowProperty(dpy, w, wmatom[WMState], 0L, 2L, False, wmatom[WMState],
767 &real, &format, &n, &extra, (unsigned char **)&p);
768 if(status != Success)
777 gettextprop(Window w, Atom atom, char *text, unsigned int size) {
782 if(!text || size == 0)
785 XGetTextProperty(dpy, w, &name, atom);
788 if(name.encoding == XA_STRING)
789 strncpy(text, (char *)name.value, size - 1);
791 if(XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success
794 strncpy(text, *list, size - 1);
795 XFreeStringList(list);
798 text[size - 1] = '\0';
804 grabbuttons(Client *c, Bool focused) {
805 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
808 XGrabButton(dpy, Button1, MODKEY, c->win, False, BUTTONMASK,
809 GrabModeAsync, GrabModeSync, None, None);
810 XGrabButton(dpy, Button1, MODKEY | LockMask, c->win, False, BUTTONMASK,
811 GrabModeAsync, GrabModeSync, None, None);
812 XGrabButton(dpy, Button1, MODKEY | numlockmask, c->win, False, BUTTONMASK,
813 GrabModeAsync, GrabModeSync, None, None);
814 XGrabButton(dpy, Button1, MODKEY | numlockmask | LockMask, c->win, False, BUTTONMASK,
815 GrabModeAsync, GrabModeSync, None, None);
817 XGrabButton(dpy, Button2, MODKEY, c->win, False, BUTTONMASK,
818 GrabModeAsync, GrabModeSync, None, None);
819 XGrabButton(dpy, Button2, MODKEY | LockMask, c->win, False, BUTTONMASK,
820 GrabModeAsync, GrabModeSync, None, None);
821 XGrabButton(dpy, Button2, MODKEY | numlockmask, c->win, False, BUTTONMASK,
822 GrabModeAsync, GrabModeSync, None, None);
823 XGrabButton(dpy, Button2, MODKEY | numlockmask | LockMask, c->win, False, BUTTONMASK,
824 GrabModeAsync, GrabModeSync, None, None);
826 XGrabButton(dpy, Button3, MODKEY, c->win, False, BUTTONMASK,
827 GrabModeAsync, GrabModeSync, None, None);
828 XGrabButton(dpy, Button3, MODKEY | LockMask, c->win, False, BUTTONMASK,
829 GrabModeAsync, GrabModeSync, None, None);
830 XGrabButton(dpy, Button3, MODKEY | numlockmask, c->win, False, BUTTONMASK,
831 GrabModeAsync, GrabModeSync, None, None);
832 XGrabButton(dpy, Button3, MODKEY | numlockmask | LockMask, c->win, False, BUTTONMASK,
833 GrabModeAsync, GrabModeSync, None, None);
836 XGrabButton(dpy, AnyButton, AnyModifier, c->win, False, BUTTONMASK,
837 GrabModeAsync, GrabModeSync, None, None);
841 idxoftag(const char *tag) {
844 for(i = 0; i < ntags; i++)
851 initfont(const char *fontstr) {
852 char *def, **missing;
857 XFreeFontSet(dpy, dc.font.set);
858 dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
861 fprintf(stderr, "dwm: missing fontset: %s\n", missing[n]);
862 XFreeStringList(missing);
865 XFontSetExtents *font_extents;
866 XFontStruct **xfonts;
868 dc.font.ascent = dc.font.descent = 0;
869 font_extents = XExtentsOfFontSet(dc.font.set);
870 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
871 for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
872 if(dc.font.ascent < (*xfonts)->ascent)
873 dc.font.ascent = (*xfonts)->ascent;
874 if(dc.font.descent < (*xfonts)->descent)
875 dc.font.descent = (*xfonts)->descent;
881 XFreeFont(dpy, dc.font.xfont);
882 dc.font.xfont = NULL;
883 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr))
884 || !(dc.font.xfont = XLoadQueryFont(dpy, "fixed")))
885 eprint("error, cannot load font: '%s'\n", fontstr);
886 dc.font.ascent = dc.font.xfont->ascent;
887 dc.font.descent = dc.font.xfont->descent;
889 dc.font.height = dc.font.ascent + dc.font.descent;
893 isarrange(void (*func)())
895 return func == layouts[ltidx].arrange;
899 isoccupied(unsigned int t) {
902 for(c = clients; c; c = c->next)
909 isprotodel(Client *c) {
914 if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
915 for(i = 0; !ret && i < n; i++)
916 if(protocols[i] == wmatom[WMDelete])
924 isvisible(Client *c) {
927 for(i = 0; i < ntags; i++)
928 if(c->tags[i] && seltags[i])
934 keypress(XEvent *e) {
936 unsigned int len = sizeof keys / sizeof keys[0];
942 if(!e) { /* grabkeys */
943 XUngrabKey(dpy, AnyKey, AnyModifier, root);
944 for(i = 0; i < len; i++) {
945 code = XKeysymToKeycode(dpy, keys[i].keysym);
946 XGrabKey(dpy, code, keys[i].mod, root, True,
947 GrabModeAsync, GrabModeAsync);
948 XGrabKey(dpy, code, keys[i].mod | LockMask, root, True,
949 GrabModeAsync, GrabModeAsync);
950 XGrabKey(dpy, code, keys[i].mod | numlockmask, root, True,
951 GrabModeAsync, GrabModeAsync);
952 XGrabKey(dpy, code, keys[i].mod | numlockmask | LockMask, root, True,
953 GrabModeAsync, GrabModeAsync);
958 keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
959 for(i = 0; i < len; i++)
960 if(keysym == keys[i].keysym
961 && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state))
964 keys[i].func(keys[i].arg);
969 killclient(const char *arg) {
974 if(isprotodel(sel)) {
975 ev.type = ClientMessage;
976 ev.xclient.window = sel->win;
977 ev.xclient.message_type = wmatom[WMProtocols];
978 ev.xclient.format = 32;
979 ev.xclient.data.l[0] = wmatom[WMDelete];
980 ev.xclient.data.l[1] = CurrentTime;
981 XSendEvent(dpy, sel->win, False, NoEventMask, &ev);
984 XKillClient(dpy, sel->win);
988 leavenotify(XEvent *e) {
989 XCrossingEvent *ev = &e->xcrossing;
991 if((ev->window == root) && !ev->same_screen) {
998 manage(Window w, XWindowAttributes *wa) {
1000 Client *c, *t = NULL;
1005 c = emallocz(sizeof(Client));
1006 c->tags = emallocz(ntags * sizeof(Bool));
1012 c->oldborder = wa->border_width;
1013 if(c->w == sw && c->h == sh) {
1016 c->border = wa->border_width;
1019 if(c->x + c->w + 2 * c->border > wax + waw)
1020 c->x = wax + waw - c->w - 2 * c->border;
1021 if(c->y + c->h + 2 * c->border > way + wah)
1022 c->y = way + wah - c->h - 2 * c->border;
1027 c->border = BORDERPX;
1029 wc.border_width = c->border;
1030 XConfigureWindow(dpy, w, CWBorderWidth, &wc);
1031 XSetWindowBorder(dpy, w, dc.norm[ColBorder]);
1032 configure(c); /* propagates border_width, if size doesn't change */
1034 XSelectInput(dpy, w,
1035 StructureNotifyMask | PropertyChangeMask | EnterWindowMask);
1036 grabbuttons(c, False);
1038 if((rettrans = XGetTransientForHint(dpy, w, &trans) == Success))
1039 for(t = clients; t && t->win != trans; t = t->next);
1041 for(i = 0; i < ntags; i++)
1042 c->tags[i] = t->tags[i];
1045 c->isfloating = (rettrans == Success) || c->isfixed;
1048 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h); /* some windows require this */
1050 XMapWindow(dpy, c->win);
1051 setclientstate(c, NormalState);
1056 mappingnotify(XEvent *e) {
1057 XMappingEvent *ev = &e->xmapping;
1059 XRefreshKeyboardMapping(ev);
1060 if(ev->request == MappingKeyboard)
1065 maprequest(XEvent *e) {
1066 static XWindowAttributes wa;
1067 XMapRequestEvent *ev = &e->xmaprequest;
1069 if(!XGetWindowAttributes(dpy, ev->window, &wa))
1071 if(wa.override_redirect)
1073 if(!getclient(ev->window))
1074 manage(ev->window, &wa);
1078 movemouse(Client *c) {
1079 int x1, y1, ocx, ocy, di, nx, ny;
1086 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1087 None, cursor[CurMove], CurrentTime) != GrabSuccess)
1090 XQueryPointer(dpy, root, &dummy, &dummy, &x1, &y1, &di, &di, &dui);
1092 XMaskEvent(dpy, MOUSEMASK | ExposureMask | SubstructureRedirectMask, &ev);
1095 XUngrabPointer(dpy, CurrentTime);
1097 case ConfigureRequest:
1100 handler[ev.type](&ev);
1104 nx = ocx + (ev.xmotion.x - x1);
1105 ny = ocy + (ev.xmotion.y - y1);
1106 if(abs(wax + nx) < SNAP)
1108 else if(abs((wax + waw) - (nx + c->w + 2 * c->border)) < SNAP)
1109 nx = wax + waw - c->w - 2 * c->border;
1110 if(abs(way - ny) < SNAP)
1112 else if(abs((way + wah) - (ny + c->h + 2 * c->border)) < SNAP)
1113 ny = way + wah - c->h - 2 * c->border;
1114 resize(c, nx, ny, c->w, c->h, False);
1121 nexttiled(Client *c) {
1122 for(; c && (c->isfloating || !isvisible(c)); c = c->next);
1127 propertynotify(XEvent *e) {
1130 XPropertyEvent *ev = &e->xproperty;
1132 if(ev->state == PropertyDelete)
1133 return; /* ignore */
1134 if((c = getclient(ev->window))) {
1137 case XA_WM_TRANSIENT_FOR:
1138 XGetTransientForHint(dpy, c->win, &trans);
1139 if(!c->isfloating && (c->isfloating = (getclient(trans) != NULL)))
1142 case XA_WM_NORMAL_HINTS:
1146 if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
1155 quit(const char *arg) {
1156 readin = running = False;
1160 resize(Client *c, int x, int y, int w, int h, Bool sizehints) {
1161 double dx, dy, max, min, ratio;
1165 if(c->minay > 0 && c->maxay > 0 && (h - c->baseh) > 0 && (w - c->basew) > 0) {
1166 dx = (double)(w - c->basew);
1167 dy = (double)(h - c->baseh);
1168 min = (double)(c->minax) / (double)(c->minay);
1169 max = (double)(c->maxax) / (double)(c->maxay);
1171 if(max > 0 && min > 0 && ratio > 0) {
1173 dy = (dx * min + dy) / (min * min + 1);
1175 w = (int)dx + c->basew;
1176 h = (int)dy + c->baseh;
1178 else if(ratio > max) {
1179 dy = (dx * min + dy) / (max * max + 1);
1181 w = (int)dx + c->basew;
1182 h = (int)dy + c->baseh;
1186 if(c->minw && w < c->minw)
1188 if(c->minh && h < c->minh)
1190 if(c->maxw && w > c->maxw)
1192 if(c->maxh && h > c->maxh)
1195 w -= (w - c->basew) % c->incw;
1197 h -= (h - c->baseh) % c->inch;
1199 if(w <= 0 || h <= 0)
1201 /* offscreen appearance fixes */
1203 x = sw - w - 2 * c->border;
1205 y = sh - h - 2 * c->border;
1206 if(x + w + 2 * c->border < sx)
1208 if(y + h + 2 * c->border < sy)
1210 if(c->x != x || c->y != y || c->w != w || c->h != h) {
1213 c->w = wc.width = w;
1214 c->h = wc.height = h;
1215 wc.border_width = c->border;
1216 XConfigureWindow(dpy, c->win, CWX | CWY | CWWidth | CWHeight | CWBorderWidth, &wc);
1223 resizemouse(Client *c) {
1230 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1231 None, cursor[CurResize], CurrentTime) != GrabSuccess)
1234 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->border - 1, c->h + c->border - 1);
1236 XMaskEvent(dpy, MOUSEMASK | ExposureMask | SubstructureRedirectMask , &ev);
1239 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0,
1240 c->w + c->border - 1, c->h + c->border - 1);
1241 XUngrabPointer(dpy, CurrentTime);
1242 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1244 case ConfigureRequest:
1247 handler[ev.type](&ev);
1251 if((nw = ev.xmotion.x - ocx - 2 * c->border + 1) <= 0)
1253 if((nh = ev.xmotion.y - ocy - 2 * c->border + 1) <= 0)
1255 resize(c, c->x, c->y, nw, nh, True);
1270 if(sel->isfloating || isarrange(floating))
1271 XRaiseWindow(dpy, sel->win);
1272 if(!isarrange(floating)) {
1273 wc.stack_mode = Below;
1274 wc.sibling = barwin;
1275 if(!sel->isfloating) {
1276 XConfigureWindow(dpy, sel->win, CWSibling | CWStackMode, &wc);
1277 wc.sibling = sel->win;
1279 for(c = nexttiled(clients); c; c = nexttiled(c->next)) {
1282 XConfigureWindow(dpy, c->win, CWSibling | CWStackMode, &wc);
1283 wc.sibling = c->win;
1287 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1297 /* main event loop, also reads status text from stdin */
1299 xfd = ConnectionNumber(dpy);
1304 FD_SET(STDIN_FILENO, &rd);
1306 if(select(xfd + 1, &rd, NULL, NULL, NULL) == -1) {
1309 eprint("select failed\n");
1311 if(FD_ISSET(STDIN_FILENO, &rd)) {
1312 switch(r = read(STDIN_FILENO, stext, sizeof stext - 1)) {
1314 strncpy(stext, strerror(errno), sizeof stext - 1);
1315 stext[sizeof stext - 1] = '\0';
1319 strncpy(stext, "EOF", 4);
1323 for(stext[r] = '\0', p = stext + strlen(stext) - 1; p >= stext && *p == '\n'; *p-- = '\0');
1324 for(; p >= stext && *p != '\n'; --p);
1326 strncpy(stext, p + 1, sizeof stext);
1330 while(XPending(dpy)) {
1331 XNextEvent(dpy, &ev);
1332 if(handler[ev.type])
1333 (handler[ev.type])(&ev); /* call handler */
1340 unsigned int i, num;
1341 Window *wins, d1, d2;
1342 XWindowAttributes wa;
1345 if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1346 for(i = 0; i < num; i++) {
1347 if(!XGetWindowAttributes(dpy, wins[i], &wa)
1348 || wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1350 if(wa.map_state == IsViewable || getstate(wins[i]) == IconicState)
1351 manage(wins[i], &wa);
1353 for(i = 0; i < num; i++) { /* now the transients */
1354 if(!XGetWindowAttributes(dpy, wins[i], &wa))
1356 if(XGetTransientForHint(dpy, wins[i], &d1)
1357 && (wa.map_state == IsViewable || getstate(wins[i]) == IconicState))
1358 manage(wins[i], &wa);
1366 setclientstate(Client *c, long state) {
1367 long data[] = {state, None};
1369 XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1370 PropModeReplace, (unsigned char *)data, 2);
1374 setlayout(const char *arg) {
1378 if(++ltidx == nlayouts)
1382 for(i = 0; i < nlayouts; i++)
1383 if(!strcmp(arg, layouts[i].symbol))
1396 setmwfact(const char *arg) {
1399 if(!isarrange(tile))
1401 /* arg handling, manipulate mwfact */
1404 else if(1 == sscanf(arg, "%lf", &delta)) {
1405 if(arg[0] != '+' && arg[0] != '-')
1411 else if(mwfact > 0.9)
1419 unsigned int i, j, mask;
1421 XModifierKeymap *modmap;
1422 XSetWindowAttributes wa;
1425 wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1426 wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1427 wmatom[WMName] = XInternAtom(dpy, "WM_NAME", False);
1428 wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1429 netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1430 netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1431 XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1432 PropModeReplace, (unsigned char *) netatom, NetLast);
1435 cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1436 cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1437 cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1441 sw = DisplayWidth(dpy, screen);
1442 sh = DisplayHeight(dpy, screen);
1444 /* init modifier map */
1445 modmap = XGetModifierMapping(dpy);
1446 for(i = 0; i < 8; i++)
1447 for(j = 0; j < modmap->max_keypermod; j++) {
1448 if(modmap->modifiermap[i * modmap->max_keypermod + j]
1449 == XKeysymToKeycode(dpy, XK_Num_Lock))
1450 numlockmask = (1 << i);
1452 XFreeModifiermap(modmap);
1454 /* select for events */
1455 wa.event_mask = SubstructureRedirectMask | SubstructureNotifyMask
1456 | EnterWindowMask | LeaveWindowMask | StructureNotifyMask;
1457 wa.cursor = cursor[CurNormal];
1458 XChangeWindowAttributes(dpy, root, CWEventMask | CWCursor, &wa);
1459 XSelectInput(dpy, root, wa.event_mask);
1466 for(ntags = 0; tags[ntags]; ntags++);
1467 seltags = emallocz(sizeof(Bool) * ntags);
1470 /* init appearance */
1471 dc.norm[ColBorder] = getcolor(NORMBORDERCOLOR);
1472 dc.norm[ColBG] = getcolor(NORMBGCOLOR);
1473 dc.norm[ColFG] = getcolor(NORMFGCOLOR);
1474 dc.sel[ColBorder] = getcolor(SELBORDERCOLOR);
1475 dc.sel[ColBG] = getcolor(SELBGCOLOR);
1476 dc.sel[ColFG] = getcolor(SELFGCOLOR);
1478 dc.h = bh = dc.font.height + 2;
1482 nlayouts = sizeof layouts / sizeof layouts[0];
1483 for(blw = i = 0; i < nlayouts; i++) {
1484 j = textw(layouts[i].symbol);
1491 wa.override_redirect = 1;
1492 wa.background_pixmap = ParentRelative;
1493 wa.event_mask = ButtonPressMask | ExposureMask;
1494 barwin = XCreateWindow(dpy, root, sx, sy, sw, bh, 0,
1495 DefaultDepth(dpy, screen), CopyFromParent, DefaultVisual(dpy, screen),
1496 CWOverrideRedirect | CWBackPixmap | CWEventMask, &wa);
1497 XDefineCursor(dpy, barwin, cursor[CurNormal]);
1499 XMapRaised(dpy, barwin);
1500 strcpy(stext, "dwm-"VERSION);
1501 dc.drawable = XCreatePixmap(dpy, root, sw, bh, DefaultDepth(dpy, screen));
1502 dc.gc = XCreateGC(dpy, root, 0, 0);
1503 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
1505 XSetFont(dpy, dc.gc, dc.font.xfont->fid);
1507 /* multihead support */
1508 selscreen = XQueryPointer(dpy, root, &w, &w, &i, &i, &i, &i, &mask);
1512 spawn(const char *arg) {
1513 static char *shell = NULL;
1515 if(!shell && !(shell = getenv("SHELL")))
1519 /* The double-fork construct avoids zombie processes and keeps the code
1520 * clean from stupid signal handlers. */
1524 close(ConnectionNumber(dpy));
1526 execl(shell, shell, "-c", arg, (char *)NULL);
1527 fprintf(stderr, "dwm: execl '%s -c %s'", shell, arg);
1536 tag(const char *arg) {
1541 for(i = 0; i < ntags; i++)
1542 sel->tags[i] = arg == NULL;
1544 if(i >= 0 && i < ntags)
1545 sel->tags[i] = True;
1550 textnw(const char *text, unsigned int len) {
1554 XmbTextExtents(dc.font.set, text, len, NULL, &r);
1557 return XTextWidth(dc.font.xfont, text, len);
1561 textw(const char *text) {
1562 return textnw(text, strlen(text)) + dc.font.height;
1567 unsigned int i, n, nx, ny, nw, nh, mw, th;
1570 for(n = 0, c = nexttiled(clients); c; c = nexttiled(c->next))
1574 mw = (n == 1) ? waw : mwfact * waw;
1575 th = (n > 1) ? wah / (n - 1) : 0;
1576 if(n > 1 && th < bh)
1581 for(i = 0, c = nexttiled(clients); c; c = nexttiled(c->next), i++) {
1583 if(i == 0) { /* master */
1584 nw = mw - 2 * c->border;
1585 nh = wah - 2 * c->border;
1587 else { /* tile window */
1592 nw = waw - mw - 2 * c->border;
1593 if(i + 1 == n) /* remainder */
1594 nh = (way + wah) - ny - 2 * c->border;
1596 nh = th - 2 * c->border;
1598 resize(c, nx, ny, nw, nh, RESIZEHINTS);
1599 if(n > 1 && th != wah)
1600 ny += nh + 2 * c->border;
1605 togglebar(const char *arg) {
1607 bpos = (BARPOS == BarOff) ? BarTop : BARPOS;
1615 togglefloating(const char *arg) {
1618 sel->isfloating = !sel->isfloating;
1620 resize(sel, sel->x, sel->y, sel->w, sel->h, True);
1625 togglemax(const char *arg) {
1628 if(!sel || (!isarrange(floating) && !sel->isfloating) || sel->isfixed)
1630 if((sel->ismax = !sel->ismax)) {
1635 resize(sel, wax, way, waw - 2 * sel->border, wah - 2 * sel->border, True);
1638 resize(sel, sel->rx, sel->ry, sel->rw, sel->rh, True);
1640 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1644 toggletag(const char *arg) {
1650 sel->tags[i] = !sel->tags[i];
1651 for(j = 0; j < ntags && !sel->tags[j]; j++);
1653 sel->tags[i] = True;
1658 toggleview(const char *arg) {
1662 seltags[i] = !seltags[i];
1663 for(j = 0; j < ntags && !seltags[j]; j++);
1665 seltags[i] = True; /* cannot toggle last view */
1673 XMoveWindow(dpy, c->win, c->x, c->y);
1674 c->isbanned = False;
1678 unmanage(Client *c) {
1681 wc.border_width = c->oldborder;
1682 /* The server grab construct avoids race conditions. */
1684 XSetErrorHandler(xerrordummy);
1685 XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
1690 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1691 setclientstate(c, WithdrawnState);
1695 XSetErrorHandler(xerror);
1701 unmapnotify(XEvent *e) {
1703 XUnmapEvent *ev = &e->xunmap;
1705 if((c = getclient(ev->window)))
1710 updatebarpos(void) {
1721 XMoveWindow(dpy, barwin, sx, sy);
1725 XMoveWindow(dpy, barwin, sx, sy + wah);
1728 XMoveWindow(dpy, barwin, sx, sy - bh);
1732 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1736 updatesizehints(Client *c) {
1740 if(!XGetWMNormalHints(dpy, c->win, &size, &msize) || !size.flags)
1742 c->flags = size.flags;
1743 if(c->flags & PBaseSize) {
1744 c->basew = size.base_width;
1745 c->baseh = size.base_height;
1747 else if(c->flags & PMinSize) {
1748 c->basew = size.min_width;
1749 c->baseh = size.min_height;
1752 c->basew = c->baseh = 0;
1753 if(c->flags & PResizeInc) {
1754 c->incw = size.width_inc;
1755 c->inch = size.height_inc;
1758 c->incw = c->inch = 0;
1759 if(c->flags & PMaxSize) {
1760 c->maxw = size.max_width;
1761 c->maxh = size.max_height;
1764 c->maxw = c->maxh = 0;
1765 if(c->flags & PMinSize) {
1766 c->minw = size.min_width;
1767 c->minh = size.min_height;
1769 else if(c->flags & PBaseSize) {
1770 c->minw = size.base_width;
1771 c->minh = size.base_height;
1774 c->minw = c->minh = 0;
1775 if(c->flags & PAspect) {
1776 c->minax = size.min_aspect.x;
1777 c->maxax = size.max_aspect.x;
1778 c->minay = size.min_aspect.y;
1779 c->maxay = size.max_aspect.y;
1782 c->minax = c->maxax = c->minay = c->maxay = 0;
1783 c->isfixed = (c->maxw && c->minw && c->maxh && c->minh
1784 && c->maxw == c->minw && c->maxh == c->minh);
1788 updatetitle(Client *c) {
1789 if(!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
1790 gettextprop(c->win, wmatom[WMName], c->name, sizeof c->name);
1793 /* There's no way to check accesses to destroyed windows, thus those cases are
1794 * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
1795 * default error handler, which may call exit. */
1797 xerror(Display *dpy, XErrorEvent *ee) {
1798 if(ee->error_code == BadWindow
1799 || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1800 || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1801 || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1802 || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1803 || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1804 || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1805 || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1807 fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1808 ee->request_code, ee->error_code);
1809 return xerrorxlib(dpy, ee); /* may call exit */
1813 xerrordummy(Display *dsply, XErrorEvent *ee) {
1817 /* Startup Error handler to check if another window manager
1818 * is already running. */
1820 xerrorstart(Display *dsply, XErrorEvent *ee) {
1826 view(const char *arg) {
1829 for(i = 0; i < ntags; i++)
1830 seltags[i] = arg == NULL;
1832 if(i >= 0 && i < ntags)
1838 zoom(const char *arg) {
1841 if(!sel || !isarrange(tile) || sel->isfloating)
1843 if((c = sel) == nexttiled(clients))
1844 if(!(c = nexttiled(c->next)))
1853 main(int argc, char *argv[]) {
1854 if(argc == 2 && !strcmp("-v", argv[1]))
1855 eprint("dwm-"VERSION", © 2006-2007 A. R. Garbe, S. van Dijk, J. Salmi, P. Hruby, S. Nagy\n");
1857 eprint("usage: dwm [-v]\n");
1859 setlocale(LC_CTYPE, "");
1860 if(!(dpy = XOpenDisplay(0)))
1861 eprint("dwm: cannot open display\n");
1862 screen = DefaultScreen(dpy);
1863 root = RootWindow(dpy, screen);