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);
116 static void eprint(const char *errstr, ...);
117 static void *emallocz(unsigned int size);
118 static void spawn(const char *arg);
119 static void drawsquare(Bool filled, Bool empty, unsigned long col[ColLast]);
120 static unsigned long initcolor(const char *colstr);
121 static void initfont(const char *fontstr);
122 static Bool isoccupied(unsigned int t);
123 static unsigned int textnw(const char *text, unsigned int len);
124 static void drawtext(const char *text, unsigned long col[ColLast]);
125 static void drawbar(void);
126 static void initstyle(void);
127 static void initbar(void);
128 static unsigned int textw(const char *text);
129 static void togglebar(const char *arg);
130 static void updatebarpos(void);
131 static void attachstack(Client *c);
132 static void detachstack(Client *c);
133 static void grabbuttons(Client *c, Bool focused);
134 static Bool isprotodel(Client *c);
135 static void setclientstate(Client *c, long state);
136 static int xerrordummy(Display *dsply, XErrorEvent *ee);
137 static void ban(Client *c);
138 static void configure(Client *c);
139 static void killclient(const char *arg);
140 static void manage(Window w, XWindowAttributes *wa);
141 static void resize(Client *c, int x, int y, int w, int h, Bool sizehints);
142 static void unban(Client *c);
143 static void unmanage(Client *c);
144 static void updatesizehints(Client *c);
145 static void updatetitle(Client *c);
146 static Client *getclient(Window w);
147 static void movemouse(Client *c);
148 static void resizemouse(Client *c);
149 static void buttonpress(XEvent *e);
150 static void configurerequest(XEvent *e);
151 static void configurenotify(XEvent *e);
152 static void destroynotify(XEvent *e);
153 static void enternotify(XEvent *e);
154 static void expose(XEvent *e);
155 static void keypress(XEvent *e);
156 static void leavenotify(XEvent *e);
157 static void mappingnotify(XEvent *e);
158 static void maprequest(XEvent *e);
159 static void propertynotify(XEvent *e);
160 static void unmapnotify(XEvent *e);
161 static unsigned int idxoftag(const char *tag);
162 static void floating(void); /* default floating layout */
163 static void applyrules(Client *c);
164 static void compileregs(void);
165 static void focusnext(const char *arg);
166 static void focusprev(const char *arg);
167 static void initlayouts(void);
168 static Bool isfloating(void);
169 static Bool isvisible(Client *c);
170 static void restack(void);
171 static void setlayout(const char *arg);
172 static void tag(const char *arg);
173 static void togglefloating(const char *arg);
174 static void togglemax(const char *arg);
175 static void toggletag(const char *arg);
176 static void toggleview(const char *arg);
177 static void view(const char *arg);
178 static void cleanup(void);
179 static long getstate(Window w);
180 static void scan(void);
181 static void setup(void);
182 static int xerrorstart(Display *dsply, XErrorEvent *ee);
183 static Bool gettextprop(Window w, Atom atom, char *text, unsigned int size);
184 static void quit(const char *arg);
185 static int xerror(Display *dpy, XErrorEvent *ee);
186 static void arrange(void);
187 static void attach(Client *c);
188 static void detach(Client *c);
189 static void focus(Client *c);
190 static Bool isarrange(void (*func)());
191 static Client *nexttiled(Client *c);
192 static void setmwfact(const char *arg);
193 static void tile(void);
194 static void zoom(const char *arg);
199 static char stext[256];
200 static double mwfact = MWFACT;
201 static int screen, sx, sy, sw, sh, wax, way, waw, wah;
202 static int (*xerrorxlib)(Display *, XErrorEvent *);
203 static unsigned int bh;
204 static unsigned int blw = 0;
205 static unsigned int bpos = BARPOS;
206 static unsigned int ltidx = 0; /* default */
207 static unsigned int nlayouts = 0;
208 static unsigned int nrules = 0;
209 static unsigned int ntags;
210 static unsigned int numlockmask = 0;
211 static void (*handler[LASTEvent]) (XEvent *) = {
212 [ButtonPress] = buttonpress,
213 [ConfigureRequest] = configurerequest,
214 [ConfigureNotify] = configurenotify,
215 [DestroyNotify] = destroynotify,
216 [EnterNotify] = enternotify,
217 [LeaveNotify] = leavenotify,
219 [KeyPress] = keypress,
220 [MappingNotify] = mappingnotify,
221 [MapRequest] = maprequest,
222 [PropertyNotify] = propertynotify,
223 [UnmapNotify] = unmapnotify
225 static Atom wmatom[WMLast], netatom[NetLast];
226 static Bool otherwm, readin;
227 static Bool running = True;
228 static Bool *seltags;
229 static Bool selscreen = True;
230 static Client *clients = NULL;
231 static Client *sel = NULL;
232 static Client *stack = NULL;
233 static Cursor cursor[CurLast];
236 static Window barwin, root;
237 static Regs *regs = NULL;
240 eprint(const char *errstr, ...) {
243 va_start(ap, errstr);
244 vfprintf(stderr, errstr, ap);
250 emallocz(unsigned int size) {
251 void *res = calloc(1, size);
254 eprint("fatal: could not malloc() %u bytes\n", size);
259 spawn(const char *arg) {
260 static char *shell = NULL;
262 if(!shell && !(shell = getenv("SHELL")))
266 /* The double-fork construct avoids zombie processes and keeps the code
267 * clean from stupid signal handlers. */
271 close(ConnectionNumber(dpy));
273 execl(shell, shell, "-c", arg, (char *)NULL);
274 fprintf(stderr, "dwm: execl '%s -c %s'", shell, arg);
283 drawsquare(Bool filled, Bool empty, unsigned long col[ColLast]) {
286 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
288 gcv.foreground = col[ColFG];
289 XChangeGC(dpy, dc.gc, GCForeground, &gcv);
290 x = (dc.font.ascent + dc.font.descent + 2) / 4;
294 r.width = r.height = x + 1;
295 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
298 r.width = r.height = x;
299 XDrawRectangles(dpy, dc.drawable, dc.gc, &r, 1);
304 initcolor(const char *colstr) {
305 Colormap cmap = DefaultColormap(dpy, screen);
308 if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
309 eprint("error, cannot allocate color '%s'\n", colstr);
314 initfont(const char *fontstr) {
315 char *def, **missing;
320 XFreeFontSet(dpy, dc.font.set);
321 dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
324 fprintf(stderr, "dwm: missing fontset: %s\n", missing[n]);
325 XFreeStringList(missing);
328 XFontSetExtents *font_extents;
329 XFontStruct **xfonts;
331 dc.font.ascent = dc.font.descent = 0;
332 font_extents = XExtentsOfFontSet(dc.font.set);
333 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
334 for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
335 if(dc.font.ascent < (*xfonts)->ascent)
336 dc.font.ascent = (*xfonts)->ascent;
337 if(dc.font.descent < (*xfonts)->descent)
338 dc.font.descent = (*xfonts)->descent;
344 XFreeFont(dpy, dc.font.xfont);
345 dc.font.xfont = NULL;
346 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr))
347 || !(dc.font.xfont = XLoadQueryFont(dpy, "fixed")))
348 eprint("error, cannot load font: '%s'\n", fontstr);
349 dc.font.ascent = dc.font.xfont->ascent;
350 dc.font.descent = dc.font.xfont->descent;
352 dc.font.height = dc.font.ascent + dc.font.descent;
356 isoccupied(unsigned int t) {
359 for(c = clients; c; c = c->next)
366 textnw(const char *text, unsigned int len) {
370 XmbTextExtents(dc.font.set, text, len, NULL, &r);
373 return XTextWidth(dc.font.xfont, text, len);
377 drawtext(const char *text, unsigned long col[ColLast]) {
379 static char buf[256];
380 unsigned int len, olen;
381 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
383 XSetForeground(dpy, dc.gc, col[ColBG]);
384 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
388 olen = len = strlen(text);
389 if(len >= sizeof buf)
390 len = sizeof buf - 1;
391 memcpy(buf, text, len);
393 h = dc.font.ascent + dc.font.descent;
394 y = dc.y + (dc.h / 2) - (h / 2) + dc.font.ascent;
396 /* shorten text if necessary */
397 while(len && (w = textnw(buf, len)) > dc.w - h)
408 return; /* too long */
409 XSetForeground(dpy, dc.gc, col[ColFG]);
411 XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
413 XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
421 for(i = 0; i < ntags; i++) {
422 dc.w = textw(tags[i]);
424 drawtext(tags[i], dc.sel);
425 drawsquare(sel && sel->tags[i], isoccupied(i), dc.sel);
428 drawtext(tags[i], dc.norm);
429 drawsquare(sel && sel->tags[i], isoccupied(i), dc.norm);
434 drawtext(layouts[ltidx].symbol, dc.norm);
442 drawtext(stext, dc.norm);
443 if((dc.w = dc.x - x) > bh) {
446 drawtext(sel->name, dc.sel);
447 drawsquare(sel->ismax, sel->isfloating, dc.sel);
450 drawtext(NULL, dc.norm);
452 XCopyArea(dpy, dc.drawable, barwin, dc.gc, 0, 0, sw, bh, 0, 0);
458 dc.norm[ColBorder] = initcolor(NORMBORDERCOLOR);
459 dc.norm[ColBG] = initcolor(NORMBGCOLOR);
460 dc.norm[ColFG] = initcolor(NORMFGCOLOR);
461 dc.sel[ColBorder] = initcolor(SELBORDERCOLOR);
462 dc.sel[ColBG] = initcolor(SELBGCOLOR);
463 dc.sel[ColFG] = initcolor(SELFGCOLOR);
465 dc.h = bh = dc.font.height + 2;
470 XSetWindowAttributes wa;
472 wa.override_redirect = 1;
473 wa.background_pixmap = ParentRelative;
474 wa.event_mask = ButtonPressMask | ExposureMask;
475 barwin = XCreateWindow(dpy, root, sx, sy, sw, bh, 0,
476 DefaultDepth(dpy, screen), CopyFromParent, DefaultVisual(dpy, screen),
477 CWOverrideRedirect | CWBackPixmap | CWEventMask, &wa);
478 XDefineCursor(dpy, barwin, cursor[CurNormal]);
480 XMapRaised(dpy, barwin);
481 strcpy(stext, "dwm-"VERSION);
482 dc.drawable = XCreatePixmap(dpy, root, sw, bh, DefaultDepth(dpy, screen));
483 dc.gc = XCreateGC(dpy, root, 0, 0);
484 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
486 XSetFont(dpy, dc.gc, dc.font.xfont->fid);
490 textw(const char *text) {
491 return textnw(text, strlen(text)) + dc.font.height;
495 togglebar(const char *arg) {
497 bpos = (BARPOS == BarOff) ? BarTop : BARPOS;
516 XMoveWindow(dpy, barwin, sx, sy);
520 XMoveWindow(dpy, barwin, sx, sy + wah);
523 XMoveWindow(dpy, barwin, sx, sy - bh);
527 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
531 attachstack(Client *c) {
537 detachstack(Client *c) {
540 for(tc=&stack; *tc && *tc != c; tc=&(*tc)->snext);
545 grabbuttons(Client *c, Bool focused) {
546 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
549 XGrabButton(dpy, Button1, MODKEY, c->win, False, BUTTONMASK,
550 GrabModeAsync, GrabModeSync, None, None);
551 XGrabButton(dpy, Button1, MODKEY | LockMask, c->win, False, BUTTONMASK,
552 GrabModeAsync, GrabModeSync, None, None);
553 XGrabButton(dpy, Button1, MODKEY | numlockmask, c->win, False, BUTTONMASK,
554 GrabModeAsync, GrabModeSync, None, None);
555 XGrabButton(dpy, Button1, MODKEY | numlockmask | LockMask, c->win, False, BUTTONMASK,
556 GrabModeAsync, GrabModeSync, None, None);
558 XGrabButton(dpy, Button2, MODKEY, c->win, False, BUTTONMASK,
559 GrabModeAsync, GrabModeSync, None, None);
560 XGrabButton(dpy, Button2, MODKEY | LockMask, c->win, False, BUTTONMASK,
561 GrabModeAsync, GrabModeSync, None, None);
562 XGrabButton(dpy, Button2, MODKEY | numlockmask, c->win, False, BUTTONMASK,
563 GrabModeAsync, GrabModeSync, None, None);
564 XGrabButton(dpy, Button2, MODKEY | numlockmask | LockMask, c->win, False, BUTTONMASK,
565 GrabModeAsync, GrabModeSync, None, None);
567 XGrabButton(dpy, Button3, MODKEY, c->win, False, BUTTONMASK,
568 GrabModeAsync, GrabModeSync, None, None);
569 XGrabButton(dpy, Button3, MODKEY | LockMask, c->win, False, BUTTONMASK,
570 GrabModeAsync, GrabModeSync, None, None);
571 XGrabButton(dpy, Button3, MODKEY | numlockmask, c->win, False, BUTTONMASK,
572 GrabModeAsync, GrabModeSync, None, None);
573 XGrabButton(dpy, Button3, MODKEY | numlockmask | LockMask, c->win, False, BUTTONMASK,
574 GrabModeAsync, GrabModeSync, None, None);
577 XGrabButton(dpy, AnyButton, AnyModifier, c->win, False, BUTTONMASK,
578 GrabModeAsync, GrabModeSync, None, None);
582 isprotodel(Client *c) {
587 if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
588 for(i = 0; !ret && i < n; i++)
589 if(protocols[i] == wmatom[WMDelete])
597 setclientstate(Client *c, long state) {
598 long data[] = {state, None};
600 XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
601 PropModeReplace, (unsigned char *)data, 2);
605 xerrordummy(Display *dsply, XErrorEvent *ee) {
613 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
618 configure(Client *c) {
621 ce.type = ConfigureNotify;
629 ce.border_width = c->border;
631 ce.override_redirect = False;
632 XSendEvent(dpy, c->win, False, StructureNotifyMask, (XEvent *)&ce);
636 killclient(const char *arg) {
641 if(isprotodel(sel)) {
642 ev.type = ClientMessage;
643 ev.xclient.window = sel->win;
644 ev.xclient.message_type = wmatom[WMProtocols];
645 ev.xclient.format = 32;
646 ev.xclient.data.l[0] = wmatom[WMDelete];
647 ev.xclient.data.l[1] = CurrentTime;
648 XSendEvent(dpy, sel->win, False, NoEventMask, &ev);
651 XKillClient(dpy, sel->win);
655 manage(Window w, XWindowAttributes *wa) {
657 Client *c, *t = NULL;
662 c = emallocz(sizeof(Client));
663 c->tags = emallocz(ntags * sizeof(Bool));
669 c->oldborder = wa->border_width;
670 if(c->w == sw && c->h == sh) {
673 c->border = wa->border_width;
676 if(c->x + c->w + 2 * c->border > wax + waw)
677 c->x = wax + waw - c->w - 2 * c->border;
678 if(c->y + c->h + 2 * c->border > way + wah)
679 c->y = way + wah - c->h - 2 * c->border;
684 c->border = BORDERPX;
686 wc.border_width = c->border;
687 XConfigureWindow(dpy, w, CWBorderWidth, &wc);
688 XSetWindowBorder(dpy, w, dc.norm[ColBorder]);
689 configure(c); /* propagates border_width, if size doesn't change */
692 StructureNotifyMask | PropertyChangeMask | EnterWindowMask);
693 grabbuttons(c, False);
695 if((rettrans = XGetTransientForHint(dpy, w, &trans) == Success))
696 for(t = clients; t && t->win != trans; t = t->next);
698 for(i = 0; i < ntags; i++)
699 c->tags[i] = t->tags[i];
702 c->isfloating = (rettrans == Success) || c->isfixed;
705 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h); /* some windows require this */
707 XMapWindow(dpy, c->win);
708 setclientstate(c, NormalState);
713 resize(Client *c, int x, int y, int w, int h, Bool sizehints) {
714 double dx, dy, max, min, ratio;
718 if(c->minay > 0 && c->maxay > 0 && (h - c->baseh) > 0 && (w - c->basew) > 0) {
719 dx = (double)(w - c->basew);
720 dy = (double)(h - c->baseh);
721 min = (double)(c->minax) / (double)(c->minay);
722 max = (double)(c->maxax) / (double)(c->maxay);
724 if(max > 0 && min > 0 && ratio > 0) {
726 dy = (dx * min + dy) / (min * min + 1);
728 w = (int)dx + c->basew;
729 h = (int)dy + c->baseh;
731 else if(ratio > max) {
732 dy = (dx * min + dy) / (max * max + 1);
734 w = (int)dx + c->basew;
735 h = (int)dy + c->baseh;
739 if(c->minw && w < c->minw)
741 if(c->minh && h < c->minh)
743 if(c->maxw && w > c->maxw)
745 if(c->maxh && h > c->maxh)
748 w -= (w - c->basew) % c->incw;
750 h -= (h - c->baseh) % c->inch;
754 /* offscreen appearance fixes */
756 x = sw - w - 2 * c->border;
758 y = sh - h - 2 * c->border;
759 if(x + w + 2 * c->border < sx)
761 if(y + h + 2 * c->border < sy)
763 if(c->x != x || c->y != y || c->w != w || c->h != h) {
767 c->h = wc.height = h;
768 wc.border_width = c->border;
769 XConfigureWindow(dpy, c->win, CWX | CWY | CWWidth | CWHeight | CWBorderWidth, &wc);
779 XMoveWindow(dpy, c->win, c->x, c->y);
784 unmanage(Client *c) {
787 wc.border_width = c->oldborder;
788 /* The server grab construct avoids race conditions. */
790 XSetErrorHandler(xerrordummy);
791 XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
796 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
797 setclientstate(c, WithdrawnState);
801 XSetErrorHandler(xerror);
807 updatesizehints(Client *c) {
811 if(!XGetWMNormalHints(dpy, c->win, &size, &msize) || !size.flags)
813 c->flags = size.flags;
814 if(c->flags & PBaseSize) {
815 c->basew = size.base_width;
816 c->baseh = size.base_height;
818 else if(c->flags & PMinSize) {
819 c->basew = size.min_width;
820 c->baseh = size.min_height;
823 c->basew = c->baseh = 0;
824 if(c->flags & PResizeInc) {
825 c->incw = size.width_inc;
826 c->inch = size.height_inc;
829 c->incw = c->inch = 0;
830 if(c->flags & PMaxSize) {
831 c->maxw = size.max_width;
832 c->maxh = size.max_height;
835 c->maxw = c->maxh = 0;
836 if(c->flags & PMinSize) {
837 c->minw = size.min_width;
838 c->minh = size.min_height;
840 else if(c->flags & PBaseSize) {
841 c->minw = size.base_width;
842 c->minh = size.base_height;
845 c->minw = c->minh = 0;
846 if(c->flags & PAspect) {
847 c->minax = size.min_aspect.x;
848 c->maxax = size.max_aspect.x;
849 c->minay = size.min_aspect.y;
850 c->maxay = size.max_aspect.y;
853 c->minax = c->maxax = c->minay = c->maxay = 0;
854 c->isfixed = (c->maxw && c->minw && c->maxh && c->minh
855 && c->maxw == c->minw && c->maxh == c->minh);
859 updatetitle(Client *c) {
860 if(!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
861 gettextprop(c->win, wmatom[WMName], c->name, sizeof c->name);
865 getclient(Window w) {
868 for(c = clients; c && c->win != w; c = c->next);
873 movemouse(Client *c) {
874 int x1, y1, ocx, ocy, di, nx, ny;
881 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
882 None, cursor[CurMove], CurrentTime) != GrabSuccess)
885 XQueryPointer(dpy, root, &dummy, &dummy, &x1, &y1, &di, &di, &dui);
887 XMaskEvent(dpy, MOUSEMASK | ExposureMask | SubstructureRedirectMask, &ev);
890 XUngrabPointer(dpy, CurrentTime);
892 case ConfigureRequest:
895 handler[ev.type](&ev);
899 nx = ocx + (ev.xmotion.x - x1);
900 ny = ocy + (ev.xmotion.y - y1);
901 if(abs(wax + nx) < SNAP)
903 else if(abs((wax + waw) - (nx + c->w + 2 * c->border)) < SNAP)
904 nx = wax + waw - c->w - 2 * c->border;
905 if(abs(way - ny) < SNAP)
907 else if(abs((way + wah) - (ny + c->h + 2 * c->border)) < SNAP)
908 ny = way + wah - c->h - 2 * c->border;
909 resize(c, nx, ny, c->w, c->h, False);
916 resizemouse(Client *c) {
923 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
924 None, cursor[CurResize], CurrentTime) != GrabSuccess)
927 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->border - 1, c->h + c->border - 1);
929 XMaskEvent(dpy, MOUSEMASK | ExposureMask | SubstructureRedirectMask , &ev);
932 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0,
933 c->w + c->border - 1, c->h + c->border - 1);
934 XUngrabPointer(dpy, CurrentTime);
935 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
937 case ConfigureRequest:
940 handler[ev.type](&ev);
944 if((nw = ev.xmotion.x - ocx - 2 * c->border + 1) <= 0)
946 if((nh = ev.xmotion.y - ocy - 2 * c->border + 1) <= 0)
948 resize(c, c->x, c->y, nw, nh, True);
955 buttonpress(XEvent *e) {
958 XButtonPressedEvent *ev = &e->xbutton;
960 if(barwin == ev->window) {
962 for(i = 0; i < ntags; i++) {
965 if(ev->button == Button1) {
966 if(ev->state & MODKEY)
971 else if(ev->button == Button3) {
972 if(ev->state & MODKEY)
980 if((ev->x < x + blw) && ev->button == Button1)
983 else if((c = getclient(ev->window))) {
985 if(CLEANMASK(ev->state) != MODKEY)
987 if(ev->button == Button1 && (isfloating() || c->isfloating)) {
991 else if(ev->button == Button2)
993 else if(ev->button == Button3
994 && (isfloating() || c->isfloating) && !c->isfixed)
1003 configurerequest(XEvent *e) {
1005 XConfigureRequestEvent *ev = &e->xconfigurerequest;
1008 if((c = getclient(ev->window))) {
1010 if(ev->value_mask & CWBorderWidth)
1011 c->border = ev->border_width;
1012 if(c->isfixed || c->isfloating || isfloating()) {
1013 if(ev->value_mask & CWX)
1015 if(ev->value_mask & CWY)
1017 if(ev->value_mask & CWWidth)
1019 if(ev->value_mask & CWHeight)
1021 if((c->x + c->w) > sw && c->isfloating)
1022 c->x = sw / 2 - c->w / 2; /* center in x direction */
1023 if((c->y + c->h) > sh && c->isfloating)
1024 c->y = sh / 2 - c->h / 2; /* center in y direction */
1025 if((ev->value_mask & (CWX | CWY))
1026 && !(ev->value_mask & (CWWidth | CWHeight)))
1029 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h);
1037 wc.width = ev->width;
1038 wc.height = ev->height;
1039 wc.border_width = ev->border_width;
1040 wc.sibling = ev->above;
1041 wc.stack_mode = ev->detail;
1042 XConfigureWindow(dpy, ev->window, ev->value_mask, &wc);
1048 configurenotify(XEvent *e) {
1049 XConfigureEvent *ev = &e->xconfigure;
1051 if (ev->window == root && (ev->width != sw || ev->height != sh)) {
1054 XFreePixmap(dpy, dc.drawable);
1055 dc.drawable = XCreatePixmap(dpy, root, sw, bh, DefaultDepth(dpy, screen));
1056 XResizeWindow(dpy, barwin, sw, bh);
1063 destroynotify(XEvent *e) {
1065 XDestroyWindowEvent *ev = &e->xdestroywindow;
1067 if((c = getclient(ev->window)))
1072 enternotify(XEvent *e) {
1074 XCrossingEvent *ev = &e->xcrossing;
1076 if(ev->mode != NotifyNormal || ev->detail == NotifyInferior)
1078 if((c = getclient(ev->window)))
1080 else if(ev->window == root) {
1088 XExposeEvent *ev = &e->xexpose;
1090 if(ev->count == 0) {
1091 if(barwin == ev->window)
1097 keypress(XEvent *e) {
1099 unsigned int len = sizeof keys / sizeof keys[0];
1105 if(!e) { /* grabkeys */
1106 XUngrabKey(dpy, AnyKey, AnyModifier, root);
1107 for(i = 0; i < len; i++) {
1108 code = XKeysymToKeycode(dpy, keys[i].keysym);
1109 XGrabKey(dpy, code, keys[i].mod, root, True,
1110 GrabModeAsync, GrabModeAsync);
1111 XGrabKey(dpy, code, keys[i].mod | LockMask, root, True,
1112 GrabModeAsync, GrabModeAsync);
1113 XGrabKey(dpy, code, keys[i].mod | numlockmask, root, True,
1114 GrabModeAsync, GrabModeAsync);
1115 XGrabKey(dpy, code, keys[i].mod | numlockmask | LockMask, root, True,
1116 GrabModeAsync, GrabModeAsync);
1121 keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
1122 for(i = 0; i < len; i++)
1123 if(keysym == keys[i].keysym
1124 && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state))
1127 keys[i].func(keys[i].arg);
1132 leavenotify(XEvent *e) {
1133 XCrossingEvent *ev = &e->xcrossing;
1135 if((ev->window == root) && !ev->same_screen) {
1142 mappingnotify(XEvent *e) {
1143 XMappingEvent *ev = &e->xmapping;
1145 XRefreshKeyboardMapping(ev);
1146 if(ev->request == MappingKeyboard)
1151 maprequest(XEvent *e) {
1152 static XWindowAttributes wa;
1153 XMapRequestEvent *ev = &e->xmaprequest;
1155 if(!XGetWindowAttributes(dpy, ev->window, &wa))
1157 if(wa.override_redirect)
1159 if(!getclient(ev->window))
1160 manage(ev->window, &wa);
1164 propertynotify(XEvent *e) {
1167 XPropertyEvent *ev = &e->xproperty;
1169 if(ev->state == PropertyDelete)
1170 return; /* ignore */
1171 if((c = getclient(ev->window))) {
1174 case XA_WM_TRANSIENT_FOR:
1175 XGetTransientForHint(dpy, c->win, &trans);
1176 if(!c->isfloating && (c->isfloating = (getclient(trans) != NULL)))
1179 case XA_WM_NORMAL_HINTS:
1183 if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
1192 unmapnotify(XEvent *e) {
1194 XUnmapEvent *ev = &e->xunmap;
1196 if((c = getclient(ev->window)))
1201 idxoftag(const char *tag) {
1204 for(i = 0; i < ntags; i++)
1211 floating(void) { /* default floating layout */
1214 for(c = clients; c; c = c->next)
1216 resize(c, c->x, c->y, c->w, c->h, True);
1220 applyrules(Client *c) {
1221 static char buf[512];
1224 Bool matched = False;
1225 XClassHint ch = { 0 };
1228 XGetClassHint(dpy, c->win, &ch);
1229 snprintf(buf, sizeof buf, "%s:%s:%s",
1230 ch.res_class ? ch.res_class : "",
1231 ch.res_name ? ch.res_name : "", c->name);
1232 for(i = 0; i < nrules; i++)
1233 if(regs[i].propregex && !regexec(regs[i].propregex, buf, 1, &tmp, 0)) {
1234 c->isfloating = rules[i].isfloating;
1235 for(j = 0; regs[i].tagregex && j < ntags; j++) {
1236 if(!regexec(regs[i].tagregex, tags[j], 1, &tmp, 0)) {
1243 XFree(ch.res_class);
1247 for(i = 0; i < ntags; i++)
1248 c->tags[i] = seltags[i];
1258 nrules = sizeof rules / sizeof rules[0];
1259 regs = emallocz(nrules * sizeof(Regs));
1260 for(i = 0; i < nrules; i++) {
1262 reg = emallocz(sizeof(regex_t));
1263 if(regcomp(reg, rules[i].prop, REG_EXTENDED))
1266 regs[i].propregex = reg;
1269 reg = emallocz(sizeof(regex_t));
1270 if(regcomp(reg, rules[i].tags, REG_EXTENDED))
1273 regs[i].tagregex = reg;
1279 focusnext(const char *arg) {
1284 for(c = sel->next; c && !isvisible(c); c = c->next);
1286 for(c = clients; c && !isvisible(c); c = c->next);
1294 focusprev(const char *arg) {
1299 for(c = sel->prev; c && !isvisible(c); c = c->prev);
1301 for(c = clients; c && c->next; c = c->next);
1302 for(; c && !isvisible(c); c = c->prev);
1314 nlayouts = sizeof layouts / sizeof layouts[0];
1315 for(blw = i = 0; i < nlayouts; i++) {
1316 w = textw(layouts[i].symbol);
1324 return layouts[ltidx].arrange == floating;
1328 isvisible(Client *c) {
1331 for(i = 0; i < ntags; i++)
1332 if(c->tags[i] && seltags[i])
1346 if(sel->isfloating || isfloating())
1347 XRaiseWindow(dpy, sel->win);
1349 wc.stack_mode = Below;
1350 wc.sibling = barwin;
1351 if(!sel->isfloating) {
1352 XConfigureWindow(dpy, sel->win, CWSibling | CWStackMode, &wc);
1353 wc.sibling = sel->win;
1355 for(c = nexttiled(clients); c; c = nexttiled(c->next)) {
1358 XConfigureWindow(dpy, c->win, CWSibling | CWStackMode, &wc);
1359 wc.sibling = c->win;
1363 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1367 setlayout(const char *arg) {
1371 if(++ltidx == nlayouts)
1375 for(i = 0; i < nlayouts; i++)
1376 if(!strcmp(arg, layouts[i].symbol))
1389 tag(const char *arg) {
1394 for(i = 0; i < ntags; i++)
1395 sel->tags[i] = arg == NULL;
1397 if(i >= 0 && i < ntags)
1398 sel->tags[i] = True;
1403 togglefloating(const char *arg) {
1406 sel->isfloating = !sel->isfloating;
1408 resize(sel, sel->x, sel->y, sel->w, sel->h, True);
1413 togglemax(const char *arg) {
1416 if(!sel || (!isfloating() && !sel->isfloating) || sel->isfixed)
1418 if((sel->ismax = !sel->ismax)) {
1423 resize(sel, wax, way, waw - 2 * sel->border, wah - 2 * sel->border, True);
1426 resize(sel, sel->rx, sel->ry, sel->rw, sel->rh, True);
1428 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1432 toggletag(const char *arg) {
1438 sel->tags[i] = !sel->tags[i];
1439 for(j = 0; j < ntags && !sel->tags[j]; j++);
1441 sel->tags[i] = True;
1446 toggleview(const char *arg) {
1450 seltags[i] = !seltags[i];
1451 for(j = 0; j < ntags && !seltags[j]; j++);
1453 seltags[i] = True; /* cannot toggle last view */
1458 view(const char *arg) {
1461 for(i = 0; i < ntags; i++)
1462 seltags[i] = arg == NULL;
1464 if(i >= 0 && i < ntags)
1471 close(STDIN_FILENO);
1477 XFreeFontSet(dpy, dc.font.set);
1479 XFreeFont(dpy, dc.font.xfont);
1480 XUngrabKey(dpy, AnyKey, AnyModifier, root);
1481 XFreePixmap(dpy, dc.drawable);
1482 XFreeGC(dpy, dc.gc);
1483 XDestroyWindow(dpy, barwin);
1484 XFreeCursor(dpy, cursor[CurNormal]);
1485 XFreeCursor(dpy, cursor[CurResize]);
1486 XFreeCursor(dpy, cursor[CurMove]);
1487 XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime);
1493 getstate(Window w) {
1496 unsigned char *p = NULL;
1497 unsigned long n, extra;
1500 status = XGetWindowProperty(dpy, w, wmatom[WMState], 0L, 2L, False, wmatom[WMState],
1501 &real, &format, &n, &extra, (unsigned char **)&p);
1502 if(status != Success)
1512 unsigned int i, num;
1513 Window *wins, d1, d2;
1514 XWindowAttributes wa;
1517 if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1518 for(i = 0; i < num; i++) {
1519 if(!XGetWindowAttributes(dpy, wins[i], &wa)
1520 || wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1522 if(wa.map_state == IsViewable || getstate(wins[i]) == IconicState)
1523 manage(wins[i], &wa);
1525 for(i = 0; i < num; i++) { /* now the transients */
1526 if(!XGetWindowAttributes(dpy, wins[i], &wa))
1528 if(XGetTransientForHint(dpy, wins[i], &d1)
1529 && (wa.map_state == IsViewable || getstate(wins[i]) == IconicState))
1530 manage(wins[i], &wa);
1542 XModifierKeymap *modmap;
1543 XSetWindowAttributes wa;
1546 wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1547 wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1548 wmatom[WMName] = XInternAtom(dpy, "WM_NAME", False);
1549 wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1550 netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1551 netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1552 XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1553 PropModeReplace, (unsigned char *) netatom, NetLast);
1555 cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1556 cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1557 cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1558 /* init modifier map */
1559 modmap = XGetModifierMapping(dpy);
1560 for (i = 0; i < 8; i++)
1561 for (j = 0; j < modmap->max_keypermod; j++) {
1562 if(modmap->modifiermap[i * modmap->max_keypermod + j]
1563 == XKeysymToKeycode(dpy, XK_Num_Lock))
1564 numlockmask = (1 << i);
1566 XFreeModifiermap(modmap);
1567 /* select for events */
1568 wa.event_mask = SubstructureRedirectMask | SubstructureNotifyMask
1569 | EnterWindowMask | LeaveWindowMask | StructureNotifyMask;
1570 wa.cursor = cursor[CurNormal];
1571 XChangeWindowAttributes(dpy, root, CWEventMask | CWCursor, &wa);
1572 XSelectInput(dpy, root, wa.event_mask);
1573 keypress(NULL); /* grabkeys */
1575 for(ntags = 0; tags[ntags]; ntags++);
1576 seltags = emallocz(sizeof(Bool) * ntags);
1580 sw = DisplayWidth(dpy, screen);
1581 sh = DisplayHeight(dpy, screen);
1585 /* multihead support */
1586 selscreen = XQueryPointer(dpy, root, &w, &w, &i, &i, &i, &i, &mask);
1590 * Startup Error handler to check if another window manager
1591 * is already running.
1594 xerrorstart(Display *dsply, XErrorEvent *ee) {
1600 gettextprop(Window w, Atom atom, char *text, unsigned int size) {
1605 if(!text || size == 0)
1608 XGetTextProperty(dpy, w, &name, atom);
1611 if(name.encoding == XA_STRING)
1612 strncpy(text, (char *)name.value, size - 1);
1614 if(XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success
1617 strncpy(text, *list, size - 1);
1618 XFreeStringList(list);
1621 text[size - 1] = '\0';
1627 quit(const char *arg) {
1628 readin = running = False;
1631 /* There's no way to check accesses to destroyed windows, thus those cases are
1632 * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
1633 * default error handler, which may call exit.
1636 xerror(Display *dpy, XErrorEvent *ee) {
1637 if(ee->error_code == BadWindow
1638 || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1639 || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1640 || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1641 || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1642 || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1643 || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1644 || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1646 fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1647 ee->request_code, ee->error_code);
1648 return xerrorxlib(dpy, ee); /* may call exit */
1655 for(c = clients; c; c = c->next)
1660 layouts[ltidx].arrange();
1676 c->prev->next = c->next;
1678 c->next->prev = c->prev;
1681 c->next = c->prev = NULL;
1686 if((!c && selscreen) || (c && !isvisible(c)))
1687 for(c = stack; c && !isvisible(c); c = c->snext);
1688 if(sel && sel != c) {
1689 grabbuttons(sel, False);
1690 XSetWindowBorder(dpy, sel->win, dc.norm[ColBorder]);
1695 grabbuttons(c, True);
1702 XSetWindowBorder(dpy, c->win, dc.sel[ColBorder]);
1703 XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
1706 XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
1710 isarrange(void (*func)())
1712 return func == layouts[ltidx].arrange;
1716 nexttiled(Client *c) {
1717 for(; c && (c->isfloating || !isvisible(c)); c = c->next);
1722 setmwfact(const char *arg) {
1725 if(!isarrange(tile))
1727 /* arg handling, manipulate mwfact */
1730 else if(1 == sscanf(arg, "%lf", &delta)) {
1731 if(arg[0] != '+' && arg[0] != '-')
1737 else if(mwfact > 0.9)
1745 unsigned int i, n, nx, ny, nw, nh, mw, th;
1748 for(n = 0, c = nexttiled(clients); c; c = nexttiled(c->next))
1752 mw = (n == 1) ? waw : mwfact * waw;
1753 th = (n > 1) ? wah / (n - 1) : 0;
1754 if(n > 1 && th < bh)
1759 for(i = 0, c = nexttiled(clients); c; c = nexttiled(c->next), i++) {
1761 if(i == 0) { /* master */
1762 nw = mw - 2 * c->border;
1763 nh = wah - 2 * c->border;
1765 else { /* tile window */
1770 nw = waw - mw - 2 * c->border;
1771 if(i + 1 == n) /* remainder */
1772 nh = (way + wah) - ny - 2 * c->border;
1774 nh = th - 2 * c->border;
1776 resize(c, nx, ny, nw, nh, RESIZEHINTS);
1777 if(n > 1 && th != wah)
1778 ny += nh + 2 * c->border;
1783 zoom(const char *arg) {
1786 if(!sel || !isarrange(tile) || sel->isfloating)
1788 if((c = sel) == nexttiled(clients))
1789 if(!(c = nexttiled(c->next)))
1798 main(int argc, char *argv[]) {
1804 if(argc == 2 && !strcmp("-v", argv[1]))
1805 eprint("dwm-"VERSION", © 2006-2007 A. R. Garbe, S. van Dijk, J. Salmi, P. Hruby, S. Nagy\n");
1807 eprint("usage: dwm [-v]\n");
1808 setlocale(LC_CTYPE, "");
1809 if(!(dpy = XOpenDisplay(0)))
1810 eprint("dwm: cannot open display\n");
1811 xfd = ConnectionNumber(dpy);
1812 screen = DefaultScreen(dpy);
1813 root = RootWindow(dpy, screen);
1815 XSetErrorHandler(xerrorstart);
1816 /* this causes an error if some other window manager is running */
1817 XSelectInput(dpy, root, SubstructureRedirectMask);
1820 eprint("dwm: another window manager is already running\n");
1823 XSetErrorHandler(NULL);
1824 xerrorxlib = XSetErrorHandler(xerror);
1830 /* main event loop, also reads status text from stdin */
1836 FD_SET(STDIN_FILENO, &rd);
1838 if(select(xfd + 1, &rd, NULL, NULL, NULL) == -1) {
1841 eprint("select failed\n");
1843 if(FD_ISSET(STDIN_FILENO, &rd)) {
1844 switch(r = read(STDIN_FILENO, stext, sizeof stext - 1)) {
1846 strncpy(stext, strerror(errno), sizeof stext - 1);
1847 stext[sizeof stext - 1] = '\0';
1851 strncpy(stext, "EOF", 4);
1855 for(stext[r] = '\0', p = stext + strlen(stext) - 1; p >= stext && *p == '\n'; *p-- = '\0');
1856 for(; p >= stext && *p != '\n'; --p);
1858 strncpy(stext, p + 1, sizeof stext);
1862 while(XPending(dpy)) {
1863 XNextEvent(dpy, &ev);
1864 if(handler[ev.type])
1865 (handler[ev.type])(&ev); /* call handler */