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 config.h.
26 * To understand everything else, start reading main().
35 #include <sys/select.h>
36 #include <sys/types.h>
39 #include <X11/cursorfont.h>
40 #include <X11/keysym.h>
41 #include <X11/Xatom.h>
43 #include <X11/Xproto.h>
44 #include <X11/Xutil.h>
47 #define BUTTONMASK (ButtonPressMask | ButtonReleaseMask)
48 #define CLEANMASK(mask) (mask & ~(numlockmask | LockMask))
49 #define MOUSEMASK (BUTTONMASK | PointerMotionMask)
52 enum { BarTop, BarBot, BarOff }; /* bar position */
53 enum { CurNormal, CurResize, CurMove, CurLast }; /* cursor */
54 enum { ColBorder, ColFG, ColBG, ColLast }; /* color */
55 enum { NetSupported, NetWMName, NetLast }; /* EWMH atoms */
56 enum { WMProtocols, WMDelete, WMName, WMState, WMLast };/* default atoms */
59 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, wasfloating;
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 void applyrules(Client *c);
118 void attach(Client *c);
119 void attachstack(Client *c);
121 void buttonpress(XEvent *e);
122 void checkotherwm(void);
124 void compileregs(void);
125 void configure(Client *c);
126 void configurenotify(XEvent *e);
127 void configurerequest(XEvent *e);
128 void destroynotify(XEvent *e);
129 void detach(Client *c);
130 void detachstack(Client *c);
132 void drawsquare(Bool filled, Bool empty, unsigned long col[ColLast]);
133 void drawtext(const char *text, unsigned long col[ColLast]);
134 void *emallocz(unsigned int size);
135 void enternotify(XEvent *e);
136 void eprint(const char *errstr, ...);
137 void expose(XEvent *e);
138 void floating(void); /* default floating layout */
139 void focus(Client *c);
140 void focusnext(const char *arg);
141 void focusprev(const char *arg);
142 Client *getclient(Window w);
143 unsigned long getcolor(const char *colstr);
144 long getstate(Window w);
145 Bool gettextprop(Window w, Atom atom, char *text, unsigned int size);
146 void grabbuttons(Client *c, Bool focused);
147 unsigned int idxoftag(const char *tag);
148 void initfont(const char *fontstr);
149 Bool isarrange(void (*func)());
150 Bool isoccupied(unsigned int t);
151 Bool isprotodel(Client *c);
152 Bool isvisible(Client *c);
153 void keypress(XEvent *e);
154 void killclient(const char *arg);
155 void leavenotify(XEvent *e);
156 void manage(Window w, XWindowAttributes *wa);
157 void mappingnotify(XEvent *e);
158 void maprequest(XEvent *e);
159 void movemouse(Client *c);
160 Client *nexttiled(Client *c);
161 void propertynotify(XEvent *e);
162 void quit(const char *arg);
163 void resize(Client *c, int x, int y, int w, int h, Bool sizehints);
164 void resizemouse(Client *c);
168 void setclientstate(Client *c, long state);
169 void setlayout(const char *arg);
170 void setmwfact(const char *arg);
172 void spawn(const char *arg);
173 void tag(const char *arg);
174 unsigned int textnw(const char *text, unsigned int len);
175 unsigned int textw(const char *text);
177 void togglebar(const char *arg);
178 void togglefloating(const char *arg);
179 void togglemax(const char *arg);
180 void toggletag(const char *arg);
181 void toggleview(const char *arg);
182 void unban(Client *c);
183 void unmanage(Client *c);
184 void unmapnotify(XEvent *e);
185 void updatebarpos(void);
186 void updatesizehints(Client *c);
187 void updatetitle(Client *c);
188 void view(const char *arg);
189 void viewprevtag(const char *arg); /* views previous selected tags */
190 int xerror(Display *dpy, XErrorEvent *ee);
191 int xerrordummy(Display *dsply, XErrorEvent *ee);
192 int xerrorstart(Display *dsply, XErrorEvent *ee);
193 void zoom(const char *arg);
198 int screen, sx, sy, sw, sh, wax, way, waw, wah;
199 int (*xerrorxlib)(Display *, XErrorEvent *);
200 unsigned int bh, bpos;
201 unsigned int blw = 0;
202 unsigned int ltidx = 0; /* default */
203 unsigned int nlayouts = 0;
204 unsigned int nrules = 0;
205 unsigned int numlockmask = 0;
206 void (*handler[LASTEvent]) (XEvent *) = {
207 [ButtonPress] = buttonpress,
208 [ConfigureRequest] = configurerequest,
209 [ConfigureNotify] = configurenotify,
210 [DestroyNotify] = destroynotify,
211 [EnterNotify] = enternotify,
212 [LeaveNotify] = leavenotify,
214 [KeyPress] = keypress,
215 [MappingNotify] = mappingnotify,
216 [MapRequest] = maprequest,
217 [PropertyNotify] = propertynotify,
218 [UnmapNotify] = unmapnotify
220 Atom wmatom[WMLast], netatom[NetLast];
221 Bool otherwm, readin;
223 Bool selscreen = True;
224 Client *clients = NULL;
226 Client *stack = NULL;
227 Cursor cursor[CurLast];
233 /* configuration, allows nested code to access above variables */
236 /* Statically define the number of tags. */
237 unsigned int ntags = sizeof tags / sizeof tags[0];
238 Bool seltags[sizeof tags / sizeof tags[0]] = {[0] = True};
239 Bool prevtags[sizeof tags / sizeof tags[0]] = {[0] = True};
243 applyrules(Client *c) {
244 static char buf[512];
247 Bool matched = False;
248 XClassHint ch = { 0 };
251 XGetClassHint(dpy, c->win, &ch);
252 snprintf(buf, sizeof buf, "%s:%s:%s",
253 ch.res_class ? ch.res_class : "",
254 ch.res_name ? ch.res_name : "", c->name);
255 for(i = 0; i < nrules; i++)
256 if(regs[i].propregex && !regexec(regs[i].propregex, buf, 1, &tmp, 0)) {
257 c->isfloating = rules[i].isfloating;
258 for(j = 0; regs[i].tagregex && j < ntags; j++) {
259 if(!regexec(regs[i].tagregex, tags[j], 1, &tmp, 0)) {
270 memcpy(c->tags, seltags, sizeof seltags);
277 for(c = clients; c; c = c->next)
282 layouts[ltidx].arrange();
296 attachstack(Client *c) {
305 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
310 buttonpress(XEvent *e) {
313 XButtonPressedEvent *ev = &e->xbutton;
315 if(barwin == ev->window) {
317 for(i = 0; i < ntags; i++) {
320 if(ev->button == Button1) {
321 if(ev->state & MODKEY)
326 else if(ev->button == Button3) {
327 if(ev->state & MODKEY)
335 if((ev->x < x + blw) && ev->button == Button1)
338 else if((c = getclient(ev->window))) {
340 if(CLEANMASK(ev->state) != MODKEY)
342 if(ev->button == Button1) {
343 if(isarrange(floating) || c->isfloating)
346 togglefloating(NULL);
349 else if(ev->button == Button2) {
350 if(ISTILE && !c->isfixed && c->isfloating)
351 togglefloating(NULL);
355 else if(ev->button == Button3 && !c->isfixed) {
356 if(isarrange(floating) || c->isfloating)
359 togglefloating(NULL);
368 XSetErrorHandler(xerrorstart);
370 /* this causes an error if some other window manager is running */
371 XSelectInput(dpy, root, SubstructureRedirectMask);
374 eprint("dwm: another window manager is already running\n");
376 XSetErrorHandler(NULL);
377 xerrorxlib = XSetErrorHandler(xerror);
389 XFreeFontSet(dpy, dc.font.set);
391 XFreeFont(dpy, dc.font.xfont);
392 XUngrabKey(dpy, AnyKey, AnyModifier, root);
393 XFreePixmap(dpy, dc.drawable);
395 XDestroyWindow(dpy, barwin);
396 XFreeCursor(dpy, cursor[CurNormal]);
397 XFreeCursor(dpy, cursor[CurResize]);
398 XFreeCursor(dpy, cursor[CurMove]);
399 XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime);
410 nrules = sizeof rules / sizeof rules[0];
411 regs = emallocz(nrules * sizeof(Regs));
412 for(i = 0; i < nrules; i++) {
414 reg = emallocz(sizeof(regex_t));
415 if(regcomp(reg, rules[i].prop, REG_EXTENDED))
418 regs[i].propregex = reg;
421 reg = emallocz(sizeof(regex_t));
422 if(regcomp(reg, rules[i].tags, REG_EXTENDED))
425 regs[i].tagregex = reg;
431 configure(Client *c) {
434 ce.type = ConfigureNotify;
442 ce.border_width = c->border;
444 ce.override_redirect = False;
445 XSendEvent(dpy, c->win, False, StructureNotifyMask, (XEvent *)&ce);
449 configurenotify(XEvent *e) {
450 XConfigureEvent *ev = &e->xconfigure;
452 if(ev->window == root && (ev->width != sw || ev->height != sh)) {
455 XFreePixmap(dpy, dc.drawable);
456 dc.drawable = XCreatePixmap(dpy, root, sw, bh, DefaultDepth(dpy, screen));
457 XResizeWindow(dpy, barwin, sw, bh);
464 configurerequest(XEvent *e) {
466 XConfigureRequestEvent *ev = &e->xconfigurerequest;
469 if((c = getclient(ev->window))) {
471 if(ev->value_mask & CWBorderWidth)
472 c->border = ev->border_width;
473 if(c->isfixed || c->isfloating || isarrange(floating)) {
474 if(ev->value_mask & CWX)
476 if(ev->value_mask & CWY)
478 if(ev->value_mask & CWWidth)
480 if(ev->value_mask & CWHeight)
482 if((c->x + c->w) > sw && c->isfloating)
483 c->x = sw / 2 - c->w / 2; /* center in x direction */
484 if((c->y + c->h) > sh && c->isfloating)
485 c->y = sh / 2 - c->h / 2; /* center in y direction */
486 if((ev->value_mask & (CWX | CWY))
487 && !(ev->value_mask & (CWWidth | CWHeight)))
490 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h);
498 wc.width = ev->width;
499 wc.height = ev->height;
500 wc.border_width = ev->border_width;
501 wc.sibling = ev->above;
502 wc.stack_mode = ev->detail;
503 XConfigureWindow(dpy, ev->window, ev->value_mask, &wc);
509 destroynotify(XEvent *e) {
511 XDestroyWindowEvent *ev = &e->xdestroywindow;
513 if((c = getclient(ev->window)))
520 c->prev->next = c->next;
522 c->next->prev = c->prev;
525 c->next = c->prev = NULL;
529 detachstack(Client *c) {
532 for(tc=&stack; *tc && *tc != c; tc=&(*tc)->snext);
541 for(i = 0; i < ntags; i++) {
542 dc.w = textw(tags[i]);
544 drawtext(tags[i], dc.sel);
545 drawsquare(sel && sel->tags[i], isoccupied(i), dc.sel);
548 drawtext(tags[i], dc.norm);
549 drawsquare(sel && sel->tags[i], isoccupied(i), dc.norm);
554 drawtext(layouts[ltidx].symbol, dc.norm);
562 drawtext(stext, dc.norm);
563 if((dc.w = dc.x - x) > bh) {
566 drawtext(sel->name, dc.sel);
567 drawsquare(sel->ismax, sel->isfloating, dc.sel);
570 drawtext(NULL, dc.norm);
572 XCopyArea(dpy, dc.drawable, barwin, dc.gc, 0, 0, sw, bh, 0, 0);
577 drawsquare(Bool filled, Bool empty, unsigned long col[ColLast]) {
580 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
582 gcv.foreground = col[ColFG];
583 XChangeGC(dpy, dc.gc, GCForeground, &gcv);
584 x = (dc.font.ascent + dc.font.descent + 2) / 4;
588 r.width = r.height = x + 1;
589 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
592 r.width = r.height = x;
593 XDrawRectangles(dpy, dc.drawable, dc.gc, &r, 1);
598 drawtext(const char *text, unsigned long col[ColLast]) {
600 static char buf[256];
601 unsigned int len, olen;
602 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
604 XSetForeground(dpy, dc.gc, col[ColBG]);
605 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
609 olen = len = strlen(text);
610 if(len >= sizeof buf)
611 len = sizeof buf - 1;
612 memcpy(buf, text, len);
614 h = dc.font.ascent + dc.font.descent;
615 y = dc.y + (dc.h / 2) - (h / 2) + dc.font.ascent;
617 /* shorten text if necessary */
618 while(len && (w = textnw(buf, len)) > dc.w - h)
629 return; /* too long */
630 XSetForeground(dpy, dc.gc, col[ColFG]);
632 XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
634 XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
638 emallocz(unsigned int size) {
639 void *res = calloc(1, size);
642 eprint("fatal: could not malloc() %u bytes\n", size);
647 enternotify(XEvent *e) {
649 XCrossingEvent *ev = &e->xcrossing;
651 if(ev->mode != NotifyNormal || ev->detail == NotifyInferior)
653 if((c = getclient(ev->window)))
655 else if(ev->window == root) {
662 eprint(const char *errstr, ...) {
665 va_start(ap, errstr);
666 vfprintf(stderr, errstr, ap);
673 XExposeEvent *ev = &e->xexpose;
676 if(barwin == ev->window)
682 floating(void) { /* default floating layout */
685 for(c = clients; c; c = c->next)
687 resize(c, c->x, c->y, c->w, c->h, True);
692 if((!c && selscreen) || (c && !isvisible(c)))
693 for(c = stack; c && !isvisible(c); c = c->snext);
694 if(sel && sel != c) {
695 grabbuttons(sel, False);
696 XSetWindowBorder(dpy, sel->win, dc.norm[ColBorder]);
701 grabbuttons(c, True);
708 XSetWindowBorder(dpy, c->win, dc.sel[ColBorder]);
709 XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
712 XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
716 focusnext(const char *arg) {
721 for(c = sel->next; c && !isvisible(c); c = c->next);
723 for(c = clients; c && !isvisible(c); c = c->next);
731 focusprev(const char *arg) {
736 for(c = sel->prev; c && !isvisible(c); c = c->prev);
738 for(c = clients; c && c->next; c = c->next);
739 for(; c && !isvisible(c); c = c->prev);
748 getclient(Window w) {
751 for(c = clients; c && c->win != w; c = c->next);
756 getcolor(const char *colstr) {
757 Colormap cmap = DefaultColormap(dpy, screen);
760 if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
761 eprint("error, cannot allocate color '%s'\n", colstr);
769 unsigned char *p = NULL;
770 unsigned long n, extra;
773 status = XGetWindowProperty(dpy, w, wmatom[WMState], 0L, 2L, False, wmatom[WMState],
774 &real, &format, &n, &extra, (unsigned char **)&p);
775 if(status != Success)
784 gettextprop(Window w, Atom atom, char *text, unsigned int size) {
789 if(!text || size == 0)
792 XGetTextProperty(dpy, w, &name, atom);
795 if(name.encoding == XA_STRING)
796 strncpy(text, (char *)name.value, size - 1);
798 if(XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success
801 strncpy(text, *list, size - 1);
802 XFreeStringList(list);
805 text[size - 1] = '\0';
811 grabbuttons(Client *c, Bool focused) {
812 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
815 XGrabButton(dpy, Button1, MODKEY, c->win, False, BUTTONMASK,
816 GrabModeAsync, GrabModeSync, None, None);
817 XGrabButton(dpy, Button1, MODKEY | LockMask, c->win, False, BUTTONMASK,
818 GrabModeAsync, GrabModeSync, None, None);
819 XGrabButton(dpy, Button1, MODKEY | numlockmask, c->win, False, BUTTONMASK,
820 GrabModeAsync, GrabModeSync, None, None);
821 XGrabButton(dpy, Button1, MODKEY | numlockmask | LockMask, c->win, False, BUTTONMASK,
822 GrabModeAsync, GrabModeSync, None, None);
824 XGrabButton(dpy, Button2, MODKEY, c->win, False, BUTTONMASK,
825 GrabModeAsync, GrabModeSync, None, None);
826 XGrabButton(dpy, Button2, MODKEY | LockMask, c->win, False, BUTTONMASK,
827 GrabModeAsync, GrabModeSync, None, None);
828 XGrabButton(dpy, Button2, MODKEY | numlockmask, c->win, False, BUTTONMASK,
829 GrabModeAsync, GrabModeSync, None, None);
830 XGrabButton(dpy, Button2, MODKEY | numlockmask | LockMask, c->win, False, BUTTONMASK,
831 GrabModeAsync, GrabModeSync, None, None);
833 XGrabButton(dpy, Button3, MODKEY, c->win, False, BUTTONMASK,
834 GrabModeAsync, GrabModeSync, None, None);
835 XGrabButton(dpy, Button3, MODKEY | LockMask, c->win, False, BUTTONMASK,
836 GrabModeAsync, GrabModeSync, None, None);
837 XGrabButton(dpy, Button3, MODKEY | numlockmask, c->win, False, BUTTONMASK,
838 GrabModeAsync, GrabModeSync, None, None);
839 XGrabButton(dpy, Button3, MODKEY | numlockmask | LockMask, c->win, False, BUTTONMASK,
840 GrabModeAsync, GrabModeSync, None, None);
843 XGrabButton(dpy, AnyButton, AnyModifier, c->win, False, BUTTONMASK,
844 GrabModeAsync, GrabModeSync, None, None);
848 idxoftag(const char *tag) {
851 for(i = 0; i < ntags; i++)
858 initfont(const char *fontstr) {
859 char *def, **missing;
864 XFreeFontSet(dpy, dc.font.set);
865 dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
868 fprintf(stderr, "dwm: missing fontset: %s\n", missing[n]);
869 XFreeStringList(missing);
872 XFontSetExtents *font_extents;
873 XFontStruct **xfonts;
875 dc.font.ascent = dc.font.descent = 0;
876 font_extents = XExtentsOfFontSet(dc.font.set);
877 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
878 for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
879 if(dc.font.ascent < (*xfonts)->ascent)
880 dc.font.ascent = (*xfonts)->ascent;
881 if(dc.font.descent < (*xfonts)->descent)
882 dc.font.descent = (*xfonts)->descent;
888 XFreeFont(dpy, dc.font.xfont);
889 dc.font.xfont = NULL;
890 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr))
891 && !(dc.font.xfont = XLoadQueryFont(dpy, "fixed")))
892 eprint("error, cannot load font: '%s'\n", fontstr);
893 dc.font.ascent = dc.font.xfont->ascent;
894 dc.font.descent = dc.font.xfont->descent;
896 dc.font.height = dc.font.ascent + dc.font.descent;
900 isarrange(void (*func)())
902 return func == layouts[ltidx].arrange;
906 isoccupied(unsigned int t) {
909 for(c = clients; c; c = c->next)
916 isprotodel(Client *c) {
921 if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
922 for(i = 0; !ret && i < n; i++)
923 if(protocols[i] == wmatom[WMDelete])
931 isvisible(Client *c) {
934 for(i = 0; i < ntags; i++)
935 if(c->tags[i] && seltags[i])
941 keypress(XEvent *e) {
943 unsigned int len = sizeof keys / sizeof keys[0];
949 if(!e) { /* grabkeys */
950 XUngrabKey(dpy, AnyKey, AnyModifier, root);
951 for(i = 0; i < len; i++) {
952 code = XKeysymToKeycode(dpy, keys[i].keysym);
953 XGrabKey(dpy, code, keys[i].mod, root, True,
954 GrabModeAsync, GrabModeAsync);
955 XGrabKey(dpy, code, keys[i].mod | LockMask, root, True,
956 GrabModeAsync, GrabModeAsync);
957 XGrabKey(dpy, code, keys[i].mod | numlockmask, root, True,
958 GrabModeAsync, GrabModeAsync);
959 XGrabKey(dpy, code, keys[i].mod | numlockmask | LockMask, root, True,
960 GrabModeAsync, GrabModeAsync);
965 keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
966 for(i = 0; i < len; i++)
967 if(keysym == keys[i].keysym
968 && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state))
971 keys[i].func(keys[i].arg);
976 killclient(const char *arg) {
981 if(isprotodel(sel)) {
982 ev.type = ClientMessage;
983 ev.xclient.window = sel->win;
984 ev.xclient.message_type = wmatom[WMProtocols];
985 ev.xclient.format = 32;
986 ev.xclient.data.l[0] = wmatom[WMDelete];
987 ev.xclient.data.l[1] = CurrentTime;
988 XSendEvent(dpy, sel->win, False, NoEventMask, &ev);
991 XKillClient(dpy, sel->win);
995 leavenotify(XEvent *e) {
996 XCrossingEvent *ev = &e->xcrossing;
998 if((ev->window == root) && !ev->same_screen) {
1005 manage(Window w, XWindowAttributes *wa) {
1006 Client *c, *t = NULL;
1011 c = emallocz(sizeof(Client));
1012 c->tags = emallocz(sizeof seltags);
1018 c->oldborder = wa->border_width;
1019 if(c->w == sw && c->h == sh) {
1022 c->border = wa->border_width;
1025 if(c->x + c->w + 2 * c->border > wax + waw)
1026 c->x = wax + waw - c->w - 2 * c->border;
1027 if(c->y + c->h + 2 * c->border > way + wah)
1028 c->y = way + wah - c->h - 2 * c->border;
1033 c->border = BORDERPX;
1035 wc.border_width = c->border;
1036 XConfigureWindow(dpy, w, CWBorderWidth, &wc);
1037 XSetWindowBorder(dpy, w, dc.norm[ColBorder]);
1038 configure(c); /* propagates border_width, if size doesn't change */
1040 XSelectInput(dpy, w,
1041 StructureNotifyMask | PropertyChangeMask | EnterWindowMask);
1042 grabbuttons(c, False);
1044 if((rettrans = XGetTransientForHint(dpy, w, &trans) == Success))
1045 for(t = clients; t && t->win != trans; t = t->next);
1047 memcpy(c->tags, t->tags, sizeof seltags);
1050 c->isfloating = (rettrans == Success) || c->isfixed;
1053 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h); /* some windows require this */
1055 XMapWindow(dpy, c->win);
1056 setclientstate(c, NormalState);
1061 mappingnotify(XEvent *e) {
1062 XMappingEvent *ev = &e->xmapping;
1064 XRefreshKeyboardMapping(ev);
1065 if(ev->request == MappingKeyboard)
1070 maprequest(XEvent *e) {
1071 static XWindowAttributes wa;
1072 XMapRequestEvent *ev = &e->xmaprequest;
1074 if(!XGetWindowAttributes(dpy, ev->window, &wa))
1076 if(wa.override_redirect)
1078 if(!getclient(ev->window))
1079 manage(ev->window, &wa);
1083 movemouse(Client *c) {
1084 int x1, y1, ocx, ocy, di, nx, ny;
1091 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1092 None, cursor[CurMove], CurrentTime) != GrabSuccess)
1095 XQueryPointer(dpy, root, &dummy, &dummy, &x1, &y1, &di, &di, &dui);
1097 XMaskEvent(dpy, MOUSEMASK | ExposureMask | SubstructureRedirectMask, &ev);
1100 XUngrabPointer(dpy, CurrentTime);
1102 case ConfigureRequest:
1105 handler[ev.type](&ev);
1109 nx = ocx + (ev.xmotion.x - x1);
1110 ny = ocy + (ev.xmotion.y - y1);
1111 if(abs(wax + nx) < SNAP)
1113 else if(abs((wax + waw) - (nx + c->w + 2 * c->border)) < SNAP)
1114 nx = wax + waw - c->w - 2 * c->border;
1115 if(abs(way - ny) < SNAP)
1117 else if(abs((way + wah) - (ny + c->h + 2 * c->border)) < SNAP)
1118 ny = way + wah - c->h - 2 * c->border;
1119 resize(c, nx, ny, c->w, c->h, False);
1126 nexttiled(Client *c) {
1127 for(; c && (c->isfloating || !isvisible(c)); c = c->next);
1132 propertynotify(XEvent *e) {
1135 XPropertyEvent *ev = &e->xproperty;
1137 if(ev->state == PropertyDelete)
1138 return; /* ignore */
1139 if((c = getclient(ev->window))) {
1142 case XA_WM_TRANSIENT_FOR:
1143 XGetTransientForHint(dpy, c->win, &trans);
1144 if(!c->isfloating && (c->isfloating = (getclient(trans) != NULL)))
1147 case XA_WM_NORMAL_HINTS:
1151 if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
1160 quit(const char *arg) {
1161 readin = running = False;
1165 resize(Client *c, int x, int y, int w, int h, Bool sizehints) {
1166 double dx, dy, max, min, ratio;
1170 if(c->minay > 0 && c->maxay > 0 && (h - c->baseh) > 0 && (w - c->basew) > 0) {
1171 dx = (double)(w - c->basew);
1172 dy = (double)(h - c->baseh);
1173 min = (double)(c->minax) / (double)(c->minay);
1174 max = (double)(c->maxax) / (double)(c->maxay);
1176 if(max > 0 && min > 0 && ratio > 0) {
1178 dy = (dx * min + dy) / (min * min + 1);
1180 w = (int)dx + c->basew;
1181 h = (int)dy + c->baseh;
1183 else if(ratio > max) {
1184 dy = (dx * min + dy) / (max * max + 1);
1186 w = (int)dx + c->basew;
1187 h = (int)dy + c->baseh;
1191 if(c->minw && w < c->minw)
1193 if(c->minh && h < c->minh)
1195 if(c->maxw && w > c->maxw)
1197 if(c->maxh && h > c->maxh)
1200 w -= (w - c->basew) % c->incw;
1202 h -= (h - c->baseh) % c->inch;
1204 if(w <= 0 || h <= 0)
1206 /* offscreen appearance fixes */
1208 x = sw - w - 2 * c->border;
1210 y = sh - h - 2 * c->border;
1211 if(x + w + 2 * c->border < sx)
1213 if(y + h + 2 * c->border < sy)
1215 if(c->x != x || c->y != y || c->w != w || c->h != h) {
1218 c->w = wc.width = w;
1219 c->h = wc.height = h;
1220 wc.border_width = c->border;
1221 XConfigureWindow(dpy, c->win, CWX | CWY | CWWidth | CWHeight | CWBorderWidth, &wc);
1228 resizemouse(Client *c) {
1235 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1236 None, cursor[CurResize], CurrentTime) != GrabSuccess)
1239 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->border - 1, c->h + c->border - 1);
1241 XMaskEvent(dpy, MOUSEMASK | ExposureMask | SubstructureRedirectMask , &ev);
1244 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0,
1245 c->w + c->border - 1, c->h + c->border - 1);
1246 XUngrabPointer(dpy, CurrentTime);
1247 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1249 case ConfigureRequest:
1252 handler[ev.type](&ev);
1256 if((nw = ev.xmotion.x - ocx - 2 * c->border + 1) <= 0)
1258 if((nh = ev.xmotion.y - ocy - 2 * c->border + 1) <= 0)
1260 resize(c, c->x, c->y, nw, nh, True);
1275 if(sel->isfloating || isarrange(floating))
1276 XRaiseWindow(dpy, sel->win);
1277 if(!isarrange(floating)) {
1278 wc.stack_mode = Below;
1279 wc.sibling = barwin;
1280 if(!sel->isfloating) {
1281 XConfigureWindow(dpy, sel->win, CWSibling | CWStackMode, &wc);
1282 wc.sibling = sel->win;
1284 for(c = nexttiled(clients); c; c = nexttiled(c->next)) {
1287 XConfigureWindow(dpy, c->win, CWSibling | CWStackMode, &wc);
1288 wc.sibling = c->win;
1292 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1302 /* main event loop, also reads status text from stdin */
1304 xfd = ConnectionNumber(dpy);
1309 FD_SET(STDIN_FILENO, &rd);
1311 if(select(xfd + 1, &rd, NULL, NULL, NULL) == -1) {
1314 eprint("select failed\n");
1316 if(FD_ISSET(STDIN_FILENO, &rd)) {
1317 switch(r = read(STDIN_FILENO, stext, sizeof stext - 1)) {
1319 strncpy(stext, strerror(errno), sizeof stext - 1);
1320 stext[sizeof stext - 1] = '\0';
1324 strncpy(stext, "EOF", 4);
1328 for(stext[r] = '\0', p = stext + strlen(stext) - 1; p >= stext && *p == '\n'; *p-- = '\0');
1329 for(; p >= stext && *p != '\n'; --p);
1331 strncpy(stext, p + 1, sizeof stext);
1335 while(XPending(dpy)) {
1336 XNextEvent(dpy, &ev);
1337 if(handler[ev.type])
1338 (handler[ev.type])(&ev); /* call handler */
1345 unsigned int i, num;
1346 Window *wins, d1, d2;
1347 XWindowAttributes wa;
1350 if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1351 for(i = 0; i < num; i++) {
1352 if(!XGetWindowAttributes(dpy, wins[i], &wa)
1353 || wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1355 if(wa.map_state == IsViewable || getstate(wins[i]) == IconicState)
1356 manage(wins[i], &wa);
1358 for(i = 0; i < num; i++) { /* now the transients */
1359 if(!XGetWindowAttributes(dpy, wins[i], &wa))
1361 if(XGetTransientForHint(dpy, wins[i], &d1)
1362 && (wa.map_state == IsViewable || getstate(wins[i]) == IconicState))
1363 manage(wins[i], &wa);
1371 setclientstate(Client *c, long state) {
1372 long data[] = {state, None};
1374 XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1375 PropModeReplace, (unsigned char *)data, 2);
1379 setlayout(const char *arg) {
1383 if(++ltidx == nlayouts)
1387 for(i = 0; i < nlayouts; i++)
1388 if(!strcmp(arg, layouts[i].symbol))
1401 setmwfact(const char *arg) {
1406 /* arg handling, manipulate mwfact */
1409 else if(1 == sscanf(arg, "%lf", &delta)) {
1410 if(arg[0] == '+' || arg[0] == '-')
1416 else if(mwfact > 0.9)
1425 unsigned int i, j, mask;
1427 XModifierKeymap *modmap;
1428 XSetWindowAttributes wa;
1431 wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1432 wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1433 wmatom[WMName] = XInternAtom(dpy, "WM_NAME", False);
1434 wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1435 netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1436 netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1437 XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1438 PropModeReplace, (unsigned char *) netatom, NetLast);
1441 cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1442 cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1443 cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1447 sw = DisplayWidth(dpy, screen);
1448 sh = DisplayHeight(dpy, screen);
1450 /* init modifier map */
1451 modmap = XGetModifierMapping(dpy);
1452 for(i = 0; i < 8; i++)
1453 for(j = 0; j < modmap->max_keypermod; j++) {
1454 if(modmap->modifiermap[i * modmap->max_keypermod + j]
1455 == XKeysymToKeycode(dpy, XK_Num_Lock))
1456 numlockmask = (1 << i);
1458 XFreeModifiermap(modmap);
1460 /* select for events */
1461 wa.event_mask = SubstructureRedirectMask | SubstructureNotifyMask
1462 | EnterWindowMask | LeaveWindowMask | StructureNotifyMask;
1463 wa.cursor = cursor[CurNormal];
1464 XChangeWindowAttributes(dpy, root, CWEventMask | CWCursor, &wa);
1465 XSelectInput(dpy, root, wa.event_mask);
1473 /* init appearance */
1474 dc.norm[ColBorder] = getcolor(NORMBORDERCOLOR);
1475 dc.norm[ColBG] = getcolor(NORMBGCOLOR);
1476 dc.norm[ColFG] = getcolor(NORMFGCOLOR);
1477 dc.sel[ColBorder] = getcolor(SELBORDERCOLOR);
1478 dc.sel[ColBG] = getcolor(SELBGCOLOR);
1479 dc.sel[ColFG] = getcolor(SELFGCOLOR);
1481 dc.h = bh = dc.font.height + 2;
1485 nlayouts = sizeof layouts / sizeof layouts[0];
1486 for(blw = i = 0; i < nlayouts; i++) {
1487 j = textw(layouts[i].symbol);
1494 wa.override_redirect = 1;
1495 wa.background_pixmap = ParentRelative;
1496 wa.event_mask = ButtonPressMask | ExposureMask;
1497 barwin = XCreateWindow(dpy, root, sx, sy, sw, bh, 0,
1498 DefaultDepth(dpy, screen), CopyFromParent, DefaultVisual(dpy, screen),
1499 CWOverrideRedirect | CWBackPixmap | CWEventMask, &wa);
1500 XDefineCursor(dpy, barwin, cursor[CurNormal]);
1502 XMapRaised(dpy, barwin);
1503 strcpy(stext, "dwm-"VERSION);
1504 dc.drawable = XCreatePixmap(dpy, root, sw, bh, DefaultDepth(dpy, screen));
1505 dc.gc = XCreateGC(dpy, root, 0, 0);
1506 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
1508 XSetFont(dpy, dc.gc, dc.font.xfont->fid);
1510 /* multihead support */
1511 selscreen = XQueryPointer(dpy, root, &w, &w, &d, &d, &d, &d, &mask);
1515 spawn(const char *arg) {
1516 static char *shell = NULL;
1518 if(!shell && !(shell = getenv("SHELL")))
1522 /* The double-fork construct avoids zombie processes and keeps the code
1523 * clean from stupid signal handlers. */
1527 close(ConnectionNumber(dpy));
1529 execl(shell, shell, "-c", arg, (char *)NULL);
1530 fprintf(stderr, "dwm: execl '%s -c %s'", shell, arg);
1539 tag(const char *arg) {
1544 for(i = 0; i < ntags; i++)
1545 sel->tags[i] = arg == NULL;
1547 if(i >= 0 && i < ntags)
1548 sel->tags[i] = True;
1553 textnw(const char *text, unsigned int len) {
1557 XmbTextExtents(dc.font.set, text, len, NULL, &r);
1560 return XTextWidth(dc.font.xfont, text, len);
1564 textw(const char *text) {
1565 return textnw(text, strlen(text)) + dc.font.height;
1570 unsigned int i, n, nx, ny, nw, nh, mw, th;
1573 for(n = 0, c = nexttiled(clients); c; c = nexttiled(c->next))
1577 mw = (n == 1) ? waw : mwfact * waw;
1578 th = (n > 1) ? wah / (n - 1) : 0;
1579 if(n > 1 && th < bh)
1584 nw = 0; /* gcc stupidity requires this */
1585 for(i = 0, c = mc = nexttiled(clients); c; c = nexttiled(c->next), i++) {
1587 if(i == 0) { /* master */
1588 nw = mw - 2 * c->border;
1589 nh = wah - 2 * c->border;
1591 else { /* tile window */
1594 nx += mc->w + 2 * mc->border;
1595 nw = waw - nx - 2 * c->border;
1597 if(i + 1 == n) /* remainder */
1598 nh = (way + wah) - ny - 2 * c->border;
1600 nh = th - 2 * c->border;
1602 resize(c, nx, ny, nw, nh, RESIZEHINTS);
1603 if(n > 1 && th != wah)
1604 ny = c->y + c->h + 2 * c->border;
1609 togglebar(const char *arg) {
1611 bpos = (BARPOS == BarOff) ? BarTop : BARPOS;
1619 togglefloating(const char *arg) {
1622 sel->isfloating = !sel->isfloating;
1624 resize(sel, sel->x, sel->y, sel->w, sel->h, True);
1629 togglemax(const char *arg) {
1632 if(!sel || sel->isfixed)
1634 if((sel->ismax = !sel->ismax)) {
1635 if(isarrange(floating) || sel->isfloating)
1636 sel->wasfloating = True;
1638 togglefloating(NULL);
1639 sel->wasfloating = False;
1645 resize(sel, wax, way, waw - 2 * sel->border, wah - 2 * sel->border, True);
1648 resize(sel, sel->rx, sel->ry, sel->rw, sel->rh, True);
1649 if(!sel->wasfloating)
1650 togglefloating(NULL);
1653 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1657 toggletag(const char *arg) {
1663 sel->tags[i] = !sel->tags[i];
1664 for(j = 0; j < ntags && !sel->tags[j]; j++);
1666 sel->tags[i] = True;
1671 toggleview(const char *arg) {
1675 seltags[i] = !seltags[i];
1676 for(j = 0; j < ntags && !seltags[j]; j++);
1678 seltags[i] = True; /* at least one tag must be viewed */
1686 XMoveWindow(dpy, c->win, c->x, c->y);
1687 c->isbanned = False;
1691 unmanage(Client *c) {
1694 wc.border_width = c->oldborder;
1695 /* The server grab construct avoids race conditions. */
1697 XSetErrorHandler(xerrordummy);
1698 XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
1703 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1704 setclientstate(c, WithdrawnState);
1708 XSetErrorHandler(xerror);
1714 unmapnotify(XEvent *e) {
1716 XUnmapEvent *ev = &e->xunmap;
1718 if((c = getclient(ev->window)))
1723 updatebarpos(void) {
1734 XMoveWindow(dpy, barwin, sx, sy);
1738 XMoveWindow(dpy, barwin, sx, sy + wah);
1741 XMoveWindow(dpy, barwin, sx, sy - bh);
1745 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1749 updatesizehints(Client *c) {
1753 if(!XGetWMNormalHints(dpy, c->win, &size, &msize) || !size.flags)
1755 c->flags = size.flags;
1756 if(c->flags & PBaseSize) {
1757 c->basew = size.base_width;
1758 c->baseh = size.base_height;
1760 else if(c->flags & PMinSize) {
1761 c->basew = size.min_width;
1762 c->baseh = size.min_height;
1765 c->basew = c->baseh = 0;
1766 if(c->flags & PResizeInc) {
1767 c->incw = size.width_inc;
1768 c->inch = size.height_inc;
1771 c->incw = c->inch = 0;
1772 if(c->flags & PMaxSize) {
1773 c->maxw = size.max_width;
1774 c->maxh = size.max_height;
1777 c->maxw = c->maxh = 0;
1778 if(c->flags & PMinSize) {
1779 c->minw = size.min_width;
1780 c->minh = size.min_height;
1782 else if(c->flags & PBaseSize) {
1783 c->minw = size.base_width;
1784 c->minh = size.base_height;
1787 c->minw = c->minh = 0;
1788 if(c->flags & PAspect) {
1789 c->minax = size.min_aspect.x;
1790 c->maxax = size.max_aspect.x;
1791 c->minay = size.min_aspect.y;
1792 c->maxay = size.max_aspect.y;
1795 c->minax = c->maxax = c->minay = c->maxay = 0;
1796 c->isfixed = (c->maxw && c->minw && c->maxh && c->minh
1797 && c->maxw == c->minw && c->maxh == c->minh);
1801 updatetitle(Client *c) {
1802 if(!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
1803 gettextprop(c->win, wmatom[WMName], c->name, sizeof c->name);
1806 /* There's no way to check accesses to destroyed windows, thus those cases are
1807 * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
1808 * default error handler, which may call exit. */
1810 xerror(Display *dpy, XErrorEvent *ee) {
1811 if(ee->error_code == BadWindow
1812 || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1813 || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1814 || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1815 || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1816 || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1817 || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1818 || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1820 fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1821 ee->request_code, ee->error_code);
1822 return xerrorxlib(dpy, ee); /* may call exit */
1826 xerrordummy(Display *dsply, XErrorEvent *ee) {
1830 /* Startup Error handler to check if another window manager
1831 * is already running. */
1833 xerrorstart(Display *dsply, XErrorEvent *ee) {
1839 view(const char *arg) {
1842 memcpy(prevtags, seltags, sizeof seltags);
1843 for(i = 0; i < ntags; i++)
1844 seltags[i] = arg == NULL;
1846 if(i >= 0 && i < ntags)
1852 viewprevtag(const char *arg) {
1853 static Bool tmptags[sizeof tags / sizeof tags[0]];
1855 memcpy(tmptags, seltags, sizeof seltags);
1856 memcpy(seltags, prevtags, sizeof seltags);
1857 memcpy(prevtags, tmptags, sizeof seltags);
1862 zoom(const char *arg) {
1865 if(!sel || !ISTILE || sel->isfloating)
1867 if((c = sel) == nexttiled(clients))
1868 if(!(c = nexttiled(c->next)))
1877 main(int argc, char *argv[]) {
1878 if(argc == 2 && !strcmp("-v", argv[1]))
1879 eprint("dwm-"VERSION", © 2006-2007 A. R. Garbe, S. van Dijk, J. Salmi, P. Hruby, S. Nagy\n");
1881 eprint("usage: dwm [-v]\n");
1883 setlocale(LC_CTYPE, "");
1884 if(!(dpy = XOpenDisplay(0)))
1885 eprint("dwm: cannot open display\n");
1886 screen = DefaultScreen(dpy);
1887 root = RootWindow(dpy, screen);