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 && (isarrange(floating) || c->isfloating)) {
342 else if(ev->button == Button2)
344 else if(ev->button == Button3
345 && (isarrange(floating) || c->isfloating) && !c->isfixed)
356 XSetErrorHandler(xerrorstart);
358 /* this causes an error if some other window manager is running */
359 XSelectInput(dpy, root, SubstructureRedirectMask);
362 eprint("dwm: another window manager is already running\n");
364 XSetErrorHandler(NULL);
365 xerrorxlib = XSetErrorHandler(xerror);
377 XFreeFontSet(dpy, dc.font.set);
379 XFreeFont(dpy, dc.font.xfont);
380 XUngrabKey(dpy, AnyKey, AnyModifier, root);
381 XFreePixmap(dpy, dc.drawable);
383 XDestroyWindow(dpy, barwin);
384 XFreeCursor(dpy, cursor[CurNormal]);
385 XFreeCursor(dpy, cursor[CurResize]);
386 XFreeCursor(dpy, cursor[CurMove]);
387 XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime);
399 nrules = sizeof rules / sizeof rules[0];
400 regs = emallocz(nrules * sizeof(Regs));
401 for(i = 0; i < nrules; i++) {
403 reg = emallocz(sizeof(regex_t));
404 if(regcomp(reg, rules[i].prop, REG_EXTENDED))
407 regs[i].propregex = reg;
410 reg = emallocz(sizeof(regex_t));
411 if(regcomp(reg, rules[i].tags, REG_EXTENDED))
414 regs[i].tagregex = reg;
420 configure(Client *c) {
423 ce.type = ConfigureNotify;
431 ce.border_width = c->border;
433 ce.override_redirect = False;
434 XSendEvent(dpy, c->win, False, StructureNotifyMask, (XEvent *)&ce);
438 configurenotify(XEvent *e) {
439 XConfigureEvent *ev = &e->xconfigure;
441 if (ev->window == root && (ev->width != sw || ev->height != sh)) {
444 XFreePixmap(dpy, dc.drawable);
445 dc.drawable = XCreatePixmap(dpy, root, sw, bh, DefaultDepth(dpy, screen));
446 XResizeWindow(dpy, barwin, sw, bh);
453 configurerequest(XEvent *e) {
455 XConfigureRequestEvent *ev = &e->xconfigurerequest;
458 if((c = getclient(ev->window))) {
460 if(ev->value_mask & CWBorderWidth)
461 c->border = ev->border_width;
462 if(c->isfixed || c->isfloating || isarrange(floating)) {
463 if(ev->value_mask & CWX)
465 if(ev->value_mask & CWY)
467 if(ev->value_mask & CWWidth)
469 if(ev->value_mask & CWHeight)
471 if((c->x + c->w) > sw && c->isfloating)
472 c->x = sw / 2 - c->w / 2; /* center in x direction */
473 if((c->y + c->h) > sh && c->isfloating)
474 c->y = sh / 2 - c->h / 2; /* center in y direction */
475 if((ev->value_mask & (CWX | CWY))
476 && !(ev->value_mask & (CWWidth | CWHeight)))
479 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h);
487 wc.width = ev->width;
488 wc.height = ev->height;
489 wc.border_width = ev->border_width;
490 wc.sibling = ev->above;
491 wc.stack_mode = ev->detail;
492 XConfigureWindow(dpy, ev->window, ev->value_mask, &wc);
498 destroynotify(XEvent *e) {
500 XDestroyWindowEvent *ev = &e->xdestroywindow;
502 if((c = getclient(ev->window)))
509 c->prev->next = c->next;
511 c->next->prev = c->prev;
514 c->next = c->prev = NULL;
518 detachstack(Client *c) {
521 for(tc=&stack; *tc && *tc != c; tc=&(*tc)->snext);
530 for(i = 0; i < ntags; i++) {
531 dc.w = textw(tags[i]);
533 drawtext(tags[i], dc.sel);
534 drawsquare(sel && sel->tags[i], isoccupied(i), dc.sel);
537 drawtext(tags[i], dc.norm);
538 drawsquare(sel && sel->tags[i], isoccupied(i), dc.norm);
543 drawtext(layouts[ltidx].symbol, dc.norm);
551 drawtext(stext, dc.norm);
552 if((dc.w = dc.x - x) > bh) {
555 drawtext(sel->name, dc.sel);
556 drawsquare(sel->ismax, sel->isfloating, dc.sel);
559 drawtext(NULL, dc.norm);
561 XCopyArea(dpy, dc.drawable, barwin, dc.gc, 0, 0, sw, bh, 0, 0);
566 drawsquare(Bool filled, Bool empty, unsigned long col[ColLast]) {
569 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
571 gcv.foreground = col[ColFG];
572 XChangeGC(dpy, dc.gc, GCForeground, &gcv);
573 x = (dc.font.ascent + dc.font.descent + 2) / 4;
577 r.width = r.height = x + 1;
578 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
581 r.width = r.height = x;
582 XDrawRectangles(dpy, dc.drawable, dc.gc, &r, 1);
587 drawtext(const char *text, unsigned long col[ColLast]) {
589 static char buf[256];
590 unsigned int len, olen;
591 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
593 XSetForeground(dpy, dc.gc, col[ColBG]);
594 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
598 olen = len = strlen(text);
599 if(len >= sizeof buf)
600 len = sizeof buf - 1;
601 memcpy(buf, text, len);
603 h = dc.font.ascent + dc.font.descent;
604 y = dc.y + (dc.h / 2) - (h / 2) + dc.font.ascent;
606 /* shorten text if necessary */
607 while(len && (w = textnw(buf, len)) > dc.w - h)
618 return; /* too long */
619 XSetForeground(dpy, dc.gc, col[ColFG]);
621 XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
623 XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
627 emallocz(unsigned int size) {
628 void *res = calloc(1, size);
631 eprint("fatal: could not malloc() %u bytes\n", size);
636 enternotify(XEvent *e) {
638 XCrossingEvent *ev = &e->xcrossing;
640 if(ev->mode != NotifyNormal || ev->detail == NotifyInferior)
642 if((c = getclient(ev->window)))
644 else if(ev->window == root) {
651 eprint(const char *errstr, ...) {
654 va_start(ap, errstr);
655 vfprintf(stderr, errstr, ap);
662 XExposeEvent *ev = &e->xexpose;
665 if(barwin == ev->window)
671 floating(void) { /* default floating layout */
674 for(c = clients; c; c = c->next)
676 resize(c, c->x, c->y, c->w, c->h, True);
681 if((!c && selscreen) || (c && !isvisible(c)))
682 for(c = stack; c && !isvisible(c); c = c->snext);
683 if(sel && sel != c) {
684 grabbuttons(sel, False);
685 XSetWindowBorder(dpy, sel->win, dc.norm[ColBorder]);
690 grabbuttons(c, True);
697 XSetWindowBorder(dpy, c->win, dc.sel[ColBorder]);
698 XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
701 XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
705 focusnext(const char *arg) {
710 for(c = sel->next; c && !isvisible(c); c = c->next);
712 for(c = clients; c && !isvisible(c); c = c->next);
720 focusprev(const char *arg) {
725 for(c = sel->prev; c && !isvisible(c); c = c->prev);
727 for(c = clients; c && c->next; c = c->next);
728 for(; c && !isvisible(c); c = c->prev);
737 getclient(Window w) {
740 for(c = clients; c && c->win != w; c = c->next);
745 getcolor(const char *colstr) {
746 Colormap cmap = DefaultColormap(dpy, screen);
749 if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
750 eprint("error, cannot allocate color '%s'\n", colstr);
758 unsigned char *p = NULL;
759 unsigned long n, extra;
762 status = XGetWindowProperty(dpy, w, wmatom[WMState], 0L, 2L, False, wmatom[WMState],
763 &real, &format, &n, &extra, (unsigned char **)&p);
764 if(status != Success)
773 gettextprop(Window w, Atom atom, char *text, unsigned int size) {
778 if(!text || size == 0)
781 XGetTextProperty(dpy, w, &name, atom);
784 if(name.encoding == XA_STRING)
785 strncpy(text, (char *)name.value, size - 1);
787 if(XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success
790 strncpy(text, *list, size - 1);
791 XFreeStringList(list);
794 text[size - 1] = '\0';
800 grabbuttons(Client *c, Bool focused) {
801 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
804 XGrabButton(dpy, Button1, MODKEY, c->win, False, BUTTONMASK,
805 GrabModeAsync, GrabModeSync, None, None);
806 XGrabButton(dpy, Button1, MODKEY | LockMask, c->win, False, BUTTONMASK,
807 GrabModeAsync, GrabModeSync, None, None);
808 XGrabButton(dpy, Button1, MODKEY | numlockmask, c->win, False, BUTTONMASK,
809 GrabModeAsync, GrabModeSync, None, None);
810 XGrabButton(dpy, Button1, MODKEY | numlockmask | LockMask, c->win, False, BUTTONMASK,
811 GrabModeAsync, GrabModeSync, None, None);
813 XGrabButton(dpy, Button2, MODKEY, c->win, False, BUTTONMASK,
814 GrabModeAsync, GrabModeSync, None, None);
815 XGrabButton(dpy, Button2, MODKEY | LockMask, c->win, False, BUTTONMASK,
816 GrabModeAsync, GrabModeSync, None, None);
817 XGrabButton(dpy, Button2, MODKEY | numlockmask, c->win, False, BUTTONMASK,
818 GrabModeAsync, GrabModeSync, None, None);
819 XGrabButton(dpy, Button2, MODKEY | numlockmask | LockMask, c->win, False, BUTTONMASK,
820 GrabModeAsync, GrabModeSync, None, None);
822 XGrabButton(dpy, Button3, MODKEY, c->win, False, BUTTONMASK,
823 GrabModeAsync, GrabModeSync, None, None);
824 XGrabButton(dpy, Button3, MODKEY | LockMask, c->win, False, BUTTONMASK,
825 GrabModeAsync, GrabModeSync, None, None);
826 XGrabButton(dpy, Button3, MODKEY | numlockmask, c->win, False, BUTTONMASK,
827 GrabModeAsync, GrabModeSync, None, None);
828 XGrabButton(dpy, Button3, MODKEY | numlockmask | LockMask, c->win, False, BUTTONMASK,
829 GrabModeAsync, GrabModeSync, None, None);
832 XGrabButton(dpy, AnyButton, AnyModifier, c->win, False, BUTTONMASK,
833 GrabModeAsync, GrabModeSync, None, None);
837 idxoftag(const char *tag) {
840 for(i = 0; i < ntags; i++)
847 initfont(const char *fontstr) {
848 char *def, **missing;
853 XFreeFontSet(dpy, dc.font.set);
854 dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
857 fprintf(stderr, "dwm: missing fontset: %s\n", missing[n]);
858 XFreeStringList(missing);
861 XFontSetExtents *font_extents;
862 XFontStruct **xfonts;
864 dc.font.ascent = dc.font.descent = 0;
865 font_extents = XExtentsOfFontSet(dc.font.set);
866 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
867 for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
868 if(dc.font.ascent < (*xfonts)->ascent)
869 dc.font.ascent = (*xfonts)->ascent;
870 if(dc.font.descent < (*xfonts)->descent)
871 dc.font.descent = (*xfonts)->descent;
877 XFreeFont(dpy, dc.font.xfont);
878 dc.font.xfont = NULL;
879 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr))
880 || !(dc.font.xfont = XLoadQueryFont(dpy, "fixed")))
881 eprint("error, cannot load font: '%s'\n", fontstr);
882 dc.font.ascent = dc.font.xfont->ascent;
883 dc.font.descent = dc.font.xfont->descent;
885 dc.font.height = dc.font.ascent + dc.font.descent;
889 isarrange(void (*func)())
891 return func == layouts[ltidx].arrange;
895 isoccupied(unsigned int t) {
898 for(c = clients; c; c = c->next)
905 isprotodel(Client *c) {
910 if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
911 for(i = 0; !ret && i < n; i++)
912 if(protocols[i] == wmatom[WMDelete])
920 isvisible(Client *c) {
923 for(i = 0; i < ntags; i++)
924 if(c->tags[i] && seltags[i])
930 keypress(XEvent *e) {
932 unsigned int len = sizeof keys / sizeof keys[0];
938 if(!e) { /* grabkeys */
939 XUngrabKey(dpy, AnyKey, AnyModifier, root);
940 for(i = 0; i < len; i++) {
941 code = XKeysymToKeycode(dpy, keys[i].keysym);
942 XGrabKey(dpy, code, keys[i].mod, root, True,
943 GrabModeAsync, GrabModeAsync);
944 XGrabKey(dpy, code, keys[i].mod | LockMask, root, True,
945 GrabModeAsync, GrabModeAsync);
946 XGrabKey(dpy, code, keys[i].mod | numlockmask, root, True,
947 GrabModeAsync, GrabModeAsync);
948 XGrabKey(dpy, code, keys[i].mod | numlockmask | LockMask, root, True,
949 GrabModeAsync, GrabModeAsync);
954 keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
955 for(i = 0; i < len; i++)
956 if(keysym == keys[i].keysym
957 && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state))
960 keys[i].func(keys[i].arg);
965 killclient(const char *arg) {
970 if(isprotodel(sel)) {
971 ev.type = ClientMessage;
972 ev.xclient.window = sel->win;
973 ev.xclient.message_type = wmatom[WMProtocols];
974 ev.xclient.format = 32;
975 ev.xclient.data.l[0] = wmatom[WMDelete];
976 ev.xclient.data.l[1] = CurrentTime;
977 XSendEvent(dpy, sel->win, False, NoEventMask, &ev);
980 XKillClient(dpy, sel->win);
984 leavenotify(XEvent *e) {
985 XCrossingEvent *ev = &e->xcrossing;
987 if((ev->window == root) && !ev->same_screen) {
994 manage(Window w, XWindowAttributes *wa) {
996 Client *c, *t = NULL;
1001 c = emallocz(sizeof(Client));
1002 c->tags = emallocz(ntags * sizeof(Bool));
1008 c->oldborder = wa->border_width;
1009 if(c->w == sw && c->h == sh) {
1012 c->border = wa->border_width;
1015 if(c->x + c->w + 2 * c->border > wax + waw)
1016 c->x = wax + waw - c->w - 2 * c->border;
1017 if(c->y + c->h + 2 * c->border > way + wah)
1018 c->y = way + wah - c->h - 2 * c->border;
1023 c->border = BORDERPX;
1025 wc.border_width = c->border;
1026 XConfigureWindow(dpy, w, CWBorderWidth, &wc);
1027 XSetWindowBorder(dpy, w, dc.norm[ColBorder]);
1028 configure(c); /* propagates border_width, if size doesn't change */
1030 XSelectInput(dpy, w,
1031 StructureNotifyMask | PropertyChangeMask | EnterWindowMask);
1032 grabbuttons(c, False);
1034 if((rettrans = XGetTransientForHint(dpy, w, &trans) == Success))
1035 for(t = clients; t && t->win != trans; t = t->next);
1037 for(i = 0; i < ntags; i++)
1038 c->tags[i] = t->tags[i];
1041 c->isfloating = (rettrans == Success) || c->isfixed;
1044 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h); /* some windows require this */
1046 XMapWindow(dpy, c->win);
1047 setclientstate(c, NormalState);
1052 mappingnotify(XEvent *e) {
1053 XMappingEvent *ev = &e->xmapping;
1055 XRefreshKeyboardMapping(ev);
1056 if(ev->request == MappingKeyboard)
1061 maprequest(XEvent *e) {
1062 static XWindowAttributes wa;
1063 XMapRequestEvent *ev = &e->xmaprequest;
1065 if(!XGetWindowAttributes(dpy, ev->window, &wa))
1067 if(wa.override_redirect)
1069 if(!getclient(ev->window))
1070 manage(ev->window, &wa);
1074 movemouse(Client *c) {
1075 int x1, y1, ocx, ocy, di, nx, ny;
1082 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1083 None, cursor[CurMove], CurrentTime) != GrabSuccess)
1086 XQueryPointer(dpy, root, &dummy, &dummy, &x1, &y1, &di, &di, &dui);
1088 XMaskEvent(dpy, MOUSEMASK | ExposureMask | SubstructureRedirectMask, &ev);
1091 XUngrabPointer(dpy, CurrentTime);
1093 case ConfigureRequest:
1096 handler[ev.type](&ev);
1100 nx = ocx + (ev.xmotion.x - x1);
1101 ny = ocy + (ev.xmotion.y - y1);
1102 if(abs(wax + nx) < SNAP)
1104 else if(abs((wax + waw) - (nx + c->w + 2 * c->border)) < SNAP)
1105 nx = wax + waw - c->w - 2 * c->border;
1106 if(abs(way - ny) < SNAP)
1108 else if(abs((way + wah) - (ny + c->h + 2 * c->border)) < SNAP)
1109 ny = way + wah - c->h - 2 * c->border;
1110 resize(c, nx, ny, c->w, c->h, False);
1117 nexttiled(Client *c) {
1118 for(; c && (c->isfloating || !isvisible(c)); c = c->next);
1123 propertynotify(XEvent *e) {
1126 XPropertyEvent *ev = &e->xproperty;
1128 if(ev->state == PropertyDelete)
1129 return; /* ignore */
1130 if((c = getclient(ev->window))) {
1133 case XA_WM_TRANSIENT_FOR:
1134 XGetTransientForHint(dpy, c->win, &trans);
1135 if(!c->isfloating && (c->isfloating = (getclient(trans) != NULL)))
1138 case XA_WM_NORMAL_HINTS:
1142 if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
1151 quit(const char *arg) {
1152 readin = running = False;
1156 resize(Client *c, int x, int y, int w, int h, Bool sizehints) {
1157 double dx, dy, max, min, ratio;
1161 if(c->minay > 0 && c->maxay > 0 && (h - c->baseh) > 0 && (w - c->basew) > 0) {
1162 dx = (double)(w - c->basew);
1163 dy = (double)(h - c->baseh);
1164 min = (double)(c->minax) / (double)(c->minay);
1165 max = (double)(c->maxax) / (double)(c->maxay);
1167 if(max > 0 && min > 0 && ratio > 0) {
1169 dy = (dx * min + dy) / (min * min + 1);
1171 w = (int)dx + c->basew;
1172 h = (int)dy + c->baseh;
1174 else if(ratio > max) {
1175 dy = (dx * min + dy) / (max * max + 1);
1177 w = (int)dx + c->basew;
1178 h = (int)dy + c->baseh;
1182 if(c->minw && w < c->minw)
1184 if(c->minh && h < c->minh)
1186 if(c->maxw && w > c->maxw)
1188 if(c->maxh && h > c->maxh)
1191 w -= (w - c->basew) % c->incw;
1193 h -= (h - c->baseh) % c->inch;
1195 if(w <= 0 || h <= 0)
1197 /* offscreen appearance fixes */
1199 x = sw - w - 2 * c->border;
1201 y = sh - h - 2 * c->border;
1202 if(x + w + 2 * c->border < sx)
1204 if(y + h + 2 * c->border < sy)
1206 if(c->x != x || c->y != y || c->w != w || c->h != h) {
1209 c->w = wc.width = w;
1210 c->h = wc.height = h;
1211 wc.border_width = c->border;
1212 XConfigureWindow(dpy, c->win, CWX | CWY | CWWidth | CWHeight | CWBorderWidth, &wc);
1219 resizemouse(Client *c) {
1226 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1227 None, cursor[CurResize], CurrentTime) != GrabSuccess)
1230 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->border - 1, c->h + c->border - 1);
1232 XMaskEvent(dpy, MOUSEMASK | ExposureMask | SubstructureRedirectMask , &ev);
1235 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0,
1236 c->w + c->border - 1, c->h + c->border - 1);
1237 XUngrabPointer(dpy, CurrentTime);
1238 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1240 case ConfigureRequest:
1243 handler[ev.type](&ev);
1247 if((nw = ev.xmotion.x - ocx - 2 * c->border + 1) <= 0)
1249 if((nh = ev.xmotion.y - ocy - 2 * c->border + 1) <= 0)
1251 resize(c, c->x, c->y, nw, nh, True);
1266 if(sel->isfloating || isarrange(floating))
1267 XRaiseWindow(dpy, sel->win);
1268 if(!isarrange(floating)) {
1269 wc.stack_mode = Below;
1270 wc.sibling = barwin;
1271 if(!sel->isfloating) {
1272 XConfigureWindow(dpy, sel->win, CWSibling | CWStackMode, &wc);
1273 wc.sibling = sel->win;
1275 for(c = nexttiled(clients); c; c = nexttiled(c->next)) {
1278 XConfigureWindow(dpy, c->win, CWSibling | CWStackMode, &wc);
1279 wc.sibling = c->win;
1283 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1293 /* main event loop, also reads status text from stdin */
1295 xfd = ConnectionNumber(dpy);
1300 FD_SET(STDIN_FILENO, &rd);
1302 if(select(xfd + 1, &rd, NULL, NULL, NULL) == -1) {
1305 eprint("select failed\n");
1307 if(FD_ISSET(STDIN_FILENO, &rd)) {
1308 switch(r = read(STDIN_FILENO, stext, sizeof stext - 1)) {
1310 strncpy(stext, strerror(errno), sizeof stext - 1);
1311 stext[sizeof stext - 1] = '\0';
1315 strncpy(stext, "EOF", 4);
1319 for(stext[r] = '\0', p = stext + strlen(stext) - 1; p >= stext && *p == '\n'; *p-- = '\0');
1320 for(; p >= stext && *p != '\n'; --p);
1322 strncpy(stext, p + 1, sizeof stext);
1326 while(XPending(dpy)) {
1327 XNextEvent(dpy, &ev);
1328 if(handler[ev.type])
1329 (handler[ev.type])(&ev); /* call handler */
1336 unsigned int i, num;
1337 Window *wins, d1, d2;
1338 XWindowAttributes wa;
1341 if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1342 for(i = 0; i < num; i++) {
1343 if(!XGetWindowAttributes(dpy, wins[i], &wa)
1344 || wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1346 if(wa.map_state == IsViewable || getstate(wins[i]) == IconicState)
1347 manage(wins[i], &wa);
1349 for(i = 0; i < num; i++) { /* now the transients */
1350 if(!XGetWindowAttributes(dpy, wins[i], &wa))
1352 if(XGetTransientForHint(dpy, wins[i], &d1)
1353 && (wa.map_state == IsViewable || getstate(wins[i]) == IconicState))
1354 manage(wins[i], &wa);
1362 setclientstate(Client *c, long state) {
1363 long data[] = {state, None};
1365 XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1366 PropModeReplace, (unsigned char *)data, 2);
1370 setlayout(const char *arg) {
1374 if(++ltidx == nlayouts)
1378 for(i = 0; i < nlayouts; i++)
1379 if(!strcmp(arg, layouts[i].symbol))
1392 setmwfact(const char *arg) {
1395 if(!isarrange(tile))
1397 /* arg handling, manipulate mwfact */
1400 else if(1 == sscanf(arg, "%lf", &delta)) {
1401 if(arg[0] != '+' && arg[0] != '-')
1407 else if(mwfact > 0.9)
1415 unsigned int i, j, mask;
1417 XModifierKeymap *modmap;
1418 XSetWindowAttributes wa;
1421 wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1422 wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1423 wmatom[WMName] = XInternAtom(dpy, "WM_NAME", False);
1424 wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1425 netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1426 netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1427 XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1428 PropModeReplace, (unsigned char *) netatom, NetLast);
1431 cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1432 cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1433 cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1437 sw = DisplayWidth(dpy, screen);
1438 sh = DisplayHeight(dpy, screen);
1440 /* init modifier map */
1441 modmap = XGetModifierMapping(dpy);
1442 for(i = 0; i < 8; i++)
1443 for(j = 0; j < modmap->max_keypermod; j++) {
1444 if(modmap->modifiermap[i * modmap->max_keypermod + j]
1445 == XKeysymToKeycode(dpy, XK_Num_Lock))
1446 numlockmask = (1 << i);
1448 XFreeModifiermap(modmap);
1450 /* select for events */
1451 wa.event_mask = SubstructureRedirectMask | SubstructureNotifyMask
1452 | EnterWindowMask | LeaveWindowMask | StructureNotifyMask;
1453 wa.cursor = cursor[CurNormal];
1454 XChangeWindowAttributes(dpy, root, CWEventMask | CWCursor, &wa);
1455 XSelectInput(dpy, root, wa.event_mask);
1462 for(ntags = 0; tags[ntags]; ntags++);
1463 seltags = emallocz(sizeof(Bool) * ntags);
1466 /* init appearance */
1467 dc.norm[ColBorder] = getcolor(NORMBORDERCOLOR);
1468 dc.norm[ColBG] = getcolor(NORMBGCOLOR);
1469 dc.norm[ColFG] = getcolor(NORMFGCOLOR);
1470 dc.sel[ColBorder] = getcolor(SELBORDERCOLOR);
1471 dc.sel[ColBG] = getcolor(SELBGCOLOR);
1472 dc.sel[ColFG] = getcolor(SELFGCOLOR);
1474 dc.h = bh = dc.font.height + 2;
1478 nlayouts = sizeof layouts / sizeof layouts[0];
1479 for(blw = i = 0; i < nlayouts; i++) {
1480 j = textw(layouts[i].symbol);
1487 wa.override_redirect = 1;
1488 wa.background_pixmap = ParentRelative;
1489 wa.event_mask = ButtonPressMask | ExposureMask;
1490 barwin = XCreateWindow(dpy, root, sx, sy, sw, bh, 0,
1491 DefaultDepth(dpy, screen), CopyFromParent, DefaultVisual(dpy, screen),
1492 CWOverrideRedirect | CWBackPixmap | CWEventMask, &wa);
1493 XDefineCursor(dpy, barwin, cursor[CurNormal]);
1495 XMapRaised(dpy, barwin);
1496 strcpy(stext, "dwm-"VERSION);
1497 dc.drawable = XCreatePixmap(dpy, root, sw, bh, DefaultDepth(dpy, screen));
1498 dc.gc = XCreateGC(dpy, root, 0, 0);
1499 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
1501 XSetFont(dpy, dc.gc, dc.font.xfont->fid);
1503 /* multihead support */
1504 selscreen = XQueryPointer(dpy, root, &w, &w, &i, &i, &i, &i, &mask);
1508 spawn(const char *arg) {
1509 static char *shell = NULL;
1511 if(!shell && !(shell = getenv("SHELL")))
1515 /* The double-fork construct avoids zombie processes and keeps the code
1516 * clean from stupid signal handlers. */
1520 close(ConnectionNumber(dpy));
1522 execl(shell, shell, "-c", arg, (char *)NULL);
1523 fprintf(stderr, "dwm: execl '%s -c %s'", shell, arg);
1532 tag(const char *arg) {
1537 for(i = 0; i < ntags; i++)
1538 sel->tags[i] = arg == NULL;
1540 if(i >= 0 && i < ntags)
1541 sel->tags[i] = True;
1546 textnw(const char *text, unsigned int len) {
1550 XmbTextExtents(dc.font.set, text, len, NULL, &r);
1553 return XTextWidth(dc.font.xfont, text, len);
1557 textw(const char *text) {
1558 return textnw(text, strlen(text)) + dc.font.height;
1563 unsigned int i, n, nx, ny, nw, nh, mw, th;
1566 for(n = 0, c = nexttiled(clients); c; c = nexttiled(c->next))
1570 mw = (n == 1) ? waw : mwfact * waw;
1571 th = (n > 1) ? wah / (n - 1) : 0;
1572 if(n > 1 && th < bh)
1577 for(i = 0, c = nexttiled(clients); c; c = nexttiled(c->next), i++) {
1579 if(i == 0) { /* master */
1580 nw = mw - 2 * c->border;
1581 nh = wah - 2 * c->border;
1583 else { /* tile window */
1588 nw = waw - mw - 2 * c->border;
1589 if(i + 1 == n) /* remainder */
1590 nh = (way + wah) - ny - 2 * c->border;
1592 nh = th - 2 * c->border;
1594 resize(c, nx, ny, nw, nh, RESIZEHINTS);
1595 if(n > 1 && th != wah)
1596 ny += nh + 2 * c->border;
1601 togglebar(const char *arg) {
1603 bpos = (BARPOS == BarOff) ? BarTop : BARPOS;
1611 togglefloating(const char *arg) {
1614 sel->isfloating = !sel->isfloating;
1616 resize(sel, sel->x, sel->y, sel->w, sel->h, True);
1621 togglemax(const char *arg) {
1624 if(!sel || (!isarrange(floating) && !sel->isfloating) || sel->isfixed)
1626 if((sel->ismax = !sel->ismax)) {
1631 resize(sel, wax, way, waw - 2 * sel->border, wah - 2 * sel->border, True);
1634 resize(sel, sel->rx, sel->ry, sel->rw, sel->rh, True);
1636 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1640 toggletag(const char *arg) {
1646 sel->tags[i] = !sel->tags[i];
1647 for(j = 0; j < ntags && !sel->tags[j]; j++);
1649 sel->tags[i] = True;
1654 toggleview(const char *arg) {
1658 seltags[i] = !seltags[i];
1659 for(j = 0; j < ntags && !seltags[j]; j++);
1661 seltags[i] = True; /* cannot toggle last view */
1669 XMoveWindow(dpy, c->win, c->x, c->y);
1670 c->isbanned = False;
1674 unmanage(Client *c) {
1677 wc.border_width = c->oldborder;
1678 /* The server grab construct avoids race conditions. */
1680 XSetErrorHandler(xerrordummy);
1681 XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
1686 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1687 setclientstate(c, WithdrawnState);
1691 XSetErrorHandler(xerror);
1697 unmapnotify(XEvent *e) {
1699 XUnmapEvent *ev = &e->xunmap;
1701 if((c = getclient(ev->window)))
1706 updatebarpos(void) {
1717 XMoveWindow(dpy, barwin, sx, sy);
1721 XMoveWindow(dpy, barwin, sx, sy + wah);
1724 XMoveWindow(dpy, barwin, sx, sy - bh);
1728 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1732 updatesizehints(Client *c) {
1736 if(!XGetWMNormalHints(dpy, c->win, &size, &msize) || !size.flags)
1738 c->flags = size.flags;
1739 if(c->flags & PBaseSize) {
1740 c->basew = size.base_width;
1741 c->baseh = size.base_height;
1743 else if(c->flags & PMinSize) {
1744 c->basew = size.min_width;
1745 c->baseh = size.min_height;
1748 c->basew = c->baseh = 0;
1749 if(c->flags & PResizeInc) {
1750 c->incw = size.width_inc;
1751 c->inch = size.height_inc;
1754 c->incw = c->inch = 0;
1755 if(c->flags & PMaxSize) {
1756 c->maxw = size.max_width;
1757 c->maxh = size.max_height;
1760 c->maxw = c->maxh = 0;
1761 if(c->flags & PMinSize) {
1762 c->minw = size.min_width;
1763 c->minh = size.min_height;
1765 else if(c->flags & PBaseSize) {
1766 c->minw = size.base_width;
1767 c->minh = size.base_height;
1770 c->minw = c->minh = 0;
1771 if(c->flags & PAspect) {
1772 c->minax = size.min_aspect.x;
1773 c->maxax = size.max_aspect.x;
1774 c->minay = size.min_aspect.y;
1775 c->maxay = size.max_aspect.y;
1778 c->minax = c->maxax = c->minay = c->maxay = 0;
1779 c->isfixed = (c->maxw && c->minw && c->maxh && c->minh
1780 && c->maxw == c->minw && c->maxh == c->minh);
1784 updatetitle(Client *c) {
1785 if(!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
1786 gettextprop(c->win, wmatom[WMName], c->name, sizeof c->name);
1789 /* There's no way to check accesses to destroyed windows, thus those cases are
1790 * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
1791 * default error handler, which may call exit. */
1793 xerror(Display *dpy, XErrorEvent *ee) {
1794 if(ee->error_code == BadWindow
1795 || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1796 || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1797 || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1798 || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1799 || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1800 || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1801 || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1803 fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1804 ee->request_code, ee->error_code);
1805 return xerrorxlib(dpy, ee); /* may call exit */
1809 xerrordummy(Display *dsply, XErrorEvent *ee) {
1813 /* Startup Error handler to check if another window manager
1814 * is already running. */
1816 xerrorstart(Display *dsply, XErrorEvent *ee) {
1822 view(const char *arg) {
1825 for(i = 0; i < ntags; i++)
1826 seltags[i] = arg == NULL;
1828 if(i >= 0 && i < ntags)
1834 zoom(const char *arg) {
1837 if(!sel || !isarrange(tile) || sel->isfloating)
1839 if((c = sel) == nexttiled(clients))
1840 if(!(c = nexttiled(c->next)))
1849 main(int argc, char *argv[]) {
1850 if(argc == 2 && !strcmp("-v", argv[1]))
1851 eprint("dwm-"VERSION", © 2006-2007 A. R. Garbe, S. van Dijk, J. Salmi, P. Hruby, S. Nagy\n");
1853 eprint("usage: dwm [-v]\n");
1855 setlocale(LC_CTYPE, "");
1856 if(!(dpy = XOpenDisplay(0)))
1857 eprint("dwm: cannot open display\n");
1858 screen = DefaultScreen(dpy);
1859 root = RootWindow(dpy, screen);