1 /* See LICENSE file for copyright and license details.
3 * dynamic window manager is designed like any other X client as well. It is
4 * driven through handling X events. In contrast to other X clients, a window
5 * manager selects for SubstructureRedirectMask on the root window, to receive
6 * events about window (dis-)appearance. Only one X connection at a time is
7 * allowed to select for this event mask.
9 * Calls to fetch an X event from the event queue are blocking. Due reading
10 * status text from standard input, a select()-driven main loop has been
11 * implemented which selects for reads on the X connection and STDIN_FILENO to
12 * handle all data smoothly. The event handlers of dwm are organized in an
13 * array which is accessed whenever a new event has been fetched. This allows
14 * event dispatching in O(1) time.
16 * Each child of the root window is called a client, except windows which have
17 * set the override_redirect flag. Clients are organized in a global
18 * doubly-linked client list, the focus history is remembered through a global
19 * stack list. Each client contains an array of Bools of the same size as the
20 * global tags array to indicate the tags of a client. For each client dwm
21 * creates a small title window, which is resized whenever the (_NET_)WM_NAME
22 * properties are updated or the client is moved/resized.
24 * Keys and tagging rules are organized as arrays and defined in the config.h
25 * file. These arrays are kept static in event.o and tag.o respectively,
26 * because no other part of dwm needs access to them. The current layout is
27 * represented by the lt pointer.
29 * To understand everything else, start reading main().
39 #include <sys/select.h>
41 #include <X11/cursorfont.h>
42 #include <X11/keysym.h>
43 #include <X11/Xatom.h>
44 #include <X11/Xproto.h>
45 #include <X11/Xutil.h>
48 #define BUTTONMASK (ButtonPressMask | ButtonReleaseMask)
49 #define CLEANMASK(mask) (mask & ~(numlockmask | LockMask))
50 #define MOUSEMASK (BUTTONMASK | PointerMotionMask)
53 enum { BarTop, BarBot, BarOff }; /* bar position */
54 enum { CurNormal, CurResize, CurMove, CurLast }; /* cursor */
55 enum { ColBorder, ColFG, ColBG, ColLast }; /* color */
56 enum { NetSupported, NetWMName, NetLast }; /* EWMH atoms */
57 enum { WMProtocols, WMDelete, WMName, WMState, WMLast };/* default atoms */
60 typedef struct Client Client;
64 int rx, ry, rw, rh; /* revert geometry */
65 int basew, baseh, incw, inch, maxw, maxh, minw, minh;
66 int minax, maxax, minay, maxay;
68 unsigned int border, oldborder;
69 Bool isbanned, isfixed, ismax, isfloating;
79 unsigned long norm[ColLast];
80 unsigned long sel[ColLast];
90 } DC; /* draw context */
95 void (*func)(const char *arg);
101 void (*arrange)(void);
115 /* forward declarations */
116 static void applyrules(Client *c);
117 static void arrange(void);
118 static void attach(Client *c);
119 static void attachstack(Client *c);
120 static void ban(Client *c);
121 static void buttonpress(XEvent *e);
122 static void checkotherwm(void);
123 static void cleanup(void);
124 static void compileregs(void);
125 static void configure(Client *c);
126 static void configurenotify(XEvent *e);
127 static void configurerequest(XEvent *e);
128 static void destroynotify(XEvent *e);
129 static void detach(Client *c);
130 static void detachstack(Client *c);
131 static void drawbar(void);
132 static void drawsquare(Bool filled, Bool empty, unsigned long col[ColLast]);
133 static void drawtext(const char *text, unsigned long col[ColLast]);
134 static void *emallocz(unsigned int size);
135 static void enternotify(XEvent *e);
136 static void eprint(const char *errstr, ...);
137 static void expose(XEvent *e);
138 static void floating(void); /* default floating layout */
139 static void focus(Client *c);
140 static void focusnext(const char *arg);
141 static void focusprev(const char *arg);
142 static Client *getclient(Window w);
143 static unsigned long getcolor(const char *colstr);
144 static long getstate(Window w);
145 static Bool gettextprop(Window w, Atom atom, char *text, unsigned int size);
146 static void grabbuttons(Client *c, Bool focused);
147 static unsigned int idxoftag(const char *tag);
148 static void initfont(const char *fontstr);
149 static Bool isarrange(void (*func)());
150 static Bool isoccupied(unsigned int t);
151 static Bool isprotodel(Client *c);
152 static Bool isvisible(Client *c);
153 static void keypress(XEvent *e);
154 static void killclient(const char *arg);
155 static void leavenotify(XEvent *e);
156 static void manage(Window w, XWindowAttributes *wa);
157 static void mappingnotify(XEvent *e);
158 static void maprequest(XEvent *e);
159 static void movemouse(Client *c);
160 static Client *nexttiled(Client *c);
161 static void propertynotify(XEvent *e);
162 static void quit(const char *arg);
163 static void resize(Client *c, int x, int y, int w, int h, Bool sizehints);
164 static void resizemouse(Client *c);
165 static void restack(void);
166 static void run(void);
167 static void scan(void);
168 static void setclientstate(Client *c, long state);
169 static void setlayout(const char *arg);
170 static void setmwfact(const char *arg);
171 static void setup(void);
172 static void spawn(const char *arg);
173 static void tag(const char *arg);
174 static unsigned int textnw(const char *text, unsigned int len);
175 static unsigned int textw(const char *text);
176 static void tile(void);
177 static void togglebar(const char *arg);
178 static void togglefloating(const char *arg);
179 static void togglemax(const char *arg);
180 static void toggletag(const char *arg);
181 static void toggleview(const char *arg);
182 static void unban(Client *c);
183 static void unmanage(Client *c);
184 static void unmapnotify(XEvent *e);
185 static void updatebarpos(void);
186 static void updatesizehints(Client *c);
187 static void updatetitle(Client *c);
188 static void view(const char *arg);
189 static int xerror(Display *dpy, XErrorEvent *ee);
190 static int xerrordummy(Display *dsply, XErrorEvent *ee);
191 static int xerrorstart(Display *dsply, XErrorEvent *ee);
192 static void zoom(const char *arg);
195 static char stext[256];
196 static double mwfact;
197 static int screen, sx, sy, sw, sh, wax, way, waw, wah;
198 static int (*xerrorxlib)(Display *, XErrorEvent *);
199 static unsigned int bh, bpos, ntags;
200 static unsigned int blw = 0;
201 static unsigned int ltidx = 0; /* default */
202 static unsigned int nlayouts = 0;
203 static unsigned int nrules = 0;
204 static unsigned int numlockmask = 0;
205 static void (*handler[LASTEvent]) (XEvent *) = {
206 [ButtonPress] = buttonpress,
207 [ConfigureRequest] = configurerequest,
208 [ConfigureNotify] = configurenotify,
209 [DestroyNotify] = destroynotify,
210 [EnterNotify] = enternotify,
211 [LeaveNotify] = leavenotify,
213 [KeyPress] = keypress,
214 [MappingNotify] = mappingnotify,
215 [MapRequest] = maprequest,
216 [PropertyNotify] = propertynotify,
217 [UnmapNotify] = unmapnotify
219 static Atom wmatom[WMLast], netatom[NetLast];
220 static Bool otherwm, readin;
221 static Bool running = True;
222 static Bool *seltags;
223 static Bool selscreen = True;
224 static Client *clients = NULL;
225 static Client *sel = NULL;
226 static Client *stack = NULL;
227 static Cursor cursor[CurLast];
230 static Window barwin, root;
231 static Regs *regs = NULL;
233 /* configuration, allows nested code to access above variables */
238 applyrules(Client *c) {
239 static char buf[512];
242 Bool matched = False;
243 XClassHint ch = { 0 };
246 XGetClassHint(dpy, c->win, &ch);
247 snprintf(buf, sizeof buf, "%s:%s:%s",
248 ch.res_class ? ch.res_class : "",
249 ch.res_name ? ch.res_name : "", c->name);
250 for(i = 0; i < nrules; i++)
251 if(regs[i].propregex && !regexec(regs[i].propregex, buf, 1, &tmp, 0)) {
252 c->isfloating = rules[i].isfloating;
253 for(j = 0; regs[i].tagregex && j < ntags; j++) {
254 if(!regexec(regs[i].tagregex, tags[j], 1, &tmp, 0)) {
265 for(i = 0; i < ntags; i++)
266 c->tags[i] = seltags[i];
273 for(c = clients; c; c = c->next)
278 layouts[ltidx].arrange();
292 attachstack(Client *c) {
301 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
306 buttonpress(XEvent *e) {
309 XButtonPressedEvent *ev = &e->xbutton;
311 if(barwin == ev->window) {
313 for(i = 0; i < ntags; i++) {
316 if(ev->button == Button1) {
317 if(ev->state & MODKEY)
322 else if(ev->button == Button3) {
323 if(ev->state & MODKEY)
331 if((ev->x < x + blw) && ev->button == Button1)
334 else if((c = getclient(ev->window))) {
336 if(CLEANMASK(ev->state) != MODKEY)
338 if(ev->button == Button1) {
339 if(!isarrange(floating) && !c->isfloating)
340 togglefloating(NULL);
345 else if(ev->button == Button2) {
346 if(isarrange(tile) && !c->isfixed && c->isfloating)
347 togglefloating(NULL);
351 else if(ev->button == Button3 && !c->isfixed) {
352 if(!isarrange(floating) && !c->isfloating)
353 togglefloating(NULL);
364 XSetErrorHandler(xerrorstart);
366 /* this causes an error if some other window manager is running */
367 XSelectInput(dpy, root, SubstructureRedirectMask);
370 eprint("dwm: another window manager is already running\n");
372 XSetErrorHandler(NULL);
373 xerrorxlib = XSetErrorHandler(xerror);
385 XFreeFontSet(dpy, dc.font.set);
387 XFreeFont(dpy, dc.font.xfont);
388 XUngrabKey(dpy, AnyKey, AnyModifier, root);
389 XFreePixmap(dpy, dc.drawable);
391 XDestroyWindow(dpy, barwin);
392 XFreeCursor(dpy, cursor[CurNormal]);
393 XFreeCursor(dpy, cursor[CurResize]);
394 XFreeCursor(dpy, cursor[CurMove]);
395 XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime);
407 nrules = sizeof rules / sizeof rules[0];
408 regs = emallocz(nrules * sizeof(Regs));
409 for(i = 0; i < nrules; i++) {
411 reg = emallocz(sizeof(regex_t));
412 if(regcomp(reg, rules[i].prop, REG_EXTENDED))
415 regs[i].propregex = reg;
418 reg = emallocz(sizeof(regex_t));
419 if(regcomp(reg, rules[i].tags, REG_EXTENDED))
422 regs[i].tagregex = reg;
428 configure(Client *c) {
431 ce.type = ConfigureNotify;
439 ce.border_width = c->border;
441 ce.override_redirect = False;
442 XSendEvent(dpy, c->win, False, StructureNotifyMask, (XEvent *)&ce);
446 configurenotify(XEvent *e) {
447 XConfigureEvent *ev = &e->xconfigure;
449 if (ev->window == root && (ev->width != sw || ev->height != sh)) {
452 XFreePixmap(dpy, dc.drawable);
453 dc.drawable = XCreatePixmap(dpy, root, sw, bh, DefaultDepth(dpy, screen));
454 XResizeWindow(dpy, barwin, sw, bh);
461 configurerequest(XEvent *e) {
463 XConfigureRequestEvent *ev = &e->xconfigurerequest;
466 if((c = getclient(ev->window))) {
468 if(ev->value_mask & CWBorderWidth)
469 c->border = ev->border_width;
470 if(c->isfixed || c->isfloating || isarrange(floating)) {
471 if(ev->value_mask & CWX)
473 if(ev->value_mask & CWY)
475 if(ev->value_mask & CWWidth)
477 if(ev->value_mask & CWHeight)
479 if((c->x + c->w) > sw && c->isfloating)
480 c->x = sw / 2 - c->w / 2; /* center in x direction */
481 if((c->y + c->h) > sh && c->isfloating)
482 c->y = sh / 2 - c->h / 2; /* center in y direction */
483 if((ev->value_mask & (CWX | CWY))
484 && !(ev->value_mask & (CWWidth | CWHeight)))
487 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h);
495 wc.width = ev->width;
496 wc.height = ev->height;
497 wc.border_width = ev->border_width;
498 wc.sibling = ev->above;
499 wc.stack_mode = ev->detail;
500 XConfigureWindow(dpy, ev->window, ev->value_mask, &wc);
506 destroynotify(XEvent *e) {
508 XDestroyWindowEvent *ev = &e->xdestroywindow;
510 if((c = getclient(ev->window)))
517 c->prev->next = c->next;
519 c->next->prev = c->prev;
522 c->next = c->prev = NULL;
526 detachstack(Client *c) {
529 for(tc=&stack; *tc && *tc != c; tc=&(*tc)->snext);
538 for(i = 0; i < ntags; i++) {
539 dc.w = textw(tags[i]);
541 drawtext(tags[i], dc.sel);
542 drawsquare(sel && sel->tags[i], isoccupied(i), dc.sel);
545 drawtext(tags[i], dc.norm);
546 drawsquare(sel && sel->tags[i], isoccupied(i), dc.norm);
551 drawtext(layouts[ltidx].symbol, dc.norm);
559 drawtext(stext, dc.norm);
560 if((dc.w = dc.x - x) > bh) {
563 drawtext(sel->name, dc.sel);
564 drawsquare(sel->ismax, sel->isfloating, dc.sel);
567 drawtext(NULL, dc.norm);
569 XCopyArea(dpy, dc.drawable, barwin, dc.gc, 0, 0, sw, bh, 0, 0);
574 drawsquare(Bool filled, Bool empty, unsigned long col[ColLast]) {
577 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
579 gcv.foreground = col[ColFG];
580 XChangeGC(dpy, dc.gc, GCForeground, &gcv);
581 x = (dc.font.ascent + dc.font.descent + 2) / 4;
585 r.width = r.height = x + 1;
586 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
589 r.width = r.height = x;
590 XDrawRectangles(dpy, dc.drawable, dc.gc, &r, 1);
595 drawtext(const char *text, unsigned long col[ColLast]) {
597 static char buf[256];
598 unsigned int len, olen;
599 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
601 XSetForeground(dpy, dc.gc, col[ColBG]);
602 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
606 olen = len = strlen(text);
607 if(len >= sizeof buf)
608 len = sizeof buf - 1;
609 memcpy(buf, text, len);
611 h = dc.font.ascent + dc.font.descent;
612 y = dc.y + (dc.h / 2) - (h / 2) + dc.font.ascent;
614 /* shorten text if necessary */
615 while(len && (w = textnw(buf, len)) > dc.w - h)
626 return; /* too long */
627 XSetForeground(dpy, dc.gc, col[ColFG]);
629 XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
631 XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
635 emallocz(unsigned int size) {
636 void *res = calloc(1, size);
639 eprint("fatal: could not malloc() %u bytes\n", size);
644 enternotify(XEvent *e) {
646 XCrossingEvent *ev = &e->xcrossing;
648 if(ev->mode != NotifyNormal || ev->detail == NotifyInferior)
650 if((c = getclient(ev->window)))
652 else if(ev->window == root) {
659 eprint(const char *errstr, ...) {
662 va_start(ap, errstr);
663 vfprintf(stderr, errstr, ap);
670 XExposeEvent *ev = &e->xexpose;
673 if(barwin == ev->window)
679 floating(void) { /* default floating layout */
682 for(c = clients; c; c = c->next)
684 resize(c, c->x, c->y, c->w, c->h, True);
689 if((!c && selscreen) || (c && !isvisible(c)))
690 for(c = stack; c && !isvisible(c); c = c->snext);
691 if(sel && sel != c) {
692 grabbuttons(sel, False);
693 XSetWindowBorder(dpy, sel->win, dc.norm[ColBorder]);
698 grabbuttons(c, True);
705 XSetWindowBorder(dpy, c->win, dc.sel[ColBorder]);
706 XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
709 XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
713 focusnext(const char *arg) {
718 for(c = sel->next; c && !isvisible(c); c = c->next);
720 for(c = clients; c && !isvisible(c); c = c->next);
728 focusprev(const char *arg) {
733 for(c = sel->prev; c && !isvisible(c); c = c->prev);
735 for(c = clients; c && c->next; c = c->next);
736 for(; c && !isvisible(c); c = c->prev);
745 getclient(Window w) {
748 for(c = clients; c && c->win != w; c = c->next);
753 getcolor(const char *colstr) {
754 Colormap cmap = DefaultColormap(dpy, screen);
757 if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
758 eprint("error, cannot allocate color '%s'\n", colstr);
766 unsigned char *p = NULL;
767 unsigned long n, extra;
770 status = XGetWindowProperty(dpy, w, wmatom[WMState], 0L, 2L, False, wmatom[WMState],
771 &real, &format, &n, &extra, (unsigned char **)&p);
772 if(status != Success)
781 gettextprop(Window w, Atom atom, char *text, unsigned int size) {
786 if(!text || size == 0)
789 XGetTextProperty(dpy, w, &name, atom);
792 if(name.encoding == XA_STRING)
793 strncpy(text, (char *)name.value, size - 1);
795 if(XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success
798 strncpy(text, *list, size - 1);
799 XFreeStringList(list);
802 text[size - 1] = '\0';
808 grabbuttons(Client *c, Bool focused) {
809 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
812 XGrabButton(dpy, Button1, MODKEY, c->win, False, BUTTONMASK,
813 GrabModeAsync, GrabModeSync, None, None);
814 XGrabButton(dpy, Button1, MODKEY | LockMask, c->win, False, BUTTONMASK,
815 GrabModeAsync, GrabModeSync, None, None);
816 XGrabButton(dpy, Button1, MODKEY | numlockmask, c->win, False, BUTTONMASK,
817 GrabModeAsync, GrabModeSync, None, None);
818 XGrabButton(dpy, Button1, MODKEY | numlockmask | LockMask, c->win, False, BUTTONMASK,
819 GrabModeAsync, GrabModeSync, None, None);
821 XGrabButton(dpy, Button2, MODKEY, c->win, False, BUTTONMASK,
822 GrabModeAsync, GrabModeSync, None, None);
823 XGrabButton(dpy, Button2, MODKEY | LockMask, c->win, False, BUTTONMASK,
824 GrabModeAsync, GrabModeSync, None, None);
825 XGrabButton(dpy, Button2, MODKEY | numlockmask, c->win, False, BUTTONMASK,
826 GrabModeAsync, GrabModeSync, None, None);
827 XGrabButton(dpy, Button2, MODKEY | numlockmask | LockMask, c->win, False, BUTTONMASK,
828 GrabModeAsync, GrabModeSync, None, None);
830 XGrabButton(dpy, Button3, MODKEY, c->win, False, BUTTONMASK,
831 GrabModeAsync, GrabModeSync, None, None);
832 XGrabButton(dpy, Button3, MODKEY | LockMask, c->win, False, BUTTONMASK,
833 GrabModeAsync, GrabModeSync, None, None);
834 XGrabButton(dpy, Button3, MODKEY | numlockmask, c->win, False, BUTTONMASK,
835 GrabModeAsync, GrabModeSync, None, None);
836 XGrabButton(dpy, Button3, MODKEY | numlockmask | LockMask, c->win, False, BUTTONMASK,
837 GrabModeAsync, GrabModeSync, None, None);
840 XGrabButton(dpy, AnyButton, AnyModifier, c->win, False, BUTTONMASK,
841 GrabModeAsync, GrabModeSync, None, None);
845 idxoftag(const char *tag) {
848 for(i = 0; i < ntags; i++)
855 initfont(const char *fontstr) {
856 char *def, **missing;
861 XFreeFontSet(dpy, dc.font.set);
862 dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
865 fprintf(stderr, "dwm: missing fontset: %s\n", missing[n]);
866 XFreeStringList(missing);
869 XFontSetExtents *font_extents;
870 XFontStruct **xfonts;
872 dc.font.ascent = dc.font.descent = 0;
873 font_extents = XExtentsOfFontSet(dc.font.set);
874 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
875 for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
876 if(dc.font.ascent < (*xfonts)->ascent)
877 dc.font.ascent = (*xfonts)->ascent;
878 if(dc.font.descent < (*xfonts)->descent)
879 dc.font.descent = (*xfonts)->descent;
885 XFreeFont(dpy, dc.font.xfont);
886 dc.font.xfont = NULL;
887 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr))
888 || !(dc.font.xfont = XLoadQueryFont(dpy, "fixed")))
889 eprint("error, cannot load font: '%s'\n", fontstr);
890 dc.font.ascent = dc.font.xfont->ascent;
891 dc.font.descent = dc.font.xfont->descent;
893 dc.font.height = dc.font.ascent + dc.font.descent;
897 isarrange(void (*func)())
899 return func == layouts[ltidx].arrange;
903 isoccupied(unsigned int t) {
906 for(c = clients; c; c = c->next)
913 isprotodel(Client *c) {
918 if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
919 for(i = 0; !ret && i < n; i++)
920 if(protocols[i] == wmatom[WMDelete])
928 isvisible(Client *c) {
931 for(i = 0; i < ntags; i++)
932 if(c->tags[i] && seltags[i])
938 keypress(XEvent *e) {
940 unsigned int len = sizeof keys / sizeof keys[0];
946 if(!e) { /* grabkeys */
947 XUngrabKey(dpy, AnyKey, AnyModifier, root);
948 for(i = 0; i < len; i++) {
949 code = XKeysymToKeycode(dpy, keys[i].keysym);
950 XGrabKey(dpy, code, keys[i].mod, root, True,
951 GrabModeAsync, GrabModeAsync);
952 XGrabKey(dpy, code, keys[i].mod | LockMask, root, True,
953 GrabModeAsync, GrabModeAsync);
954 XGrabKey(dpy, code, keys[i].mod | numlockmask, root, True,
955 GrabModeAsync, GrabModeAsync);
956 XGrabKey(dpy, code, keys[i].mod | numlockmask | LockMask, root, True,
957 GrabModeAsync, GrabModeAsync);
962 keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
963 for(i = 0; i < len; i++)
964 if(keysym == keys[i].keysym
965 && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state))
968 keys[i].func(keys[i].arg);
973 killclient(const char *arg) {
978 if(isprotodel(sel)) {
979 ev.type = ClientMessage;
980 ev.xclient.window = sel->win;
981 ev.xclient.message_type = wmatom[WMProtocols];
982 ev.xclient.format = 32;
983 ev.xclient.data.l[0] = wmatom[WMDelete];
984 ev.xclient.data.l[1] = CurrentTime;
985 XSendEvent(dpy, sel->win, False, NoEventMask, &ev);
988 XKillClient(dpy, sel->win);
992 leavenotify(XEvent *e) {
993 XCrossingEvent *ev = &e->xcrossing;
995 if((ev->window == root) && !ev->same_screen) {
1002 manage(Window w, XWindowAttributes *wa) {
1004 Client *c, *t = NULL;
1009 c = emallocz(sizeof(Client));
1010 c->tags = emallocz(ntags * sizeof(Bool));
1016 c->oldborder = wa->border_width;
1017 if(c->w == sw && c->h == sh) {
1020 c->border = wa->border_width;
1023 if(c->x + c->w + 2 * c->border > wax + waw)
1024 c->x = wax + waw - c->w - 2 * c->border;
1025 if(c->y + c->h + 2 * c->border > way + wah)
1026 c->y = way + wah - c->h - 2 * c->border;
1031 c->border = BORDERPX;
1033 wc.border_width = c->border;
1034 XConfigureWindow(dpy, w, CWBorderWidth, &wc);
1035 XSetWindowBorder(dpy, w, dc.norm[ColBorder]);
1036 configure(c); /* propagates border_width, if size doesn't change */
1038 XSelectInput(dpy, w,
1039 StructureNotifyMask | PropertyChangeMask | EnterWindowMask);
1040 grabbuttons(c, False);
1042 if((rettrans = XGetTransientForHint(dpy, w, &trans) == Success))
1043 for(t = clients; t && t->win != trans; t = t->next);
1045 for(i = 0; i < ntags; i++)
1046 c->tags[i] = t->tags[i];
1049 c->isfloating = (rettrans == Success) || c->isfixed;
1052 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h); /* some windows require this */
1054 XMapWindow(dpy, c->win);
1055 setclientstate(c, NormalState);
1060 mappingnotify(XEvent *e) {
1061 XMappingEvent *ev = &e->xmapping;
1063 XRefreshKeyboardMapping(ev);
1064 if(ev->request == MappingKeyboard)
1069 maprequest(XEvent *e) {
1070 static XWindowAttributes wa;
1071 XMapRequestEvent *ev = &e->xmaprequest;
1073 if(!XGetWindowAttributes(dpy, ev->window, &wa))
1075 if(wa.override_redirect)
1077 if(!getclient(ev->window))
1078 manage(ev->window, &wa);
1082 movemouse(Client *c) {
1083 int x1, y1, ocx, ocy, di, nx, ny;
1090 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1091 None, cursor[CurMove], CurrentTime) != GrabSuccess)
1094 XQueryPointer(dpy, root, &dummy, &dummy, &x1, &y1, &di, &di, &dui);
1096 XMaskEvent(dpy, MOUSEMASK | ExposureMask | SubstructureRedirectMask, &ev);
1099 XUngrabPointer(dpy, CurrentTime);
1101 case ConfigureRequest:
1104 handler[ev.type](&ev);
1108 nx = ocx + (ev.xmotion.x - x1);
1109 ny = ocy + (ev.xmotion.y - y1);
1110 if(abs(wax + nx) < SNAP)
1112 else if(abs((wax + waw) - (nx + c->w + 2 * c->border)) < SNAP)
1113 nx = wax + waw - c->w - 2 * c->border;
1114 if(abs(way - ny) < SNAP)
1116 else if(abs((way + wah) - (ny + c->h + 2 * c->border)) < SNAP)
1117 ny = way + wah - c->h - 2 * c->border;
1118 resize(c, nx, ny, c->w, c->h, False);
1125 nexttiled(Client *c) {
1126 for(; c && (c->isfloating || !isvisible(c)); c = c->next);
1131 propertynotify(XEvent *e) {
1134 XPropertyEvent *ev = &e->xproperty;
1136 if(ev->state == PropertyDelete)
1137 return; /* ignore */
1138 if((c = getclient(ev->window))) {
1141 case XA_WM_TRANSIENT_FOR:
1142 XGetTransientForHint(dpy, c->win, &trans);
1143 if(!c->isfloating && (c->isfloating = (getclient(trans) != NULL)))
1146 case XA_WM_NORMAL_HINTS:
1150 if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
1159 quit(const char *arg) {
1160 readin = running = False;
1164 resize(Client *c, int x, int y, int w, int h, Bool sizehints) {
1165 double dx, dy, max, min, ratio;
1169 if(c->minay > 0 && c->maxay > 0 && (h - c->baseh) > 0 && (w - c->basew) > 0) {
1170 dx = (double)(w - c->basew);
1171 dy = (double)(h - c->baseh);
1172 min = (double)(c->minax) / (double)(c->minay);
1173 max = (double)(c->maxax) / (double)(c->maxay);
1175 if(max > 0 && min > 0 && ratio > 0) {
1177 dy = (dx * min + dy) / (min * min + 1);
1179 w = (int)dx + c->basew;
1180 h = (int)dy + c->baseh;
1182 else if(ratio > max) {
1183 dy = (dx * min + dy) / (max * max + 1);
1185 w = (int)dx + c->basew;
1186 h = (int)dy + c->baseh;
1190 if(c->minw && w < c->minw)
1192 if(c->minh && h < c->minh)
1194 if(c->maxw && w > c->maxw)
1196 if(c->maxh && h > c->maxh)
1199 w -= (w - c->basew) % c->incw;
1201 h -= (h - c->baseh) % c->inch;
1203 if(w <= 0 || h <= 0)
1205 /* offscreen appearance fixes */
1207 x = sw - w - 2 * c->border;
1209 y = sh - h - 2 * c->border;
1210 if(x + w + 2 * c->border < sx)
1212 if(y + h + 2 * c->border < sy)
1214 if(c->x != x || c->y != y || c->w != w || c->h != h) {
1217 c->w = wc.width = w;
1218 c->h = wc.height = h;
1219 wc.border_width = c->border;
1220 XConfigureWindow(dpy, c->win, CWX | CWY | CWWidth | CWHeight | CWBorderWidth, &wc);
1227 resizemouse(Client *c) {
1234 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1235 None, cursor[CurResize], CurrentTime) != GrabSuccess)
1238 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->border - 1, c->h + c->border - 1);
1240 XMaskEvent(dpy, MOUSEMASK | ExposureMask | SubstructureRedirectMask , &ev);
1243 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0,
1244 c->w + c->border - 1, c->h + c->border - 1);
1245 XUngrabPointer(dpy, CurrentTime);
1246 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1248 case ConfigureRequest:
1251 handler[ev.type](&ev);
1255 if((nw = ev.xmotion.x - ocx - 2 * c->border + 1) <= 0)
1257 if((nh = ev.xmotion.y - ocy - 2 * c->border + 1) <= 0)
1259 resize(c, c->x, c->y, nw, nh, True);
1274 if(sel->isfloating || isarrange(floating))
1275 XRaiseWindow(dpy, sel->win);
1276 if(!isarrange(floating)) {
1277 wc.stack_mode = Below;
1278 wc.sibling = barwin;
1279 if(!sel->isfloating) {
1280 XConfigureWindow(dpy, sel->win, CWSibling | CWStackMode, &wc);
1281 wc.sibling = sel->win;
1283 for(c = nexttiled(clients); c; c = nexttiled(c->next)) {
1286 XConfigureWindow(dpy, c->win, CWSibling | CWStackMode, &wc);
1287 wc.sibling = c->win;
1291 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1301 /* main event loop, also reads status text from stdin */
1303 xfd = ConnectionNumber(dpy);
1308 FD_SET(STDIN_FILENO, &rd);
1310 if(select(xfd + 1, &rd, NULL, NULL, NULL) == -1) {
1313 eprint("select failed\n");
1315 if(FD_ISSET(STDIN_FILENO, &rd)) {
1316 switch(r = read(STDIN_FILENO, stext, sizeof stext - 1)) {
1318 strncpy(stext, strerror(errno), sizeof stext - 1);
1319 stext[sizeof stext - 1] = '\0';
1323 strncpy(stext, "EOF", 4);
1327 for(stext[r] = '\0', p = stext + strlen(stext) - 1; p >= stext && *p == '\n'; *p-- = '\0');
1328 for(; p >= stext && *p != '\n'; --p);
1330 strncpy(stext, p + 1, sizeof stext);
1334 while(XPending(dpy)) {
1335 XNextEvent(dpy, &ev);
1336 if(handler[ev.type])
1337 (handler[ev.type])(&ev); /* call handler */
1344 unsigned int i, num;
1345 Window *wins, d1, d2;
1346 XWindowAttributes wa;
1349 if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1350 for(i = 0; i < num; i++) {
1351 if(!XGetWindowAttributes(dpy, wins[i], &wa)
1352 || wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1354 if(wa.map_state == IsViewable || getstate(wins[i]) == IconicState)
1355 manage(wins[i], &wa);
1357 for(i = 0; i < num; i++) { /* now the transients */
1358 if(!XGetWindowAttributes(dpy, wins[i], &wa))
1360 if(XGetTransientForHint(dpy, wins[i], &d1)
1361 && (wa.map_state == IsViewable || getstate(wins[i]) == IconicState))
1362 manage(wins[i], &wa);
1370 setclientstate(Client *c, long state) {
1371 long data[] = {state, None};
1373 XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1374 PropModeReplace, (unsigned char *)data, 2);
1378 setlayout(const char *arg) {
1382 if(++ltidx == nlayouts)
1386 for(i = 0; i < nlayouts; i++)
1387 if(!strcmp(arg, layouts[i].symbol))
1400 setmwfact(const char *arg) {
1403 if(!isarrange(tile))
1405 /* arg handling, manipulate mwfact */
1408 else if(1 == sscanf(arg, "%lf", &delta)) {
1409 if(arg[0] != '+' && arg[0] != '-')
1415 else if(mwfact > 0.9)
1423 unsigned int i, j, mask;
1425 XModifierKeymap *modmap;
1426 XSetWindowAttributes wa;
1429 wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1430 wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1431 wmatom[WMName] = XInternAtom(dpy, "WM_NAME", False);
1432 wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1433 netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1434 netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1435 XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1436 PropModeReplace, (unsigned char *) netatom, NetLast);
1439 cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1440 cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1441 cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1445 sw = DisplayWidth(dpy, screen);
1446 sh = DisplayHeight(dpy, screen);
1448 /* init modifier map */
1449 modmap = XGetModifierMapping(dpy);
1450 for(i = 0; i < 8; i++)
1451 for(j = 0; j < modmap->max_keypermod; j++) {
1452 if(modmap->modifiermap[i * modmap->max_keypermod + j]
1453 == XKeysymToKeycode(dpy, XK_Num_Lock))
1454 numlockmask = (1 << i);
1456 XFreeModifiermap(modmap);
1458 /* select for events */
1459 wa.event_mask = SubstructureRedirectMask | SubstructureNotifyMask
1460 | EnterWindowMask | LeaveWindowMask | StructureNotifyMask;
1461 wa.cursor = cursor[CurNormal];
1462 XChangeWindowAttributes(dpy, root, CWEventMask | CWCursor, &wa);
1463 XSelectInput(dpy, root, wa.event_mask);
1470 for(ntags = 0; tags[ntags]; ntags++);
1471 seltags = emallocz(sizeof(Bool) * ntags);
1474 /* init appearance */
1475 dc.norm[ColBorder] = getcolor(NORMBORDERCOLOR);
1476 dc.norm[ColBG] = getcolor(NORMBGCOLOR);
1477 dc.norm[ColFG] = getcolor(NORMFGCOLOR);
1478 dc.sel[ColBorder] = getcolor(SELBORDERCOLOR);
1479 dc.sel[ColBG] = getcolor(SELBGCOLOR);
1480 dc.sel[ColFG] = getcolor(SELFGCOLOR);
1482 dc.h = bh = dc.font.height + 2;
1486 nlayouts = sizeof layouts / sizeof layouts[0];
1487 for(blw = i = 0; i < nlayouts; i++) {
1488 j = textw(layouts[i].symbol);
1495 wa.override_redirect = 1;
1496 wa.background_pixmap = ParentRelative;
1497 wa.event_mask = ButtonPressMask | ExposureMask;
1498 barwin = XCreateWindow(dpy, root, sx, sy, sw, bh, 0,
1499 DefaultDepth(dpy, screen), CopyFromParent, DefaultVisual(dpy, screen),
1500 CWOverrideRedirect | CWBackPixmap | CWEventMask, &wa);
1501 XDefineCursor(dpy, barwin, cursor[CurNormal]);
1503 XMapRaised(dpy, barwin);
1504 strcpy(stext, "dwm-"VERSION);
1505 dc.drawable = XCreatePixmap(dpy, root, sw, bh, DefaultDepth(dpy, screen));
1506 dc.gc = XCreateGC(dpy, root, 0, 0);
1507 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
1509 XSetFont(dpy, dc.gc, dc.font.xfont->fid);
1511 /* multihead support */
1512 selscreen = XQueryPointer(dpy, root, &w, &w, &i, &i, &i, &i, &mask);
1516 spawn(const char *arg) {
1517 static char *shell = NULL;
1519 if(!shell && !(shell = getenv("SHELL")))
1523 /* The double-fork construct avoids zombie processes and keeps the code
1524 * clean from stupid signal handlers. */
1528 close(ConnectionNumber(dpy));
1530 execl(shell, shell, "-c", arg, (char *)NULL);
1531 fprintf(stderr, "dwm: execl '%s -c %s'", shell, arg);
1540 tag(const char *arg) {
1545 for(i = 0; i < ntags; i++)
1546 sel->tags[i] = arg == NULL;
1548 if(i >= 0 && i < ntags)
1549 sel->tags[i] = True;
1554 textnw(const char *text, unsigned int len) {
1558 XmbTextExtents(dc.font.set, text, len, NULL, &r);
1561 return XTextWidth(dc.font.xfont, text, len);
1565 textw(const char *text) {
1566 return textnw(text, strlen(text)) + dc.font.height;
1571 unsigned int i, n, nx, ny, nw, nh, mw, th;
1574 for(n = 0, c = nexttiled(clients); c; c = nexttiled(c->next))
1578 mw = (n == 1) ? waw : mwfact * waw;
1579 th = (n > 1) ? wah / (n - 1) : 0;
1580 if(n > 1 && th < bh)
1585 for(i = 0, c = 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 */
1596 nw = waw - mw - 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 += nh + 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 || (!isarrange(floating) && !sel->isfloating) || sel->isfixed)
1634 if((sel->ismax = !sel->ismax)) {
1639 resize(sel, wax, way, waw - 2 * sel->border, wah - 2 * sel->border, True);
1642 resize(sel, sel->rx, sel->ry, sel->rw, sel->rh, True);
1644 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1648 toggletag(const char *arg) {
1654 sel->tags[i] = !sel->tags[i];
1655 for(j = 0; j < ntags && !sel->tags[j]; j++);
1657 sel->tags[i] = True;
1662 toggleview(const char *arg) {
1666 seltags[i] = !seltags[i];
1667 for(j = 0; j < ntags && !seltags[j]; j++);
1669 seltags[i] = True; /* cannot toggle last view */
1677 XMoveWindow(dpy, c->win, c->x, c->y);
1678 c->isbanned = False;
1682 unmanage(Client *c) {
1685 wc.border_width = c->oldborder;
1686 /* The server grab construct avoids race conditions. */
1688 XSetErrorHandler(xerrordummy);
1689 XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
1694 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1695 setclientstate(c, WithdrawnState);
1699 XSetErrorHandler(xerror);
1705 unmapnotify(XEvent *e) {
1707 XUnmapEvent *ev = &e->xunmap;
1709 if((c = getclient(ev->window)))
1714 updatebarpos(void) {
1725 XMoveWindow(dpy, barwin, sx, sy);
1729 XMoveWindow(dpy, barwin, sx, sy + wah);
1732 XMoveWindow(dpy, barwin, sx, sy - bh);
1736 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1740 updatesizehints(Client *c) {
1744 if(!XGetWMNormalHints(dpy, c->win, &size, &msize) || !size.flags)
1746 c->flags = size.flags;
1747 if(c->flags & PBaseSize) {
1748 c->basew = size.base_width;
1749 c->baseh = size.base_height;
1751 else if(c->flags & PMinSize) {
1752 c->basew = size.min_width;
1753 c->baseh = size.min_height;
1756 c->basew = c->baseh = 0;
1757 if(c->flags & PResizeInc) {
1758 c->incw = size.width_inc;
1759 c->inch = size.height_inc;
1762 c->incw = c->inch = 0;
1763 if(c->flags & PMaxSize) {
1764 c->maxw = size.max_width;
1765 c->maxh = size.max_height;
1768 c->maxw = c->maxh = 0;
1769 if(c->flags & PMinSize) {
1770 c->minw = size.min_width;
1771 c->minh = size.min_height;
1773 else if(c->flags & PBaseSize) {
1774 c->minw = size.base_width;
1775 c->minh = size.base_height;
1778 c->minw = c->minh = 0;
1779 if(c->flags & PAspect) {
1780 c->minax = size.min_aspect.x;
1781 c->maxax = size.max_aspect.x;
1782 c->minay = size.min_aspect.y;
1783 c->maxay = size.max_aspect.y;
1786 c->minax = c->maxax = c->minay = c->maxay = 0;
1787 c->isfixed = (c->maxw && c->minw && c->maxh && c->minh
1788 && c->maxw == c->minw && c->maxh == c->minh);
1792 updatetitle(Client *c) {
1793 if(!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
1794 gettextprop(c->win, wmatom[WMName], c->name, sizeof c->name);
1797 /* There's no way to check accesses to destroyed windows, thus those cases are
1798 * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
1799 * default error handler, which may call exit. */
1801 xerror(Display *dpy, XErrorEvent *ee) {
1802 if(ee->error_code == BadWindow
1803 || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1804 || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1805 || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1806 || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1807 || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1808 || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1809 || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1811 fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1812 ee->request_code, ee->error_code);
1813 return xerrorxlib(dpy, ee); /* may call exit */
1817 xerrordummy(Display *dsply, XErrorEvent *ee) {
1821 /* Startup Error handler to check if another window manager
1822 * is already running. */
1824 xerrorstart(Display *dsply, XErrorEvent *ee) {
1830 view(const char *arg) {
1833 for(i = 0; i < ntags; i++)
1834 seltags[i] = arg == NULL;
1836 if(i >= 0 && i < ntags)
1842 zoom(const char *arg) {
1845 if(!sel || !isarrange(tile) || sel->isfloating)
1847 if((c = sel) == nexttiled(clients))
1848 if(!(c = nexttiled(c->next)))
1857 main(int argc, char *argv[]) {
1858 if(argc == 2 && !strcmp("-v", argv[1]))
1859 eprint("dwm-"VERSION", © 2006-2007 A. R. Garbe, S. van Dijk, J. Salmi, P. Hruby, S. Nagy\n");
1861 eprint("usage: dwm [-v]\n");
1863 setlocale(LC_CTYPE, "");
1864 if(!(dpy = XOpenDisplay(0)))
1865 eprint("dwm: cannot open display\n");
1866 screen = DefaultScreen(dpy);
1867 root = RootWindow(dpy, screen);