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().
36 #include <sys/select.h>
38 #include <X11/cursorfont.h>
39 #include <X11/keysym.h>
40 #include <X11/Xatom.h>
42 #include <X11/Xproto.h>
43 #include <X11/Xutil.h>
46 #define BUTTONMASK (ButtonPressMask | ButtonReleaseMask)
47 #define CLEANMASK(mask) (mask & ~(numlockmask | LockMask))
48 #define MOUSEMASK (BUTTONMASK | PointerMotionMask)
51 enum { BarTop, BarBot, BarOff }; /* bar position */
52 enum { CurNormal, CurResize, CurMove, CurLast }; /* cursor */
53 enum { ColBorder, ColFG, ColBG, ColLast }; /* color */
54 enum { NetSupported, NetWMName, NetLast }; /* EWMH atoms */
55 enum { WMProtocols, WMDelete, WMName, WMState, WMLast };/* default atoms */
58 typedef struct Client Client;
62 int rx, ry, rw, rh; /* revert geometry */
63 int basew, baseh, incw, inch, maxw, maxh, minw, minh;
64 int minax, maxax, minay, maxay;
66 unsigned int border, oldborder;
67 Bool isbanned, isfixed, ismax, isfloating, wasfloating;
77 unsigned long norm[ColLast];
78 unsigned long sel[ColLast];
88 } DC; /* draw context */
93 void (*func)(const char *arg);
99 void (*arrange)(void);
113 /* forward declarations */
114 void applyrules(Client *c);
116 void attach(Client *c);
117 void attachstack(Client *c);
119 void buttonpress(XEvent *e);
120 void checkotherwm(void);
122 void compileregs(void);
123 void configure(Client *c);
124 void configurenotify(XEvent *e);
125 void configurerequest(XEvent *e);
126 void destroynotify(XEvent *e);
127 void detach(Client *c);
128 void detachstack(Client *c);
130 void drawsquare(Bool filled, Bool empty, unsigned long col[ColLast]);
131 void drawtext(const char *text, unsigned long col[ColLast]);
132 void *emallocz(unsigned int size);
133 void enternotify(XEvent *e);
134 void eprint(const char *errstr, ...);
135 void expose(XEvent *e);
136 void floating(void); /* default floating layout */
137 void focus(Client *c);
138 void focusnext(const char *arg);
139 void focusprev(const char *arg);
140 Client *getclient(Window w);
141 unsigned long getcolor(const char *colstr);
142 long getstate(Window w);
143 Bool gettextprop(Window w, Atom atom, char *text, unsigned int size);
144 void grabbuttons(Client *c, Bool focused);
145 unsigned int idxoftag(const char *tag);
146 void initfont(const char *fontstr);
147 Bool isarrange(void (*func)());
148 Bool isoccupied(unsigned int t);
149 Bool isprotodel(Client *c);
150 Bool isvisible(Client *c);
151 void keypress(XEvent *e);
152 void killclient(const char *arg);
153 void leavenotify(XEvent *e);
154 void manage(Window w, XWindowAttributes *wa);
155 void mappingnotify(XEvent *e);
156 void maprequest(XEvent *e);
157 void movemouse(Client *c);
158 Client *nexttiled(Client *c);
159 void propertynotify(XEvent *e);
160 void quit(const char *arg);
161 void resize(Client *c, int x, int y, int w, int h, Bool sizehints);
162 void resizemouse(Client *c);
166 void setclientstate(Client *c, long state);
167 void setlayout(const char *arg);
168 void setmwfact(const char *arg);
170 void spawn(const char *arg);
171 void tag(const char *arg);
172 unsigned int textnw(const char *text, unsigned int len);
173 unsigned int textw(const char *text);
175 void togglebar(const char *arg);
176 void togglefloating(const char *arg);
177 void togglemax(const char *arg);
178 void toggletag(const char *arg);
179 void toggleview(const char *arg);
180 void unban(Client *c);
181 void unmanage(Client *c);
182 void unmapnotify(XEvent *e);
183 void updatebarpos(void);
184 void updatesizehints(Client *c);
185 void updatetitle(Client *c);
186 void view(const char *arg);
187 int xerror(Display *dpy, XErrorEvent *ee);
188 int xerrordummy(Display *dsply, XErrorEvent *ee);
189 int xerrorstart(Display *dsply, XErrorEvent *ee);
190 void zoom(const char *arg);
195 int screen, sx, sy, sw, sh, wax, way, waw, wah;
196 int (*xerrorxlib)(Display *, XErrorEvent *);
197 unsigned int bh, bpos, ntags;
198 unsigned int blw = 0;
199 unsigned int ltidx = 0; /* default */
200 unsigned int nlayouts = 0;
201 unsigned int nrules = 0;
202 unsigned int numlockmask = 0;
203 void (*handler[LASTEvent]) (XEvent *) = {
204 [ButtonPress] = buttonpress,
205 [ConfigureRequest] = configurerequest,
206 [ConfigureNotify] = configurenotify,
207 [DestroyNotify] = destroynotify,
208 [EnterNotify] = enternotify,
209 [LeaveNotify] = leavenotify,
211 [KeyPress] = keypress,
212 [MappingNotify] = mappingnotify,
213 [MapRequest] = maprequest,
214 [PropertyNotify] = propertynotify,
215 [UnmapNotify] = unmapnotify
217 Atom wmatom[WMLast], netatom[NetLast];
218 Bool otherwm, readin;
221 Bool selscreen = True;
222 Client *clients = NULL;
224 Client *stack = NULL;
225 Cursor cursor[CurLast];
231 /* configuration, allows nested code to access above variables */
236 applyrules(Client *c) {
237 static char buf[512];
240 Bool matched = False;
241 XClassHint ch = { 0 };
244 XGetClassHint(dpy, c->win, &ch);
245 snprintf(buf, sizeof buf, "%s:%s:%s",
246 ch.res_class ? ch.res_class : "",
247 ch.res_name ? ch.res_name : "", c->name);
248 for(i = 0; i < nrules; i++)
249 if(regs[i].propregex && !regexec(regs[i].propregex, buf, 1, &tmp, 0)) {
250 c->isfloating = rules[i].isfloating;
251 for(j = 0; regs[i].tagregex && j < ntags; j++) {
252 if(!regexec(regs[i].tagregex, tags[j], 1, &tmp, 0)) {
263 for(i = 0; i < ntags; i++)
264 c->tags[i] = seltags[i];
271 for(c = clients; c; c = c->next)
276 layouts[ltidx].arrange();
290 attachstack(Client *c) {
299 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
304 buttonpress(XEvent *e) {
307 XButtonPressedEvent *ev = &e->xbutton;
309 if(barwin == ev->window) {
311 for(i = 0; i < ntags; i++) {
314 if(ev->button == Button1) {
315 if(ev->state & MODKEY)
320 else if(ev->button == Button3) {
321 if(ev->state & MODKEY)
329 if((ev->x < x + blw) && ev->button == Button1)
332 else if((c = getclient(ev->window))) {
334 if(CLEANMASK(ev->state) != MODKEY)
336 if(ev->button == Button1) {
337 if(isarrange(floating) || c->isfloating)
340 togglefloating(NULL);
343 else if(ev->button == Button2) {
344 if(isarrange(tile) && !c->isfixed && c->isfloating)
345 togglefloating(NULL);
349 else if(ev->button == Button3 && !c->isfixed) {
350 if(isarrange(floating) || c->isfloating)
353 togglefloating(NULL);
362 XSetErrorHandler(xerrorstart);
364 /* this causes an error if some other window manager is running */
365 XSelectInput(dpy, root, SubstructureRedirectMask);
368 eprint("dwm: another window manager is already running\n");
370 XSetErrorHandler(NULL);
371 xerrorxlib = XSetErrorHandler(xerror);
383 XFreeFontSet(dpy, dc.font.set);
385 XFreeFont(dpy, dc.font.xfont);
386 XUngrabKey(dpy, AnyKey, AnyModifier, root);
387 XFreePixmap(dpy, dc.drawable);
389 XDestroyWindow(dpy, barwin);
390 XFreeCursor(dpy, cursor[CurNormal]);
391 XFreeCursor(dpy, cursor[CurResize]);
392 XFreeCursor(dpy, cursor[CurMove]);
393 XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime);
405 nrules = sizeof rules / sizeof rules[0];
406 regs = emallocz(nrules * sizeof(Regs));
407 for(i = 0; i < nrules; i++) {
409 reg = emallocz(sizeof(regex_t));
410 if(regcomp(reg, rules[i].prop, REG_EXTENDED))
413 regs[i].propregex = reg;
416 reg = emallocz(sizeof(regex_t));
417 if(regcomp(reg, rules[i].tags, REG_EXTENDED))
420 regs[i].tagregex = reg;
426 configure(Client *c) {
429 ce.type = ConfigureNotify;
437 ce.border_width = c->border;
439 ce.override_redirect = False;
440 XSendEvent(dpy, c->win, False, StructureNotifyMask, (XEvent *)&ce);
444 configurenotify(XEvent *e) {
445 XConfigureEvent *ev = &e->xconfigure;
447 if(ev->window == root && (ev->width != sw || ev->height != sh)) {
450 XFreePixmap(dpy, dc.drawable);
451 dc.drawable = XCreatePixmap(dpy, root, sw, bh, DefaultDepth(dpy, screen));
452 XResizeWindow(dpy, barwin, sw, bh);
459 configurerequest(XEvent *e) {
461 XConfigureRequestEvent *ev = &e->xconfigurerequest;
464 if((c = getclient(ev->window))) {
466 if(ev->value_mask & CWBorderWidth)
467 c->border = ev->border_width;
468 if(c->isfixed || c->isfloating || isarrange(floating)) {
469 if(ev->value_mask & CWX)
471 if(ev->value_mask & CWY)
473 if(ev->value_mask & CWWidth)
475 if(ev->value_mask & CWHeight)
477 if((c->x + c->w) > sw && c->isfloating)
478 c->x = sw / 2 - c->w / 2; /* center in x direction */
479 if((c->y + c->h) > sh && c->isfloating)
480 c->y = sh / 2 - c->h / 2; /* center in y direction */
481 if((ev->value_mask & (CWX | CWY))
482 && !(ev->value_mask & (CWWidth | CWHeight)))
485 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h);
493 wc.width = ev->width;
494 wc.height = ev->height;
495 wc.border_width = ev->border_width;
496 wc.sibling = ev->above;
497 wc.stack_mode = ev->detail;
498 XConfigureWindow(dpy, ev->window, ev->value_mask, &wc);
504 destroynotify(XEvent *e) {
506 XDestroyWindowEvent *ev = &e->xdestroywindow;
508 if((c = getclient(ev->window)))
515 c->prev->next = c->next;
517 c->next->prev = c->prev;
520 c->next = c->prev = NULL;
524 detachstack(Client *c) {
527 for(tc=&stack; *tc && *tc != c; tc=&(*tc)->snext);
536 for(i = 0; i < ntags; i++) {
537 dc.w = textw(tags[i]);
539 drawtext(tags[i], dc.sel);
540 drawsquare(sel && sel->tags[i], isoccupied(i), dc.sel);
543 drawtext(tags[i], dc.norm);
544 drawsquare(sel && sel->tags[i], isoccupied(i), dc.norm);
549 drawtext(layouts[ltidx].symbol, dc.norm);
557 drawtext(stext, dc.norm);
558 if((dc.w = dc.x - x) > bh) {
561 drawtext(sel->name, dc.sel);
562 drawsquare(sel->ismax, sel->isfloating, dc.sel);
565 drawtext(NULL, dc.norm);
567 XCopyArea(dpy, dc.drawable, barwin, dc.gc, 0, 0, sw, bh, 0, 0);
572 drawsquare(Bool filled, Bool empty, unsigned long col[ColLast]) {
575 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
577 gcv.foreground = col[ColFG];
578 XChangeGC(dpy, dc.gc, GCForeground, &gcv);
579 x = (dc.font.ascent + dc.font.descent + 2) / 4;
583 r.width = r.height = x + 1;
584 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
587 r.width = r.height = x;
588 XDrawRectangles(dpy, dc.drawable, dc.gc, &r, 1);
593 drawtext(const char *text, unsigned long col[ColLast]) {
595 static char buf[256];
596 unsigned int len, olen;
597 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
599 XSetForeground(dpy, dc.gc, col[ColBG]);
600 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
604 olen = len = strlen(text);
605 if(len >= sizeof buf)
606 len = sizeof buf - 1;
607 memcpy(buf, text, len);
609 h = dc.font.ascent + dc.font.descent;
610 y = dc.y + (dc.h / 2) - (h / 2) + dc.font.ascent;
612 /* shorten text if necessary */
613 while(len && (w = textnw(buf, len)) > dc.w - h)
624 return; /* too long */
625 XSetForeground(dpy, dc.gc, col[ColFG]);
627 XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
629 XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
633 emallocz(unsigned int size) {
634 void *res = calloc(1, size);
637 eprint("fatal: could not malloc() %u bytes\n", size);
642 enternotify(XEvent *e) {
644 XCrossingEvent *ev = &e->xcrossing;
646 if(ev->mode != NotifyNormal || ev->detail == NotifyInferior)
648 if((c = getclient(ev->window)))
650 else if(ev->window == root) {
657 eprint(const char *errstr, ...) {
660 va_start(ap, errstr);
661 vfprintf(stderr, errstr, ap);
668 XExposeEvent *ev = &e->xexpose;
671 if(barwin == ev->window)
677 floating(void) { /* default floating layout */
680 for(c = clients; c; c = c->next)
682 resize(c, c->x, c->y, c->w, c->h, True);
687 if((!c && selscreen) || (c && !isvisible(c)))
688 for(c = stack; c && !isvisible(c); c = c->snext);
689 if(sel && sel != c) {
690 grabbuttons(sel, False);
691 XSetWindowBorder(dpy, sel->win, dc.norm[ColBorder]);
696 grabbuttons(c, True);
703 XSetWindowBorder(dpy, c->win, dc.sel[ColBorder]);
704 XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
707 XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
711 focusnext(const char *arg) {
716 for(c = sel->next; c && !isvisible(c); c = c->next);
718 for(c = clients; c && !isvisible(c); c = c->next);
726 focusprev(const char *arg) {
731 for(c = sel->prev; c && !isvisible(c); c = c->prev);
733 for(c = clients; c && c->next; c = c->next);
734 for(; c && !isvisible(c); c = c->prev);
743 getclient(Window w) {
746 for(c = clients; c && c->win != w; c = c->next);
751 getcolor(const char *colstr) {
752 Colormap cmap = DefaultColormap(dpy, screen);
755 if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
756 eprint("error, cannot allocate color '%s'\n", colstr);
764 unsigned char *p = NULL;
765 unsigned long n, extra;
768 status = XGetWindowProperty(dpy, w, wmatom[WMState], 0L, 2L, False, wmatom[WMState],
769 &real, &format, &n, &extra, (unsigned char **)&p);
770 if(status != Success)
779 gettextprop(Window w, Atom atom, char *text, unsigned int size) {
784 if(!text || size == 0)
787 XGetTextProperty(dpy, w, &name, atom);
790 if(name.encoding == XA_STRING)
791 strncpy(text, (char *)name.value, size - 1);
793 if(XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success
796 strncpy(text, *list, size - 1);
797 XFreeStringList(list);
800 text[size - 1] = '\0';
806 grabbuttons(Client *c, Bool focused) {
807 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
810 XGrabButton(dpy, Button1, MODKEY, c->win, False, BUTTONMASK,
811 GrabModeAsync, GrabModeSync, None, None);
812 XGrabButton(dpy, Button1, MODKEY | LockMask, c->win, False, BUTTONMASK,
813 GrabModeAsync, GrabModeSync, None, None);
814 XGrabButton(dpy, Button1, MODKEY | numlockmask, c->win, False, BUTTONMASK,
815 GrabModeAsync, GrabModeSync, None, None);
816 XGrabButton(dpy, Button1, MODKEY | numlockmask | LockMask, c->win, False, BUTTONMASK,
817 GrabModeAsync, GrabModeSync, None, None);
819 XGrabButton(dpy, Button2, MODKEY, c->win, False, BUTTONMASK,
820 GrabModeAsync, GrabModeSync, None, None);
821 XGrabButton(dpy, Button2, MODKEY | LockMask, c->win, False, BUTTONMASK,
822 GrabModeAsync, GrabModeSync, None, None);
823 XGrabButton(dpy, Button2, MODKEY | numlockmask, c->win, False, BUTTONMASK,
824 GrabModeAsync, GrabModeSync, None, None);
825 XGrabButton(dpy, Button2, MODKEY | numlockmask | LockMask, c->win, False, BUTTONMASK,
826 GrabModeAsync, GrabModeSync, None, None);
828 XGrabButton(dpy, Button3, MODKEY, c->win, False, BUTTONMASK,
829 GrabModeAsync, GrabModeSync, None, None);
830 XGrabButton(dpy, Button3, MODKEY | LockMask, c->win, False, BUTTONMASK,
831 GrabModeAsync, GrabModeSync, None, None);
832 XGrabButton(dpy, Button3, MODKEY | numlockmask, c->win, False, BUTTONMASK,
833 GrabModeAsync, GrabModeSync, None, None);
834 XGrabButton(dpy, Button3, MODKEY | numlockmask | LockMask, c->win, False, BUTTONMASK,
835 GrabModeAsync, GrabModeSync, None, None);
838 XGrabButton(dpy, AnyButton, AnyModifier, c->win, False, BUTTONMASK,
839 GrabModeAsync, GrabModeSync, None, None);
843 idxoftag(const char *tag) {
846 for(i = 0; i < ntags; i++)
853 initfont(const char *fontstr) {
854 char *def, **missing;
859 XFreeFontSet(dpy, dc.font.set);
860 dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
863 fprintf(stderr, "dwm: missing fontset: %s\n", missing[n]);
864 XFreeStringList(missing);
867 XFontSetExtents *font_extents;
868 XFontStruct **xfonts;
870 dc.font.ascent = dc.font.descent = 0;
871 font_extents = XExtentsOfFontSet(dc.font.set);
872 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
873 for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
874 if(dc.font.ascent < (*xfonts)->ascent)
875 dc.font.ascent = (*xfonts)->ascent;
876 if(dc.font.descent < (*xfonts)->descent)
877 dc.font.descent = (*xfonts)->descent;
883 XFreeFont(dpy, dc.font.xfont);
884 dc.font.xfont = NULL;
885 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr))
886 && !(dc.font.xfont = XLoadQueryFont(dpy, "fixed")))
887 eprint("error, cannot load font: '%s'\n", fontstr);
888 dc.font.ascent = dc.font.xfont->ascent;
889 dc.font.descent = dc.font.xfont->descent;
891 dc.font.height = dc.font.ascent + dc.font.descent;
895 isarrange(void (*func)())
897 return func == layouts[ltidx].arrange;
901 isoccupied(unsigned int t) {
904 for(c = clients; c; c = c->next)
911 isprotodel(Client *c) {
916 if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
917 for(i = 0; !ret && i < n; i++)
918 if(protocols[i] == wmatom[WMDelete])
926 isvisible(Client *c) {
929 for(i = 0; i < ntags; i++)
930 if(c->tags[i] && seltags[i])
936 keypress(XEvent *e) {
938 unsigned int len = sizeof keys / sizeof keys[0];
944 if(!e) { /* grabkeys */
945 XUngrabKey(dpy, AnyKey, AnyModifier, root);
946 for(i = 0; i < len; i++) {
947 code = XKeysymToKeycode(dpy, keys[i].keysym);
948 XGrabKey(dpy, code, keys[i].mod, root, True,
949 GrabModeAsync, GrabModeAsync);
950 XGrabKey(dpy, code, keys[i].mod | LockMask, root, True,
951 GrabModeAsync, GrabModeAsync);
952 XGrabKey(dpy, code, keys[i].mod | numlockmask, root, True,
953 GrabModeAsync, GrabModeAsync);
954 XGrabKey(dpy, code, keys[i].mod | numlockmask | LockMask, root, True,
955 GrabModeAsync, GrabModeAsync);
960 keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
961 for(i = 0; i < len; i++)
962 if(keysym == keys[i].keysym
963 && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state))
966 keys[i].func(keys[i].arg);
971 killclient(const char *arg) {
976 if(isprotodel(sel)) {
977 ev.type = ClientMessage;
978 ev.xclient.window = sel->win;
979 ev.xclient.message_type = wmatom[WMProtocols];
980 ev.xclient.format = 32;
981 ev.xclient.data.l[0] = wmatom[WMDelete];
982 ev.xclient.data.l[1] = CurrentTime;
983 XSendEvent(dpy, sel->win, False, NoEventMask, &ev);
986 XKillClient(dpy, sel->win);
990 leavenotify(XEvent *e) {
991 XCrossingEvent *ev = &e->xcrossing;
993 if((ev->window == root) && !ev->same_screen) {
1000 manage(Window w, XWindowAttributes *wa) {
1002 Client *c, *t = NULL;
1007 c = emallocz(sizeof(Client));
1008 c->tags = emallocz(ntags * sizeof(Bool));
1014 c->oldborder = wa->border_width;
1015 if(c->w == sw && c->h == sh) {
1018 c->border = wa->border_width;
1021 if(c->x + c->w + 2 * c->border > wax + waw)
1022 c->x = wax + waw - c->w - 2 * c->border;
1023 if(c->y + c->h + 2 * c->border > way + wah)
1024 c->y = way + wah - c->h - 2 * c->border;
1029 c->border = BORDERPX;
1031 wc.border_width = c->border;
1032 XConfigureWindow(dpy, w, CWBorderWidth, &wc);
1033 XSetWindowBorder(dpy, w, dc.norm[ColBorder]);
1034 configure(c); /* propagates border_width, if size doesn't change */
1036 XSelectInput(dpy, w,
1037 StructureNotifyMask | PropertyChangeMask | EnterWindowMask);
1038 grabbuttons(c, False);
1040 if((rettrans = XGetTransientForHint(dpy, w, &trans) == Success))
1041 for(t = clients; t && t->win != trans; t = t->next);
1043 for(i = 0; i < ntags; i++)
1044 c->tags[i] = t->tags[i];
1047 c->isfloating = (rettrans == Success) || c->isfixed;
1050 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h); /* some windows require this */
1052 XMapWindow(dpy, c->win);
1053 setclientstate(c, NormalState);
1058 mappingnotify(XEvent *e) {
1059 XMappingEvent *ev = &e->xmapping;
1061 XRefreshKeyboardMapping(ev);
1062 if(ev->request == MappingKeyboard)
1067 maprequest(XEvent *e) {
1068 static XWindowAttributes wa;
1069 XMapRequestEvent *ev = &e->xmaprequest;
1071 if(!XGetWindowAttributes(dpy, ev->window, &wa))
1073 if(wa.override_redirect)
1075 if(!getclient(ev->window))
1076 manage(ev->window, &wa);
1080 movemouse(Client *c) {
1081 int x1, y1, ocx, ocy, di, nx, ny;
1088 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1089 None, cursor[CurMove], CurrentTime) != GrabSuccess)
1092 XQueryPointer(dpy, root, &dummy, &dummy, &x1, &y1, &di, &di, &dui);
1094 XMaskEvent(dpy, MOUSEMASK | ExposureMask | SubstructureRedirectMask, &ev);
1097 XUngrabPointer(dpy, CurrentTime);
1099 case ConfigureRequest:
1102 handler[ev.type](&ev);
1106 nx = ocx + (ev.xmotion.x - x1);
1107 ny = ocy + (ev.xmotion.y - y1);
1108 if(abs(wax + nx) < SNAP)
1110 else if(abs((wax + waw) - (nx + c->w + 2 * c->border)) < SNAP)
1111 nx = wax + waw - c->w - 2 * c->border;
1112 if(abs(way - ny) < SNAP)
1114 else if(abs((way + wah) - (ny + c->h + 2 * c->border)) < SNAP)
1115 ny = way + wah - c->h - 2 * c->border;
1116 resize(c, nx, ny, c->w, c->h, False);
1123 nexttiled(Client *c) {
1124 for(; c && (c->isfloating || !isvisible(c)); c = c->next);
1129 propertynotify(XEvent *e) {
1132 XPropertyEvent *ev = &e->xproperty;
1134 if(ev->state == PropertyDelete)
1135 return; /* ignore */
1136 if((c = getclient(ev->window))) {
1139 case XA_WM_TRANSIENT_FOR:
1140 XGetTransientForHint(dpy, c->win, &trans);
1141 if(!c->isfloating && (c->isfloating = (getclient(trans) != NULL)))
1144 case XA_WM_NORMAL_HINTS:
1148 if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
1157 quit(const char *arg) {
1158 readin = running = False;
1162 resize(Client *c, int x, int y, int w, int h, Bool sizehints) {
1163 double dx, dy, max, min, ratio;
1167 if(c->minay > 0 && c->maxay > 0 && (h - c->baseh) > 0 && (w - c->basew) > 0) {
1168 dx = (double)(w - c->basew);
1169 dy = (double)(h - c->baseh);
1170 min = (double)(c->minax) / (double)(c->minay);
1171 max = (double)(c->maxax) / (double)(c->maxay);
1173 if(max > 0 && min > 0 && ratio > 0) {
1175 dy = (dx * min + dy) / (min * min + 1);
1177 w = (int)dx + c->basew;
1178 h = (int)dy + c->baseh;
1180 else if(ratio > max) {
1181 dy = (dx * min + dy) / (max * max + 1);
1183 w = (int)dx + c->basew;
1184 h = (int)dy + c->baseh;
1188 if(c->minw && w < c->minw)
1190 if(c->minh && h < c->minh)
1192 if(c->maxw && w > c->maxw)
1194 if(c->maxh && h > c->maxh)
1197 w -= (w - c->basew) % c->incw;
1199 h -= (h - c->baseh) % c->inch;
1201 if(w <= 0 || h <= 0)
1203 /* offscreen appearance fixes */
1205 x = sw - w - 2 * c->border;
1207 y = sh - h - 2 * c->border;
1208 if(x + w + 2 * c->border < sx)
1210 if(y + h + 2 * c->border < sy)
1212 if(c->x != x || c->y != y || c->w != w || c->h != h) {
1215 c->w = wc.width = w;
1216 c->h = wc.height = h;
1217 wc.border_width = c->border;
1218 XConfigureWindow(dpy, c->win, CWX | CWY | CWWidth | CWHeight | CWBorderWidth, &wc);
1225 resizemouse(Client *c) {
1232 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1233 None, cursor[CurResize], CurrentTime) != GrabSuccess)
1236 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->border - 1, c->h + c->border - 1);
1238 XMaskEvent(dpy, MOUSEMASK | ExposureMask | SubstructureRedirectMask , &ev);
1241 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0,
1242 c->w + c->border - 1, c->h + c->border - 1);
1243 XUngrabPointer(dpy, CurrentTime);
1244 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1246 case ConfigureRequest:
1249 handler[ev.type](&ev);
1253 if((nw = ev.xmotion.x - ocx - 2 * c->border + 1) <= 0)
1255 if((nh = ev.xmotion.y - ocy - 2 * c->border + 1) <= 0)
1257 resize(c, c->x, c->y, nw, nh, True);
1272 if(sel->isfloating || isarrange(floating))
1273 XRaiseWindow(dpy, sel->win);
1274 if(!isarrange(floating)) {
1275 wc.stack_mode = Below;
1276 wc.sibling = barwin;
1277 if(!sel->isfloating) {
1278 XConfigureWindow(dpy, sel->win, CWSibling | CWStackMode, &wc);
1279 wc.sibling = sel->win;
1281 for(c = nexttiled(clients); c; c = nexttiled(c->next)) {
1284 XConfigureWindow(dpy, c->win, CWSibling | CWStackMode, &wc);
1285 wc.sibling = c->win;
1289 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1299 /* main event loop, also reads status text from stdin */
1301 xfd = ConnectionNumber(dpy);
1306 FD_SET(STDIN_FILENO, &rd);
1308 if(select(xfd + 1, &rd, NULL, NULL, NULL) == -1) {
1311 eprint("select failed\n");
1313 if(FD_ISSET(STDIN_FILENO, &rd)) {
1314 switch(r = read(STDIN_FILENO, stext, sizeof stext - 1)) {
1316 strncpy(stext, strerror(errno), sizeof stext - 1);
1317 stext[sizeof stext - 1] = '\0';
1321 strncpy(stext, "EOF", 4);
1325 for(stext[r] = '\0', p = stext + strlen(stext) - 1; p >= stext && *p == '\n'; *p-- = '\0');
1326 for(; p >= stext && *p != '\n'; --p);
1328 strncpy(stext, p + 1, sizeof stext);
1332 while(XPending(dpy)) {
1333 XNextEvent(dpy, &ev);
1334 if(handler[ev.type])
1335 (handler[ev.type])(&ev); /* call handler */
1342 unsigned int i, num;
1343 Window *wins, d1, d2;
1344 XWindowAttributes wa;
1347 if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1348 for(i = 0; i < num; i++) {
1349 if(!XGetWindowAttributes(dpy, wins[i], &wa)
1350 || wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1352 if(wa.map_state == IsViewable || getstate(wins[i]) == IconicState)
1353 manage(wins[i], &wa);
1355 for(i = 0; i < num; i++) { /* now the transients */
1356 if(!XGetWindowAttributes(dpy, wins[i], &wa))
1358 if(XGetTransientForHint(dpy, wins[i], &d1)
1359 && (wa.map_state == IsViewable || getstate(wins[i]) == IconicState))
1360 manage(wins[i], &wa);
1368 setclientstate(Client *c, long state) {
1369 long data[] = {state, None};
1371 XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1372 PropModeReplace, (unsigned char *)data, 2);
1376 setlayout(const char *arg) {
1380 if(++ltidx == nlayouts)
1384 for(i = 0; i < nlayouts; i++)
1385 if(!strcmp(arg, layouts[i].symbol))
1398 setmwfact(const char *arg) {
1401 if(!isarrange(tile))
1403 /* arg handling, manipulate mwfact */
1406 else if(1 == sscanf(arg, "%lf", &delta)) {
1407 if(arg[0] == '+' || arg[0] == '-')
1413 else if(mwfact > 0.9)
1421 unsigned int i, j, mask;
1423 XModifierKeymap *modmap;
1424 XSetWindowAttributes wa;
1427 wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1428 wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1429 wmatom[WMName] = XInternAtom(dpy, "WM_NAME", False);
1430 wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1431 netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1432 netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1433 XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1434 PropModeReplace, (unsigned char *) netatom, NetLast);
1437 cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1438 cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1439 cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1443 sw = DisplayWidth(dpy, screen);
1444 sh = DisplayHeight(dpy, screen);
1446 /* init modifier map */
1447 modmap = XGetModifierMapping(dpy);
1448 for(i = 0; i < 8; i++)
1449 for(j = 0; j < modmap->max_keypermod; j++) {
1450 if(modmap->modifiermap[i * modmap->max_keypermod + j]
1451 == XKeysymToKeycode(dpy, XK_Num_Lock))
1452 numlockmask = (1 << i);
1454 XFreeModifiermap(modmap);
1456 /* select for events */
1457 wa.event_mask = SubstructureRedirectMask | SubstructureNotifyMask
1458 | EnterWindowMask | LeaveWindowMask | StructureNotifyMask;
1459 wa.cursor = cursor[CurNormal];
1460 XChangeWindowAttributes(dpy, root, CWEventMask | CWCursor, &wa);
1461 XSelectInput(dpy, root, wa.event_mask);
1468 for(ntags = 0; tags[ntags]; ntags++);
1469 seltags = emallocz(sizeof(Bool) * ntags);
1472 /* init appearance */
1473 dc.norm[ColBorder] = getcolor(NORMBORDERCOLOR);
1474 dc.norm[ColBG] = getcolor(NORMBGCOLOR);
1475 dc.norm[ColFG] = getcolor(NORMFGCOLOR);
1476 dc.sel[ColBorder] = getcolor(SELBORDERCOLOR);
1477 dc.sel[ColBG] = getcolor(SELBGCOLOR);
1478 dc.sel[ColFG] = getcolor(SELFGCOLOR);
1480 dc.h = bh = dc.font.height + 2;
1484 nlayouts = sizeof layouts / sizeof layouts[0];
1485 for(blw = i = 0; i < nlayouts; i++) {
1486 j = textw(layouts[i].symbol);
1493 wa.override_redirect = 1;
1494 wa.background_pixmap = ParentRelative;
1495 wa.event_mask = ButtonPressMask | ExposureMask;
1496 barwin = XCreateWindow(dpy, root, sx, sy, sw, bh, 0,
1497 DefaultDepth(dpy, screen), CopyFromParent, DefaultVisual(dpy, screen),
1498 CWOverrideRedirect | CWBackPixmap | CWEventMask, &wa);
1499 XDefineCursor(dpy, barwin, cursor[CurNormal]);
1501 XMapRaised(dpy, barwin);
1502 strcpy(stext, "dwm-"VERSION);
1503 dc.drawable = XCreatePixmap(dpy, root, sw, bh, DefaultDepth(dpy, screen));
1504 dc.gc = XCreateGC(dpy, root, 0, 0);
1505 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
1507 XSetFont(dpy, dc.gc, dc.font.xfont->fid);
1509 /* multihead support */
1510 selscreen = XQueryPointer(dpy, root, &w, &w, &i, &i, &i, &i, &mask);
1514 spawn(const char *arg) {
1515 static char *shell = NULL;
1517 if(!shell && !(shell = getenv("SHELL")))
1521 /* The double-fork construct avoids zombie processes and keeps the code
1522 * clean from stupid signal handlers. */
1526 close(ConnectionNumber(dpy));
1528 execl(shell, shell, "-c", arg, (char *)NULL);
1529 fprintf(stderr, "dwm: execl '%s -c %s'", shell, arg);
1538 tag(const char *arg) {
1543 for(i = 0; i < ntags; i++)
1544 sel->tags[i] = arg == NULL;
1546 if(i >= 0 && i < ntags)
1547 sel->tags[i] = True;
1552 textnw(const char *text, unsigned int len) {
1556 XmbTextExtents(dc.font.set, text, len, NULL, &r);
1559 return XTextWidth(dc.font.xfont, text, len);
1563 textw(const char *text) {
1564 return textnw(text, strlen(text)) + dc.font.height;
1569 unsigned int i, n, nx, ny, nw, nh, mw, th;
1572 for(n = 0, c = nexttiled(clients); c; c = nexttiled(c->next))
1576 mw = (n == 1) ? waw : mwfact * waw;
1577 th = (n > 1) ? wah / (n - 1) : 0;
1578 if(n > 1 && th < bh)
1583 for(i = 0, c = nexttiled(clients); c; c = nexttiled(c->next), i++) {
1585 if(i == 0) { /* master */
1586 nw = mw - 2 * c->border;
1587 nh = wah - 2 * c->border;
1589 else { /* tile window */
1594 nw = waw - mw - 2 * c->border;
1595 if(i + 1 == n) /* remainder */
1596 nh = (way + wah) - ny - 2 * c->border;
1598 nh = th - 2 * c->border;
1600 resize(c, nx, ny, nw, nh, RESIZEHINTS);
1601 if(n > 1 && th != wah)
1602 ny += nh + 2 * c->border;
1607 togglebar(const char *arg) {
1609 bpos = (BARPOS == BarOff) ? BarTop : BARPOS;
1617 togglefloating(const char *arg) {
1620 sel->isfloating = !sel->isfloating;
1622 resize(sel, sel->x, sel->y, sel->w, sel->h, True);
1627 togglemax(const char *arg) {
1630 if(!sel || sel->isfixed)
1632 if((sel->ismax = !sel->ismax)) {
1633 if(isarrange(floating) || sel->isfloating)
1634 sel->wasfloating = True;
1636 togglefloating(NULL);
1637 sel->wasfloating = False;
1643 resize(sel, wax, way, waw - 2 * sel->border, wah - 2 * sel->border, True);
1646 resize(sel, sel->rx, sel->ry, sel->rw, sel->rh, True);
1647 if(!sel->wasfloating)
1648 togglefloating(NULL);
1651 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1655 toggletag(const char *arg) {
1661 sel->tags[i] = !sel->tags[i];
1662 for(j = 0; j < ntags && !sel->tags[j]; j++);
1664 sel->tags[i] = True;
1669 toggleview(const char *arg) {
1673 seltags[i] = !seltags[i];
1674 for(j = 0; j < ntags && !seltags[j]; j++);
1676 seltags[i] = True; /* at least one tag must be viewed */
1684 XMoveWindow(dpy, c->win, c->x, c->y);
1685 c->isbanned = False;
1689 unmanage(Client *c) {
1692 wc.border_width = c->oldborder;
1693 /* The server grab construct avoids race conditions. */
1695 XSetErrorHandler(xerrordummy);
1696 XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
1701 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1702 setclientstate(c, WithdrawnState);
1706 XSetErrorHandler(xerror);
1712 unmapnotify(XEvent *e) {
1714 XUnmapEvent *ev = &e->xunmap;
1716 if((c = getclient(ev->window)))
1721 updatebarpos(void) {
1732 XMoveWindow(dpy, barwin, sx, sy);
1736 XMoveWindow(dpy, barwin, sx, sy + wah);
1739 XMoveWindow(dpy, barwin, sx, sy - bh);
1743 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1747 updatesizehints(Client *c) {
1751 if(!XGetWMNormalHints(dpy, c->win, &size, &msize) || !size.flags)
1753 c->flags = size.flags;
1754 if(c->flags & PBaseSize) {
1755 c->basew = size.base_width;
1756 c->baseh = size.base_height;
1758 else if(c->flags & PMinSize) {
1759 c->basew = size.min_width;
1760 c->baseh = size.min_height;
1763 c->basew = c->baseh = 0;
1764 if(c->flags & PResizeInc) {
1765 c->incw = size.width_inc;
1766 c->inch = size.height_inc;
1769 c->incw = c->inch = 0;
1770 if(c->flags & PMaxSize) {
1771 c->maxw = size.max_width;
1772 c->maxh = size.max_height;
1775 c->maxw = c->maxh = 0;
1776 if(c->flags & PMinSize) {
1777 c->minw = size.min_width;
1778 c->minh = size.min_height;
1780 else if(c->flags & PBaseSize) {
1781 c->minw = size.base_width;
1782 c->minh = size.base_height;
1785 c->minw = c->minh = 0;
1786 if(c->flags & PAspect) {
1787 c->minax = size.min_aspect.x;
1788 c->maxax = size.max_aspect.x;
1789 c->minay = size.min_aspect.y;
1790 c->maxay = size.max_aspect.y;
1793 c->minax = c->maxax = c->minay = c->maxay = 0;
1794 c->isfixed = (c->maxw && c->minw && c->maxh && c->minh
1795 && c->maxw == c->minw && c->maxh == c->minh);
1799 updatetitle(Client *c) {
1800 if(!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
1801 gettextprop(c->win, wmatom[WMName], c->name, sizeof c->name);
1804 /* There's no way to check accesses to destroyed windows, thus those cases are
1805 * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
1806 * default error handler, which may call exit. */
1808 xerror(Display *dpy, XErrorEvent *ee) {
1809 if(ee->error_code == BadWindow
1810 || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1811 || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1812 || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1813 || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1814 || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1815 || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1816 || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1818 fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1819 ee->request_code, ee->error_code);
1820 return xerrorxlib(dpy, ee); /* may call exit */
1824 xerrordummy(Display *dsply, XErrorEvent *ee) {
1828 /* Startup Error handler to check if another window manager
1829 * is already running. */
1831 xerrorstart(Display *dsply, XErrorEvent *ee) {
1837 view(const char *arg) {
1840 for(i = 0; i < ntags; i++)
1841 seltags[i] = arg == NULL;
1843 if(i >= 0 && i < ntags)
1849 zoom(const char *arg) {
1852 if(!sel || !isarrange(tile) || sel->isfloating)
1854 if((c = sel) == nexttiled(clients))
1855 if(!(c = nexttiled(c->next)))
1864 main(int argc, char *argv[]) {
1865 if(argc == 2 && !strcmp("-v", argv[1]))
1866 eprint("dwm-"VERSION", © 2006-2007 A. R. Garbe, S. van Dijk, J. Salmi, P. Hruby, S. Nagy\n");
1868 eprint("usage: dwm [-v]\n");
1870 setlocale(LC_CTYPE, "");
1871 if(!(dpy = XOpenDisplay(0)))
1872 eprint("dwm: cannot open display\n");
1873 screen = DefaultScreen(dpy);
1874 root = RootWindow(dpy, screen);