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);
117 static void applyrules(Client *c);
118 static void arrange(void);
119 static void attach(Client *c);
120 static void attachstack(Client *c);
121 static void ban(Client *c);
122 static void buttonpress(XEvent *e);
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 long getstate(Window w);
144 static Bool gettextprop(Window w, Atom atom, char *text, unsigned int size);
145 static void grabbuttons(Client *c, Bool focused);
146 static unsigned int idxoftag(const char *tag);
147 static void initbar(void);
148 static unsigned long initcolor(const char *colstr);
149 static void initfont(const char *fontstr);
150 static void initlayouts(void);
151 static void initstyle(void);
152 static Bool isarrange(void (*func)());
153 static Bool isfloating(void);
154 static Bool isoccupied(unsigned int t);
155 static Bool isprotodel(Client *c);
156 static Bool isvisible(Client *c);
157 static void keypress(XEvent *e);
158 static void killclient(const char *arg);
159 static void leavenotify(XEvent *e);
160 static void manage(Window w, XWindowAttributes *wa);
161 static void mappingnotify(XEvent *e);
162 static void maprequest(XEvent *e);
163 static void movemouse(Client *c);
164 static Client *nexttiled(Client *c);
165 static void propertynotify(XEvent *e);
166 static void quit(const char *arg);
167 static void resize(Client *c, int x, int y, int w, int h, Bool sizehints);
168 static void resizemouse(Client *c);
169 static void restack(void);
170 static void scan(void);
171 static void setclientstate(Client *c, long state);
172 static void setlayout(const char *arg);
173 static void setmwfact(const char *arg);
174 static void setup(void);
175 static void spawn(const char *arg);
176 static void tag(const char *arg);
177 static unsigned int textnw(const char *text, unsigned int len);
178 static unsigned int textw(const char *text);
179 static void tile(void);
180 static void togglebar(const char *arg);
181 static void togglefloating(const char *arg);
182 static void togglemax(const char *arg);
183 static void toggletag(const char *arg);
184 static void toggleview(const char *arg);
185 static void unban(Client *c);
186 static void unmanage(Client *c);
187 static void unmapnotify(XEvent *e);
188 static void updatebarpos(void);
189 static void updatesizehints(Client *c);
190 static void updatetitle(Client *c);
191 static void view(const char *arg);
192 static int xerror(Display *dpy, XErrorEvent *ee);
193 static int xerrordummy(Display *dsply, XErrorEvent *ee);
194 static int xerrorstart(Display *dsply, XErrorEvent *ee);
195 static void zoom(const char *arg);
200 static char stext[256];
201 static double mwfact = MWFACT;
202 static int screen, sx, sy, sw, sh, wax, way, waw, wah;
203 static int (*xerrorxlib)(Display *, XErrorEvent *);
204 static unsigned int bh;
205 static unsigned int blw = 0;
206 static unsigned int bpos = BARPOS;
207 static unsigned int ltidx = 0; /* default */
208 static unsigned int nlayouts = 0;
209 static unsigned int nrules = 0;
210 static unsigned int ntags;
211 static unsigned int numlockmask = 0;
212 static void (*handler[LASTEvent]) (XEvent *) = {
213 [ButtonPress] = buttonpress,
214 [ConfigureRequest] = configurerequest,
215 [ConfigureNotify] = configurenotify,
216 [DestroyNotify] = destroynotify,
217 [EnterNotify] = enternotify,
218 [LeaveNotify] = leavenotify,
220 [KeyPress] = keypress,
221 [MappingNotify] = mappingnotify,
222 [MapRequest] = maprequest,
223 [PropertyNotify] = propertynotify,
224 [UnmapNotify] = unmapnotify
226 static Atom wmatom[WMLast], netatom[NetLast];
227 static Bool otherwm, readin;
228 static Bool running = True;
229 static Bool *seltags;
230 static Bool selscreen = True;
231 static Client *clients = NULL;
232 static Client *sel = NULL;
233 static Client *stack = NULL;
234 static Cursor cursor[CurLast];
237 static Window barwin, root;
238 static Regs *regs = NULL;
241 eprint(const char *errstr, ...) {
244 va_start(ap, errstr);
245 vfprintf(stderr, errstr, ap);
251 emallocz(unsigned int size) {
252 void *res = calloc(1, size);
255 eprint("fatal: could not malloc() %u bytes\n", size);
260 spawn(const char *arg) {
261 static char *shell = NULL;
263 if(!shell && !(shell = getenv("SHELL")))
267 /* The double-fork construct avoids zombie processes and keeps the code
268 * clean from stupid signal handlers. */
272 close(ConnectionNumber(dpy));
274 execl(shell, shell, "-c", arg, (char *)NULL);
275 fprintf(stderr, "dwm: execl '%s -c %s'", shell, arg);
284 drawsquare(Bool filled, Bool empty, unsigned long col[ColLast]) {
287 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
289 gcv.foreground = col[ColFG];
290 XChangeGC(dpy, dc.gc, GCForeground, &gcv);
291 x = (dc.font.ascent + dc.font.descent + 2) / 4;
295 r.width = r.height = x + 1;
296 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
299 r.width = r.height = x;
300 XDrawRectangles(dpy, dc.drawable, dc.gc, &r, 1);
305 initcolor(const char *colstr) {
306 Colormap cmap = DefaultColormap(dpy, screen);
309 if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
310 eprint("error, cannot allocate color '%s'\n", colstr);
315 initfont(const char *fontstr) {
316 char *def, **missing;
321 XFreeFontSet(dpy, dc.font.set);
322 dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
325 fprintf(stderr, "dwm: missing fontset: %s\n", missing[n]);
326 XFreeStringList(missing);
329 XFontSetExtents *font_extents;
330 XFontStruct **xfonts;
332 dc.font.ascent = dc.font.descent = 0;
333 font_extents = XExtentsOfFontSet(dc.font.set);
334 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
335 for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
336 if(dc.font.ascent < (*xfonts)->ascent)
337 dc.font.ascent = (*xfonts)->ascent;
338 if(dc.font.descent < (*xfonts)->descent)
339 dc.font.descent = (*xfonts)->descent;
345 XFreeFont(dpy, dc.font.xfont);
346 dc.font.xfont = NULL;
347 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr))
348 || !(dc.font.xfont = XLoadQueryFont(dpy, "fixed")))
349 eprint("error, cannot load font: '%s'\n", fontstr);
350 dc.font.ascent = dc.font.xfont->ascent;
351 dc.font.descent = dc.font.xfont->descent;
353 dc.font.height = dc.font.ascent + dc.font.descent;
357 isoccupied(unsigned int t) {
360 for(c = clients; c; c = c->next)
367 textnw(const char *text, unsigned int len) {
371 XmbTextExtents(dc.font.set, text, len, NULL, &r);
374 return XTextWidth(dc.font.xfont, text, len);
378 drawtext(const char *text, unsigned long col[ColLast]) {
380 static char buf[256];
381 unsigned int len, olen;
382 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
384 XSetForeground(dpy, dc.gc, col[ColBG]);
385 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
389 olen = len = strlen(text);
390 if(len >= sizeof buf)
391 len = sizeof buf - 1;
392 memcpy(buf, text, len);
394 h = dc.font.ascent + dc.font.descent;
395 y = dc.y + (dc.h / 2) - (h / 2) + dc.font.ascent;
397 /* shorten text if necessary */
398 while(len && (w = textnw(buf, len)) > dc.w - h)
409 return; /* too long */
410 XSetForeground(dpy, dc.gc, col[ColFG]);
412 XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
414 XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
422 for(i = 0; i < ntags; i++) {
423 dc.w = textw(tags[i]);
425 drawtext(tags[i], dc.sel);
426 drawsquare(sel && sel->tags[i], isoccupied(i), dc.sel);
429 drawtext(tags[i], dc.norm);
430 drawsquare(sel && sel->tags[i], isoccupied(i), dc.norm);
435 drawtext(layouts[ltidx].symbol, dc.norm);
443 drawtext(stext, dc.norm);
444 if((dc.w = dc.x - x) > bh) {
447 drawtext(sel->name, dc.sel);
448 drawsquare(sel->ismax, sel->isfloating, dc.sel);
451 drawtext(NULL, dc.norm);
453 XCopyArea(dpy, dc.drawable, barwin, dc.gc, 0, 0, sw, bh, 0, 0);
459 dc.norm[ColBorder] = initcolor(NORMBORDERCOLOR);
460 dc.norm[ColBG] = initcolor(NORMBGCOLOR);
461 dc.norm[ColFG] = initcolor(NORMFGCOLOR);
462 dc.sel[ColBorder] = initcolor(SELBORDERCOLOR);
463 dc.sel[ColBG] = initcolor(SELBGCOLOR);
464 dc.sel[ColFG] = initcolor(SELFGCOLOR);
466 dc.h = bh = dc.font.height + 2;
471 XSetWindowAttributes wa;
473 wa.override_redirect = 1;
474 wa.background_pixmap = ParentRelative;
475 wa.event_mask = ButtonPressMask | ExposureMask;
476 barwin = XCreateWindow(dpy, root, sx, sy, sw, bh, 0,
477 DefaultDepth(dpy, screen), CopyFromParent, DefaultVisual(dpy, screen),
478 CWOverrideRedirect | CWBackPixmap | CWEventMask, &wa);
479 XDefineCursor(dpy, barwin, cursor[CurNormal]);
481 XMapRaised(dpy, barwin);
482 strcpy(stext, "dwm-"VERSION);
483 dc.drawable = XCreatePixmap(dpy, root, sw, bh, DefaultDepth(dpy, screen));
484 dc.gc = XCreateGC(dpy, root, 0, 0);
485 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
487 XSetFont(dpy, dc.gc, dc.font.xfont->fid);
491 textw(const char *text) {
492 return textnw(text, strlen(text)) + dc.font.height;
496 togglebar(const char *arg) {
498 bpos = (BARPOS == BarOff) ? BarTop : BARPOS;
517 XMoveWindow(dpy, barwin, sx, sy);
521 XMoveWindow(dpy, barwin, sx, sy + wah);
524 XMoveWindow(dpy, barwin, sx, sy - bh);
528 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
532 attachstack(Client *c) {
538 detachstack(Client *c) {
541 for(tc=&stack; *tc && *tc != c; tc=&(*tc)->snext);
546 grabbuttons(Client *c, Bool focused) {
547 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
550 XGrabButton(dpy, Button1, MODKEY, c->win, False, BUTTONMASK,
551 GrabModeAsync, GrabModeSync, None, None);
552 XGrabButton(dpy, Button1, MODKEY | LockMask, c->win, False, BUTTONMASK,
553 GrabModeAsync, GrabModeSync, None, None);
554 XGrabButton(dpy, Button1, MODKEY | numlockmask, c->win, False, BUTTONMASK,
555 GrabModeAsync, GrabModeSync, None, None);
556 XGrabButton(dpy, Button1, MODKEY | numlockmask | LockMask, c->win, False, BUTTONMASK,
557 GrabModeAsync, GrabModeSync, None, None);
559 XGrabButton(dpy, Button2, MODKEY, c->win, False, BUTTONMASK,
560 GrabModeAsync, GrabModeSync, None, None);
561 XGrabButton(dpy, Button2, MODKEY | LockMask, c->win, False, BUTTONMASK,
562 GrabModeAsync, GrabModeSync, None, None);
563 XGrabButton(dpy, Button2, MODKEY | numlockmask, c->win, False, BUTTONMASK,
564 GrabModeAsync, GrabModeSync, None, None);
565 XGrabButton(dpy, Button2, MODKEY | numlockmask | LockMask, c->win, False, BUTTONMASK,
566 GrabModeAsync, GrabModeSync, None, None);
568 XGrabButton(dpy, Button3, MODKEY, c->win, False, BUTTONMASK,
569 GrabModeAsync, GrabModeSync, None, None);
570 XGrabButton(dpy, Button3, MODKEY | LockMask, c->win, False, BUTTONMASK,
571 GrabModeAsync, GrabModeSync, None, None);
572 XGrabButton(dpy, Button3, MODKEY | numlockmask, c->win, False, BUTTONMASK,
573 GrabModeAsync, GrabModeSync, None, None);
574 XGrabButton(dpy, Button3, MODKEY | numlockmask | LockMask, c->win, False, BUTTONMASK,
575 GrabModeAsync, GrabModeSync, None, None);
578 XGrabButton(dpy, AnyButton, AnyModifier, c->win, False, BUTTONMASK,
579 GrabModeAsync, GrabModeSync, None, None);
583 isprotodel(Client *c) {
588 if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
589 for(i = 0; !ret && i < n; i++)
590 if(protocols[i] == wmatom[WMDelete])
598 setclientstate(Client *c, long state) {
599 long data[] = {state, None};
601 XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
602 PropModeReplace, (unsigned char *)data, 2);
606 xerrordummy(Display *dsply, XErrorEvent *ee) {
614 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
619 configure(Client *c) {
622 ce.type = ConfigureNotify;
630 ce.border_width = c->border;
632 ce.override_redirect = False;
633 XSendEvent(dpy, c->win, False, StructureNotifyMask, (XEvent *)&ce);
637 killclient(const char *arg) {
642 if(isprotodel(sel)) {
643 ev.type = ClientMessage;
644 ev.xclient.window = sel->win;
645 ev.xclient.message_type = wmatom[WMProtocols];
646 ev.xclient.format = 32;
647 ev.xclient.data.l[0] = wmatom[WMDelete];
648 ev.xclient.data.l[1] = CurrentTime;
649 XSendEvent(dpy, sel->win, False, NoEventMask, &ev);
652 XKillClient(dpy, sel->win);
656 manage(Window w, XWindowAttributes *wa) {
658 Client *c, *t = NULL;
663 c = emallocz(sizeof(Client));
664 c->tags = emallocz(ntags * sizeof(Bool));
670 c->oldborder = wa->border_width;
671 if(c->w == sw && c->h == sh) {
674 c->border = wa->border_width;
677 if(c->x + c->w + 2 * c->border > wax + waw)
678 c->x = wax + waw - c->w - 2 * c->border;
679 if(c->y + c->h + 2 * c->border > way + wah)
680 c->y = way + wah - c->h - 2 * c->border;
685 c->border = BORDERPX;
687 wc.border_width = c->border;
688 XConfigureWindow(dpy, w, CWBorderWidth, &wc);
689 XSetWindowBorder(dpy, w, dc.norm[ColBorder]);
690 configure(c); /* propagates border_width, if size doesn't change */
693 StructureNotifyMask | PropertyChangeMask | EnterWindowMask);
694 grabbuttons(c, False);
696 if((rettrans = XGetTransientForHint(dpy, w, &trans) == Success))
697 for(t = clients; t && t->win != trans; t = t->next);
699 for(i = 0; i < ntags; i++)
700 c->tags[i] = t->tags[i];
703 c->isfloating = (rettrans == Success) || c->isfixed;
706 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h); /* some windows require this */
708 XMapWindow(dpy, c->win);
709 setclientstate(c, NormalState);
714 resize(Client *c, int x, int y, int w, int h, Bool sizehints) {
715 double dx, dy, max, min, ratio;
719 if(c->minay > 0 && c->maxay > 0 && (h - c->baseh) > 0 && (w - c->basew) > 0) {
720 dx = (double)(w - c->basew);
721 dy = (double)(h - c->baseh);
722 min = (double)(c->minax) / (double)(c->minay);
723 max = (double)(c->maxax) / (double)(c->maxay);
725 if(max > 0 && min > 0 && ratio > 0) {
727 dy = (dx * min + dy) / (min * min + 1);
729 w = (int)dx + c->basew;
730 h = (int)dy + c->baseh;
732 else if(ratio > max) {
733 dy = (dx * min + dy) / (max * max + 1);
735 w = (int)dx + c->basew;
736 h = (int)dy + c->baseh;
740 if(c->minw && w < c->minw)
742 if(c->minh && h < c->minh)
744 if(c->maxw && w > c->maxw)
746 if(c->maxh && h > c->maxh)
749 w -= (w - c->basew) % c->incw;
751 h -= (h - c->baseh) % c->inch;
755 /* offscreen appearance fixes */
757 x = sw - w - 2 * c->border;
759 y = sh - h - 2 * c->border;
760 if(x + w + 2 * c->border < sx)
762 if(y + h + 2 * c->border < sy)
764 if(c->x != x || c->y != y || c->w != w || c->h != h) {
768 c->h = wc.height = h;
769 wc.border_width = c->border;
770 XConfigureWindow(dpy, c->win, CWX | CWY | CWWidth | CWHeight | CWBorderWidth, &wc);
780 XMoveWindow(dpy, c->win, c->x, c->y);
785 unmanage(Client *c) {
788 wc.border_width = c->oldborder;
789 /* The server grab construct avoids race conditions. */
791 XSetErrorHandler(xerrordummy);
792 XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
797 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
798 setclientstate(c, WithdrawnState);
802 XSetErrorHandler(xerror);
808 updatesizehints(Client *c) {
812 if(!XGetWMNormalHints(dpy, c->win, &size, &msize) || !size.flags)
814 c->flags = size.flags;
815 if(c->flags & PBaseSize) {
816 c->basew = size.base_width;
817 c->baseh = size.base_height;
819 else if(c->flags & PMinSize) {
820 c->basew = size.min_width;
821 c->baseh = size.min_height;
824 c->basew = c->baseh = 0;
825 if(c->flags & PResizeInc) {
826 c->incw = size.width_inc;
827 c->inch = size.height_inc;
830 c->incw = c->inch = 0;
831 if(c->flags & PMaxSize) {
832 c->maxw = size.max_width;
833 c->maxh = size.max_height;
836 c->maxw = c->maxh = 0;
837 if(c->flags & PMinSize) {
838 c->minw = size.min_width;
839 c->minh = size.min_height;
841 else if(c->flags & PBaseSize) {
842 c->minw = size.base_width;
843 c->minh = size.base_height;
846 c->minw = c->minh = 0;
847 if(c->flags & PAspect) {
848 c->minax = size.min_aspect.x;
849 c->maxax = size.max_aspect.x;
850 c->minay = size.min_aspect.y;
851 c->maxay = size.max_aspect.y;
854 c->minax = c->maxax = c->minay = c->maxay = 0;
855 c->isfixed = (c->maxw && c->minw && c->maxh && c->minh
856 && c->maxw == c->minw && c->maxh == c->minh);
860 updatetitle(Client *c) {
861 if(!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
862 gettextprop(c->win, wmatom[WMName], c->name, sizeof c->name);
866 getclient(Window w) {
869 for(c = clients; c && c->win != w; c = c->next);
874 movemouse(Client *c) {
875 int x1, y1, ocx, ocy, di, nx, ny;
882 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
883 None, cursor[CurMove], CurrentTime) != GrabSuccess)
886 XQueryPointer(dpy, root, &dummy, &dummy, &x1, &y1, &di, &di, &dui);
888 XMaskEvent(dpy, MOUSEMASK | ExposureMask | SubstructureRedirectMask, &ev);
891 XUngrabPointer(dpy, CurrentTime);
893 case ConfigureRequest:
896 handler[ev.type](&ev);
900 nx = ocx + (ev.xmotion.x - x1);
901 ny = ocy + (ev.xmotion.y - y1);
902 if(abs(wax + nx) < SNAP)
904 else if(abs((wax + waw) - (nx + c->w + 2 * c->border)) < SNAP)
905 nx = wax + waw - c->w - 2 * c->border;
906 if(abs(way - ny) < SNAP)
908 else if(abs((way + wah) - (ny + c->h + 2 * c->border)) < SNAP)
909 ny = way + wah - c->h - 2 * c->border;
910 resize(c, nx, ny, c->w, c->h, False);
917 resizemouse(Client *c) {
924 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
925 None, cursor[CurResize], CurrentTime) != GrabSuccess)
928 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->border - 1, c->h + c->border - 1);
930 XMaskEvent(dpy, MOUSEMASK | ExposureMask | SubstructureRedirectMask , &ev);
933 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0,
934 c->w + c->border - 1, c->h + c->border - 1);
935 XUngrabPointer(dpy, CurrentTime);
936 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
938 case ConfigureRequest:
941 handler[ev.type](&ev);
945 if((nw = ev.xmotion.x - ocx - 2 * c->border + 1) <= 0)
947 if((nh = ev.xmotion.y - ocy - 2 * c->border + 1) <= 0)
949 resize(c, c->x, c->y, nw, nh, True);
956 buttonpress(XEvent *e) {
959 XButtonPressedEvent *ev = &e->xbutton;
961 if(barwin == ev->window) {
963 for(i = 0; i < ntags; i++) {
966 if(ev->button == Button1) {
967 if(ev->state & MODKEY)
972 else if(ev->button == Button3) {
973 if(ev->state & MODKEY)
981 if((ev->x < x + blw) && ev->button == Button1)
984 else if((c = getclient(ev->window))) {
986 if(CLEANMASK(ev->state) != MODKEY)
988 if(ev->button == Button1 && (isfloating() || c->isfloating)) {
992 else if(ev->button == Button2)
994 else if(ev->button == Button3
995 && (isfloating() || c->isfloating) && !c->isfixed)
1004 configurerequest(XEvent *e) {
1006 XConfigureRequestEvent *ev = &e->xconfigurerequest;
1009 if((c = getclient(ev->window))) {
1011 if(ev->value_mask & CWBorderWidth)
1012 c->border = ev->border_width;
1013 if(c->isfixed || c->isfloating || isfloating()) {
1014 if(ev->value_mask & CWX)
1016 if(ev->value_mask & CWY)
1018 if(ev->value_mask & CWWidth)
1020 if(ev->value_mask & CWHeight)
1022 if((c->x + c->w) > sw && c->isfloating)
1023 c->x = sw / 2 - c->w / 2; /* center in x direction */
1024 if((c->y + c->h) > sh && c->isfloating)
1025 c->y = sh / 2 - c->h / 2; /* center in y direction */
1026 if((ev->value_mask & (CWX | CWY))
1027 && !(ev->value_mask & (CWWidth | CWHeight)))
1030 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h);
1038 wc.width = ev->width;
1039 wc.height = ev->height;
1040 wc.border_width = ev->border_width;
1041 wc.sibling = ev->above;
1042 wc.stack_mode = ev->detail;
1043 XConfigureWindow(dpy, ev->window, ev->value_mask, &wc);
1049 configurenotify(XEvent *e) {
1050 XConfigureEvent *ev = &e->xconfigure;
1052 if (ev->window == root && (ev->width != sw || ev->height != sh)) {
1055 XFreePixmap(dpy, dc.drawable);
1056 dc.drawable = XCreatePixmap(dpy, root, sw, bh, DefaultDepth(dpy, screen));
1057 XResizeWindow(dpy, barwin, sw, bh);
1064 destroynotify(XEvent *e) {
1066 XDestroyWindowEvent *ev = &e->xdestroywindow;
1068 if((c = getclient(ev->window)))
1073 enternotify(XEvent *e) {
1075 XCrossingEvent *ev = &e->xcrossing;
1077 if(ev->mode != NotifyNormal || ev->detail == NotifyInferior)
1079 if((c = getclient(ev->window)))
1081 else if(ev->window == root) {
1089 XExposeEvent *ev = &e->xexpose;
1091 if(ev->count == 0) {
1092 if(barwin == ev->window)
1098 keypress(XEvent *e) {
1100 unsigned int len = sizeof keys / sizeof keys[0];
1106 if(!e) { /* grabkeys */
1107 XUngrabKey(dpy, AnyKey, AnyModifier, root);
1108 for(i = 0; i < len; i++) {
1109 code = XKeysymToKeycode(dpy, keys[i].keysym);
1110 XGrabKey(dpy, code, keys[i].mod, root, True,
1111 GrabModeAsync, GrabModeAsync);
1112 XGrabKey(dpy, code, keys[i].mod | LockMask, root, True,
1113 GrabModeAsync, GrabModeAsync);
1114 XGrabKey(dpy, code, keys[i].mod | numlockmask, root, True,
1115 GrabModeAsync, GrabModeAsync);
1116 XGrabKey(dpy, code, keys[i].mod | numlockmask | LockMask, root, True,
1117 GrabModeAsync, GrabModeAsync);
1122 keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
1123 for(i = 0; i < len; i++)
1124 if(keysym == keys[i].keysym
1125 && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state))
1128 keys[i].func(keys[i].arg);
1133 leavenotify(XEvent *e) {
1134 XCrossingEvent *ev = &e->xcrossing;
1136 if((ev->window == root) && !ev->same_screen) {
1143 mappingnotify(XEvent *e) {
1144 XMappingEvent *ev = &e->xmapping;
1146 XRefreshKeyboardMapping(ev);
1147 if(ev->request == MappingKeyboard)
1152 maprequest(XEvent *e) {
1153 static XWindowAttributes wa;
1154 XMapRequestEvent *ev = &e->xmaprequest;
1156 if(!XGetWindowAttributes(dpy, ev->window, &wa))
1158 if(wa.override_redirect)
1160 if(!getclient(ev->window))
1161 manage(ev->window, &wa);
1165 propertynotify(XEvent *e) {
1168 XPropertyEvent *ev = &e->xproperty;
1170 if(ev->state == PropertyDelete)
1171 return; /* ignore */
1172 if((c = getclient(ev->window))) {
1175 case XA_WM_TRANSIENT_FOR:
1176 XGetTransientForHint(dpy, c->win, &trans);
1177 if(!c->isfloating && (c->isfloating = (getclient(trans) != NULL)))
1180 case XA_WM_NORMAL_HINTS:
1184 if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
1193 unmapnotify(XEvent *e) {
1195 XUnmapEvent *ev = &e->xunmap;
1197 if((c = getclient(ev->window)))
1202 idxoftag(const char *tag) {
1205 for(i = 0; i < ntags; i++)
1212 floating(void) { /* default floating layout */
1215 for(c = clients; c; c = c->next)
1217 resize(c, c->x, c->y, c->w, c->h, True);
1221 applyrules(Client *c) {
1222 static char buf[512];
1225 Bool matched = False;
1226 XClassHint ch = { 0 };
1229 XGetClassHint(dpy, c->win, &ch);
1230 snprintf(buf, sizeof buf, "%s:%s:%s",
1231 ch.res_class ? ch.res_class : "",
1232 ch.res_name ? ch.res_name : "", c->name);
1233 for(i = 0; i < nrules; i++)
1234 if(regs[i].propregex && !regexec(regs[i].propregex, buf, 1, &tmp, 0)) {
1235 c->isfloating = rules[i].isfloating;
1236 for(j = 0; regs[i].tagregex && j < ntags; j++) {
1237 if(!regexec(regs[i].tagregex, tags[j], 1, &tmp, 0)) {
1244 XFree(ch.res_class);
1248 for(i = 0; i < ntags; i++)
1249 c->tags[i] = seltags[i];
1259 nrules = sizeof rules / sizeof rules[0];
1260 regs = emallocz(nrules * sizeof(Regs));
1261 for(i = 0; i < nrules; i++) {
1263 reg = emallocz(sizeof(regex_t));
1264 if(regcomp(reg, rules[i].prop, REG_EXTENDED))
1267 regs[i].propregex = reg;
1270 reg = emallocz(sizeof(regex_t));
1271 if(regcomp(reg, rules[i].tags, REG_EXTENDED))
1274 regs[i].tagregex = reg;
1280 focusnext(const char *arg) {
1285 for(c = sel->next; c && !isvisible(c); c = c->next);
1287 for(c = clients; c && !isvisible(c); c = c->next);
1295 focusprev(const char *arg) {
1300 for(c = sel->prev; c && !isvisible(c); c = c->prev);
1302 for(c = clients; c && c->next; c = c->next);
1303 for(; c && !isvisible(c); c = c->prev);
1315 nlayouts = sizeof layouts / sizeof layouts[0];
1316 for(blw = i = 0; i < nlayouts; i++) {
1317 w = textw(layouts[i].symbol);
1325 return layouts[ltidx].arrange == floating;
1329 isvisible(Client *c) {
1332 for(i = 0; i < ntags; i++)
1333 if(c->tags[i] && seltags[i])
1347 if(sel->isfloating || isfloating())
1348 XRaiseWindow(dpy, sel->win);
1350 wc.stack_mode = Below;
1351 wc.sibling = barwin;
1352 if(!sel->isfloating) {
1353 XConfigureWindow(dpy, sel->win, CWSibling | CWStackMode, &wc);
1354 wc.sibling = sel->win;
1356 for(c = nexttiled(clients); c; c = nexttiled(c->next)) {
1359 XConfigureWindow(dpy, c->win, CWSibling | CWStackMode, &wc);
1360 wc.sibling = c->win;
1364 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1368 setlayout(const char *arg) {
1372 if(++ltidx == nlayouts)
1376 for(i = 0; i < nlayouts; i++)
1377 if(!strcmp(arg, layouts[i].symbol))
1390 tag(const char *arg) {
1395 for(i = 0; i < ntags; i++)
1396 sel->tags[i] = arg == NULL;
1398 if(i >= 0 && i < ntags)
1399 sel->tags[i] = True;
1404 togglefloating(const char *arg) {
1407 sel->isfloating = !sel->isfloating;
1409 resize(sel, sel->x, sel->y, sel->w, sel->h, True);
1414 togglemax(const char *arg) {
1417 if(!sel || (!isfloating() && !sel->isfloating) || sel->isfixed)
1419 if((sel->ismax = !sel->ismax)) {
1424 resize(sel, wax, way, waw - 2 * sel->border, wah - 2 * sel->border, True);
1427 resize(sel, sel->rx, sel->ry, sel->rw, sel->rh, True);
1429 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1433 toggletag(const char *arg) {
1439 sel->tags[i] = !sel->tags[i];
1440 for(j = 0; j < ntags && !sel->tags[j]; j++);
1442 sel->tags[i] = True;
1447 toggleview(const char *arg) {
1451 seltags[i] = !seltags[i];
1452 for(j = 0; j < ntags && !seltags[j]; j++);
1454 seltags[i] = True; /* cannot toggle last view */
1459 view(const char *arg) {
1462 for(i = 0; i < ntags; i++)
1463 seltags[i] = arg == NULL;
1465 if(i >= 0 && i < ntags)
1472 close(STDIN_FILENO);
1478 XFreeFontSet(dpy, dc.font.set);
1480 XFreeFont(dpy, dc.font.xfont);
1481 XUngrabKey(dpy, AnyKey, AnyModifier, root);
1482 XFreePixmap(dpy, dc.drawable);
1483 XFreeGC(dpy, dc.gc);
1484 XDestroyWindow(dpy, barwin);
1485 XFreeCursor(dpy, cursor[CurNormal]);
1486 XFreeCursor(dpy, cursor[CurResize]);
1487 XFreeCursor(dpy, cursor[CurMove]);
1488 XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime);
1494 getstate(Window w) {
1497 unsigned char *p = NULL;
1498 unsigned long n, extra;
1501 status = XGetWindowProperty(dpy, w, wmatom[WMState], 0L, 2L, False, wmatom[WMState],
1502 &real, &format, &n, &extra, (unsigned char **)&p);
1503 if(status != Success)
1513 unsigned int i, num;
1514 Window *wins, d1, d2;
1515 XWindowAttributes wa;
1518 if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1519 for(i = 0; i < num; i++) {
1520 if(!XGetWindowAttributes(dpy, wins[i], &wa)
1521 || wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1523 if(wa.map_state == IsViewable || getstate(wins[i]) == IconicState)
1524 manage(wins[i], &wa);
1526 for(i = 0; i < num; i++) { /* now the transients */
1527 if(!XGetWindowAttributes(dpy, wins[i], &wa))
1529 if(XGetTransientForHint(dpy, wins[i], &d1)
1530 && (wa.map_state == IsViewable || getstate(wins[i]) == IconicState))
1531 manage(wins[i], &wa);
1543 XModifierKeymap *modmap;
1544 XSetWindowAttributes wa;
1547 wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1548 wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1549 wmatom[WMName] = XInternAtom(dpy, "WM_NAME", False);
1550 wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1551 netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1552 netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1553 XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1554 PropModeReplace, (unsigned char *) netatom, NetLast);
1556 cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1557 cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1558 cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1559 /* init modifier map */
1560 modmap = XGetModifierMapping(dpy);
1561 for (i = 0; i < 8; i++)
1562 for (j = 0; j < modmap->max_keypermod; j++) {
1563 if(modmap->modifiermap[i * modmap->max_keypermod + j]
1564 == XKeysymToKeycode(dpy, XK_Num_Lock))
1565 numlockmask = (1 << i);
1567 XFreeModifiermap(modmap);
1568 /* select for events */
1569 wa.event_mask = SubstructureRedirectMask | SubstructureNotifyMask
1570 | EnterWindowMask | LeaveWindowMask | StructureNotifyMask;
1571 wa.cursor = cursor[CurNormal];
1572 XChangeWindowAttributes(dpy, root, CWEventMask | CWCursor, &wa);
1573 XSelectInput(dpy, root, wa.event_mask);
1574 keypress(NULL); /* grabkeys */
1576 for(ntags = 0; tags[ntags]; ntags++);
1577 seltags = emallocz(sizeof(Bool) * ntags);
1581 sw = DisplayWidth(dpy, screen);
1582 sh = DisplayHeight(dpy, screen);
1586 /* multihead support */
1587 selscreen = XQueryPointer(dpy, root, &w, &w, &i, &i, &i, &i, &mask);
1591 * Startup Error handler to check if another window manager
1592 * is already running.
1595 xerrorstart(Display *dsply, XErrorEvent *ee) {
1601 gettextprop(Window w, Atom atom, char *text, unsigned int size) {
1606 if(!text || size == 0)
1609 XGetTextProperty(dpy, w, &name, atom);
1612 if(name.encoding == XA_STRING)
1613 strncpy(text, (char *)name.value, size - 1);
1615 if(XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success
1618 strncpy(text, *list, size - 1);
1619 XFreeStringList(list);
1622 text[size - 1] = '\0';
1628 quit(const char *arg) {
1629 readin = running = False;
1632 /* There's no way to check accesses to destroyed windows, thus those cases are
1633 * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
1634 * default error handler, which may call exit.
1637 xerror(Display *dpy, XErrorEvent *ee) {
1638 if(ee->error_code == BadWindow
1639 || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1640 || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1641 || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1642 || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1643 || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1644 || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1645 || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1647 fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1648 ee->request_code, ee->error_code);
1649 return xerrorxlib(dpy, ee); /* may call exit */
1656 for(c = clients; c; c = c->next)
1661 layouts[ltidx].arrange();
1677 c->prev->next = c->next;
1679 c->next->prev = c->prev;
1682 c->next = c->prev = NULL;
1687 if((!c && selscreen) || (c && !isvisible(c)))
1688 for(c = stack; c && !isvisible(c); c = c->snext);
1689 if(sel && sel != c) {
1690 grabbuttons(sel, False);
1691 XSetWindowBorder(dpy, sel->win, dc.norm[ColBorder]);
1696 grabbuttons(c, True);
1703 XSetWindowBorder(dpy, c->win, dc.sel[ColBorder]);
1704 XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
1707 XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
1711 isarrange(void (*func)())
1713 return func == layouts[ltidx].arrange;
1717 nexttiled(Client *c) {
1718 for(; c && (c->isfloating || !isvisible(c)); c = c->next);
1723 setmwfact(const char *arg) {
1726 if(!isarrange(tile))
1728 /* arg handling, manipulate mwfact */
1731 else if(1 == sscanf(arg, "%lf", &delta)) {
1732 if(arg[0] != '+' && arg[0] != '-')
1738 else if(mwfact > 0.9)
1746 unsigned int i, n, nx, ny, nw, nh, mw, th;
1749 for(n = 0, c = nexttiled(clients); c; c = nexttiled(c->next))
1753 mw = (n == 1) ? waw : mwfact * waw;
1754 th = (n > 1) ? wah / (n - 1) : 0;
1755 if(n > 1 && th < bh)
1760 for(i = 0, c = nexttiled(clients); c; c = nexttiled(c->next), i++) {
1762 if(i == 0) { /* master */
1763 nw = mw - 2 * c->border;
1764 nh = wah - 2 * c->border;
1766 else { /* tile window */
1771 nw = waw - mw - 2 * c->border;
1772 if(i + 1 == n) /* remainder */
1773 nh = (way + wah) - ny - 2 * c->border;
1775 nh = th - 2 * c->border;
1777 resize(c, nx, ny, nw, nh, RESIZEHINTS);
1778 if(n > 1 && th != wah)
1779 ny += nh + 2 * c->border;
1784 zoom(const char *arg) {
1787 if(!sel || !isarrange(tile) || sel->isfloating)
1789 if((c = sel) == nexttiled(clients))
1790 if(!(c = nexttiled(c->next)))
1799 main(int argc, char *argv[]) {
1805 if(argc == 2 && !strcmp("-v", argv[1]))
1806 eprint("dwm-"VERSION", © 2006-2007 A. R. Garbe, S. van Dijk, J. Salmi, P. Hruby, S. Nagy\n");
1808 eprint("usage: dwm [-v]\n");
1809 setlocale(LC_CTYPE, "");
1810 if(!(dpy = XOpenDisplay(0)))
1811 eprint("dwm: cannot open display\n");
1812 xfd = ConnectionNumber(dpy);
1813 screen = DefaultScreen(dpy);
1814 root = RootWindow(dpy, screen);
1816 XSetErrorHandler(xerrorstart);
1817 /* this causes an error if some other window manager is running */
1818 XSelectInput(dpy, root, SubstructureRedirectMask);
1821 eprint("dwm: another window manager is already running\n");
1824 XSetErrorHandler(NULL);
1825 xerrorxlib = XSetErrorHandler(xerror);
1831 /* main event loop, also reads status text from stdin */
1837 FD_SET(STDIN_FILENO, &rd);
1839 if(select(xfd + 1, &rd, NULL, NULL, NULL) == -1) {
1842 eprint("select failed\n");
1844 if(FD_ISSET(STDIN_FILENO, &rd)) {
1845 switch(r = read(STDIN_FILENO, stext, sizeof stext - 1)) {
1847 strncpy(stext, strerror(errno), sizeof stext - 1);
1848 stext[sizeof stext - 1] = '\0';
1852 strncpy(stext, "EOF", 4);
1856 for(stext[r] = '\0', p = stext + strlen(stext) - 1; p >= stext && *p == '\n'; *p-- = '\0');
1857 for(; p >= stext && *p != '\n'; --p);
1859 strncpy(stext, p + 1, sizeof stext);
1863 while(XPending(dpy)) {
1864 XNextEvent(dpy, &ev);
1865 if(handler[ev.type])
1866 (handler[ev.type])(&ev); /* call handler */