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.
22 * Keys and tagging rules are organized as arrays and defined in config.h.
24 * To understand everything else, start reading main().
33 #include <sys/select.h>
34 #include <sys/types.h>
36 #include <X11/cursorfont.h>
37 #include <X11/keysym.h>
38 #include <X11/Xatom.h>
40 #include <X11/Xproto.h>
41 #include <X11/Xutil.h>
43 #include <X11/extensions/Xinerama.h>
47 #define MAX(a, b) ((a) > (b) ? (a) : (b))
48 #define MIN(a, b) ((a) < (b) ? (a) : (b))
49 #define BUTTONMASK (ButtonPressMask|ButtonReleaseMask)
50 #define CLEANMASK(mask) (mask & ~(numlockmask|LockMask))
51 #define LENGTH(x) (sizeof x / sizeof x[0])
53 #define MOUSEMASK (BUTTONMASK|PointerMotionMask)
54 #define TAGMASK ((int)((1LL << LENGTH(tags)) - 1))
55 #define VISIBLE(x) ((x)->tags & tagset[seltags])
58 enum { CurNormal, CurResize, CurMove, CurLast }; /* cursor */
59 enum { ColBorder, ColFG, ColBG, ColLast }; /* color */
60 enum { NetSupported, NetWMName, NetLast }; /* EWMH atoms */
61 enum { WMProtocols, WMDelete, WMName, WMState, WMLast };/* default atoms */
64 typedef unsigned int uint;
65 typedef unsigned long ulong;
66 typedef struct Client Client;
70 int basew, baseh, incw, inch, maxw, maxh, minw, minh;
71 int minax, maxax, minay, maxay;
74 Bool isbanned, isfixed, isfloating, isurgent;
95 } DC; /* draw context */
100 void (*func)(const void *arg);
106 void (*arrange)(void);
107 void (*updategeom)(void);
112 const char *instance;
118 /* function declarations */
119 void applyrules(Client *c);
121 void attach(Client *c);
122 void attachstack(Client *c);
124 void buttonpress(XEvent *e);
125 void checkotherwm(void);
127 void configure(Client *c);
128 void configurenotify(XEvent *e);
129 void configurerequest(XEvent *e);
130 void destroynotify(XEvent *e);
131 void detach(Client *c);
132 void detachstack(Client *c);
134 void drawsquare(Bool filled, Bool empty, Bool invert, ulong col[ColLast]);
135 void drawtext(const char *text, ulong col[ColLast], Bool invert);
136 void enternotify(XEvent *e);
137 void eprint(const char *errstr, ...);
138 void expose(XEvent *e);
139 void focus(Client *c);
140 void focusin(XEvent *e);
141 void focusnext(const void *arg);
142 void focusprev(const void *arg);
143 Client *getclient(Window w);
144 ulong getcolor(const char *colstr);
145 long getstate(Window w);
146 Bool gettextprop(Window w, Atom atom, char *text, uint size);
147 void grabbuttons(Client *c, Bool focused);
149 void initfont(const char *fontstr);
150 Bool isoccupied(uint t);
151 Bool isprotodel(Client *c);
152 Bool isurgent(uint t);
153 void keypress(XEvent *e);
154 void killclient(const void *arg);
155 void manage(Window w, XWindowAttributes *wa);
156 void mappingnotify(XEvent *e);
157 void maprequest(XEvent *e);
158 void movemouse(Client *c);
159 Client *nexttiled(Client *c);
160 void propertynotify(XEvent *e);
161 void quit(const void *arg);
162 void resize(Client *c, int x, int y, int w, int h, Bool sizehints);
163 void resizemouse(Client *c);
167 void setclientstate(Client *c, long state);
168 void setmfact(const void *arg);
170 void spawn(const void *arg);
171 void tag(const void *arg);
172 uint textnw(const char *text, uint len);
173 uint textw(const char *text);
175 void tileresize(Client *c, int x, int y, int w, int h);
176 void togglebar(const void *arg);
177 void togglefloating(const void *arg);
178 void togglelayout(const void *arg);
179 void toggletag(const void *arg);
180 void toggleview(const void *arg);
181 void unban(Client *c);
182 void unmanage(Client *c);
183 void unmapnotify(XEvent *e);
184 void updatebar(void);
185 void updategeom(void);
186 void updatesizehints(Client *c);
187 void updatetilegeom(void);
188 void updatetitle(Client *c);
189 void updatewmhints(Client *c);
190 void view(const void *arg);
191 void viewprevtag(const void *arg);
192 int xerror(Display *dpy, XErrorEvent *ee);
193 int xerrordummy(Display *dpy, XErrorEvent *ee);
194 int xerrorstart(Display *dpy, XErrorEvent *ee);
195 void zoom(const void *arg);
199 int screen, sx, sy, sw, sh;
200 int bx, by, bw, bh, blw, wx, wy, ww, wh;
201 int mx, my, mw, mh, tx, ty, tw, th;
203 int (*xerrorxlib)(Display *, XErrorEvent *);
204 uint numlockmask = 0;
205 void (*handler[LASTEvent]) (XEvent *) = {
206 [ButtonPress] = buttonpress,
207 [ConfigureRequest] = configurerequest,
208 [ConfigureNotify] = configurenotify,
209 [DestroyNotify] = destroynotify,
210 [EnterNotify] = enternotify,
213 [KeyPress] = keypress,
214 [MappingNotify] = mappingnotify,
215 [MapRequest] = maprequest,
216 [PropertyNotify] = propertynotify,
217 [UnmapNotify] = unmapnotify
219 Atom wmatom[WMLast], netatom[NetLast];
220 Bool otherwm, readin;
222 uint tagset[] = {1, 1}; /* after start, first tag is selected */
223 Client *clients = NULL;
225 Client *stack = NULL;
226 Cursor cursor[CurLast];
230 Layout *lt = layouts;
233 /* configuration, allows nested code to access above variables */
236 /* compile-time check if all tags fit into an uint bit array. */
237 struct NumTags { char limitexceeded[sizeof(uint) * 8 < LENGTH(tags) ? -1 : 1]; };
239 /* function implementations */
241 applyrules(Client *c) {
244 XClassHint ch = { 0 };
247 XGetClassHint(dpy, c->win, &ch);
248 for(i = 0; i < LENGTH(rules); i++) {
250 if((!r->title || strstr(c->name, r->title))
251 && (!r->class || (ch.res_class && strstr(ch.res_class, r->class)))
252 && (!r->instance || (ch.res_name && strstr(ch.res_name, r->instance)))) {
253 c->isfloating = r->isfloating;
254 c->tags |= r->tags & TAGMASK;
262 c->tags = tagset[seltags];
269 for(c = clients; c; c = c->next)
272 if(!lt->arrange || c->isfloating)
273 resize(c, c->x, c->y, c->w, c->h, True);
293 attachstack(Client *c) {
302 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
307 buttonpress(XEvent *e) {
310 XButtonPressedEvent *ev = &e->xbutton;
312 if(ev->window == barwin) {
314 for(i = 0; i < LENGTH(tags); i++) {
318 if(ev->button == Button1) {
319 if(ev->state & MODKEY)
324 else if(ev->button == Button3) {
325 if(ev->state & MODKEY)
333 if((ev->x < x + blw) && ev->button == Button1)
336 else if((c = getclient(ev->window))) {
338 if(CLEANMASK(ev->state) != MODKEY)
340 if(ev->button == Button1) {
344 else if(ev->button == Button2)
345 togglefloating(NULL);
346 else if(ev->button == Button3 && !c->isfixed) {
356 XSetErrorHandler(xerrorstart);
358 /* this causes an error if some other window manager is running */
359 XSelectInput(dpy, DefaultRootWindow(dpy), SubstructureRedirectMask);
362 eprint("dwm: another window manager is already running\n");
364 XSetErrorHandler(NULL);
365 xerrorxlib = XSetErrorHandler(xerror);
377 XFreeFontSet(dpy, dc.font.set);
379 XFreeFont(dpy, dc.font.xfont);
380 XUngrabKey(dpy, AnyKey, AnyModifier, root);
381 XFreePixmap(dpy, dc.drawable);
383 XFreeCursor(dpy, cursor[CurNormal]);
384 XFreeCursor(dpy, cursor[CurResize]);
385 XFreeCursor(dpy, cursor[CurMove]);
386 XDestroyWindow(dpy, barwin);
388 XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime);
392 configure(Client *c) {
395 ce.type = ConfigureNotify;
403 ce.border_width = c->bw;
405 ce.override_redirect = False;
406 XSendEvent(dpy, c->win, False, StructureNotifyMask, (XEvent *)&ce);
410 configurenotify(XEvent *e) {
411 XConfigureEvent *ev = &e->xconfigure;
413 if(ev->window == root && (ev->width != sw || ev->height != sh)) {
423 configurerequest(XEvent *e) {
425 XConfigureRequestEvent *ev = &e->xconfigurerequest;
428 if((c = getclient(ev->window))) {
429 if(ev->value_mask & CWBorderWidth)
430 c->bw = ev->border_width;
431 if(c->isfixed || c->isfloating || !lt->arrange) {
432 if(ev->value_mask & CWX)
434 if(ev->value_mask & CWY)
436 if(ev->value_mask & CWWidth)
438 if(ev->value_mask & CWHeight)
440 if((c->x - sx + c->w) > sw && c->isfloating)
441 c->x = sx + (sw / 2 - c->w / 2); /* center in x direction */
442 if((c->y - sy + c->h) > sh && c->isfloating)
443 c->y = sy + (sh / 2 - c->h / 2); /* center in y direction */
444 if((ev->value_mask & (CWX|CWY))
445 && !(ev->value_mask & (CWWidth|CWHeight)))
448 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h);
456 wc.width = ev->width;
457 wc.height = ev->height;
458 wc.border_width = ev->border_width;
459 wc.sibling = ev->above;
460 wc.stack_mode = ev->detail;
461 XConfigureWindow(dpy, ev->window, ev->value_mask, &wc);
467 destroynotify(XEvent *e) {
469 XDestroyWindowEvent *ev = &e->xdestroywindow;
471 if((c = getclient(ev->window)))
478 c->prev->next = c->next;
480 c->next->prev = c->prev;
483 c->next = c->prev = NULL;
487 detachstack(Client *c) {
490 for(tc = &stack; *tc && *tc != c; tc = &(*tc)->snext);
500 for(c = stack; c && !VISIBLE(c); c = c->snext);
501 for(i = 0; i < LENGTH(tags); i++) {
502 dc.w = textw(tags[i]);
503 if(tagset[seltags] & 1 << i) {
504 drawtext(tags[i], dc.sel, isurgent(i));
505 drawsquare(c && c->tags & 1 << i, isoccupied(i), isurgent(i), dc.sel);
508 drawtext(tags[i], dc.norm, isurgent(i));
509 drawsquare(c && c->tags & 1 << i, isoccupied(i), isurgent(i), dc.norm);
515 drawtext(lt->symbol, dc.norm, False);
526 drawtext(stext, dc.norm, False);
527 if((dc.w = dc.x - x) > bh) {
530 drawtext(c->name, dc.sel, False);
531 drawsquare(False, c->isfloating, False, dc.sel);
534 drawtext(NULL, dc.norm, False);
536 XCopyArea(dpy, dc.drawable, barwin, dc.gc, 0, 0, bw, bh, 0, 0);
541 drawsquare(Bool filled, Bool empty, Bool invert, ulong col[ColLast]) {
544 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
546 gcv.foreground = col[invert ? ColBG : ColFG];
547 XChangeGC(dpy, dc.gc, GCForeground, &gcv);
548 x = (dc.font.ascent + dc.font.descent + 2) / 4;
552 r.width = r.height = x + 1;
553 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
556 r.width = r.height = x;
557 XDrawRectangles(dpy, dc.drawable, dc.gc, &r, 1);
562 drawtext(const char *text, ulong col[ColLast], Bool invert) {
565 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
568 XSetForeground(dpy, dc.gc, col[invert ? ColFG : ColBG]);
569 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
573 len = MIN(olen, sizeof buf);
574 memcpy(buf, text, len);
576 h = dc.font.ascent + dc.font.descent;
577 y = dc.y + (dc.h / 2) - (h / 2) + dc.font.ascent;
579 /* shorten text if necessary */
580 for(; len && (w = textnw(buf, len)) > dc.w - h; len--);
591 XSetForeground(dpy, dc.gc, col[invert ? ColBG : ColFG]);
593 XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
595 XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
599 enternotify(XEvent *e) {
601 XCrossingEvent *ev = &e->xcrossing;
603 if((ev->mode != NotifyNormal || ev->detail == NotifyInferior) && ev->window != root)
605 if((c = getclient(ev->window)))
612 eprint(const char *errstr, ...) {
615 va_start(ap, errstr);
616 vfprintf(stderr, errstr, ap);
623 XExposeEvent *ev = &e->xexpose;
625 if(ev->count == 0 && (ev->window == barwin))
631 if(!c || (c && !VISIBLE(c)))
632 for(c = stack; c && !VISIBLE(c); c = c->snext);
633 if(sel && sel != c) {
634 grabbuttons(sel, False);
635 XSetWindowBorder(dpy, sel->win, dc.norm[ColBorder]);
640 grabbuttons(c, True);
644 XSetWindowBorder(dpy, c->win, dc.sel[ColBorder]);
645 XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
648 XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
653 focusin(XEvent *e) { /* there are some broken focus acquiring clients */
654 XFocusChangeEvent *ev = &e->xfocus;
656 if(sel && ev->window != sel->win)
657 XSetInputFocus(dpy, sel->win, RevertToPointerRoot, CurrentTime);
661 focusnext(const void *arg) {
666 for(c = sel->next; c && !VISIBLE(c); c = c->next);
668 for(c = clients; c && !VISIBLE(c); c = c->next);
676 focusprev(const void *arg) {
681 for(c = sel->prev; c && !VISIBLE(c); c = c->prev);
683 for(c = clients; c && c->next; c = c->next);
684 for(; c && !VISIBLE(c); c = c->prev);
693 getclient(Window w) {
696 for(c = clients; c && c->win != w; c = c->next);
701 getcolor(const char *colstr) {
702 Colormap cmap = DefaultColormap(dpy, screen);
705 if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
706 eprint("error, cannot allocate color '%s'\n", colstr);
714 unsigned char *p = NULL;
718 status = XGetWindowProperty(dpy, w, wmatom[WMState], 0L, 2L, False, wmatom[WMState],
719 &real, &format, &n, &extra, (unsigned char **)&p);
720 if(status != Success)
729 gettextprop(Window w, Atom atom, char *text, uint size) {
734 if(!text || size == 0)
737 XGetTextProperty(dpy, w, &name, atom);
740 if(name.encoding == XA_STRING)
741 strncpy(text, (char *)name.value, size - 1);
743 if(XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success
745 strncpy(text, *list, size - 1);
746 XFreeStringList(list);
749 text[size - 1] = '\0';
755 grabbuttons(Client *c, Bool focused) {
757 uint buttons[] = { Button1, Button2, Button3 };
758 uint modifiers[] = { MODKEY, MODKEY|LockMask, MODKEY|numlockmask,
759 MODKEY|numlockmask|LockMask} ;
761 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
763 for(i = 0; i < LENGTH(buttons); i++)
764 for(j = 0; j < LENGTH(modifiers); j++)
765 XGrabButton(dpy, buttons[i], modifiers[j], c->win, False,
766 BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
768 XGrabButton(dpy, AnyButton, AnyModifier, c->win, False,
769 BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
776 XModifierKeymap *modmap;
778 /* init modifier map */
779 modmap = XGetModifierMapping(dpy);
780 for(i = 0; i < 8; i++)
781 for(j = 0; j < modmap->max_keypermod; j++) {
782 if(modmap->modifiermap[i * modmap->max_keypermod + j] == XKeysymToKeycode(dpy, XK_Num_Lock))
783 numlockmask = (1 << i);
785 XFreeModifiermap(modmap);
787 XUngrabKey(dpy, AnyKey, AnyModifier, root);
788 for(i = 0; i < LENGTH(keys); i++) {
789 code = XKeysymToKeycode(dpy, keys[i].keysym);
790 XGrabKey(dpy, code, keys[i].mod, root, True,
791 GrabModeAsync, GrabModeAsync);
792 XGrabKey(dpy, code, keys[i].mod|LockMask, root, True,
793 GrabModeAsync, GrabModeAsync);
794 XGrabKey(dpy, code, keys[i].mod|numlockmask, root, True,
795 GrabModeAsync, GrabModeAsync);
796 XGrabKey(dpy, code, keys[i].mod|numlockmask|LockMask, root, True,
797 GrabModeAsync, GrabModeAsync);
802 initfont(const char *fontstr) {
803 char *def, **missing;
808 XFreeFontSet(dpy, dc.font.set);
809 dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
812 fprintf(stderr, "dwm: missing fontset: %s\n", missing[n]);
813 XFreeStringList(missing);
816 XFontSetExtents *font_extents;
817 XFontStruct **xfonts;
819 dc.font.ascent = dc.font.descent = 0;
820 font_extents = XExtentsOfFontSet(dc.font.set);
821 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
822 for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
823 dc.font.ascent = MAX(dc.font.ascent, (*xfonts)->ascent);
824 dc.font.descent = MAX(dc.font.descent,(*xfonts)->descent);
830 XFreeFont(dpy, dc.font.xfont);
831 dc.font.xfont = NULL;
832 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr))
833 && !(dc.font.xfont = XLoadQueryFont(dpy, "fixed")))
834 eprint("error, cannot load font: '%s'\n", fontstr);
835 dc.font.ascent = dc.font.xfont->ascent;
836 dc.font.descent = dc.font.xfont->descent;
838 dc.font.height = dc.font.ascent + dc.font.descent;
845 for(c = clients; c; c = c->next)
852 isprotodel(Client *c) {
857 if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
858 for(i = 0; !ret && i < n; i++)
859 if(protocols[i] == wmatom[WMDelete])
870 for(c = clients; c; c = c->next)
871 if(c->isurgent && c->tags & 1 << t)
877 keypress(XEvent *e) {
883 keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
884 for(i = 0; i < LENGTH(keys); i++)
885 if(keysym == keys[i].keysym
886 && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state))
889 keys[i].func(keys[i].arg);
894 killclient(const void *arg) {
899 if(isprotodel(sel)) {
900 ev.type = ClientMessage;
901 ev.xclient.window = sel->win;
902 ev.xclient.message_type = wmatom[WMProtocols];
903 ev.xclient.format = 32;
904 ev.xclient.data.l[0] = wmatom[WMDelete];
905 ev.xclient.data.l[1] = CurrentTime;
906 XSendEvent(dpy, sel->win, False, NoEventMask, &ev);
909 XKillClient(dpy, sel->win);
913 manage(Window w, XWindowAttributes *wa) {
914 Client *c, *t = NULL;
919 if(!(c = calloc(1, sizeof(Client))))
920 eprint("fatal: could not calloc() %u bytes\n", sizeof(Client));
928 c->oldbw = wa->border_width;
929 if(c->w == sw && c->h == sh) {
932 c->bw = wa->border_width;
935 if(c->x + c->w + 2 * c->bw > sx + sw)
936 c->x = sx + sw - c->w - 2 * c->bw;
937 if(c->y + c->h + 2 * c->bw > sy + sh)
938 c->y = sy + sh - c->h - 2 * c->bw;
939 c->x = MAX(c->x, sx);
940 c->y = MAX(c->y, by == 0 ? bh : sy);
944 wc.border_width = c->bw;
945 XConfigureWindow(dpy, w, CWBorderWidth, &wc);
946 XSetWindowBorder(dpy, w, dc.norm[ColBorder]);
947 configure(c); /* propagates border_width, if size doesn't change */
949 XSelectInput(dpy, w, EnterWindowMask|FocusChangeMask|PropertyChangeMask|StructureNotifyMask);
950 grabbuttons(c, False);
952 if((rettrans = XGetTransientForHint(dpy, w, &trans) == Success))
953 for(t = clients; t && t->win != trans; t = t->next);
959 c->isfloating = (rettrans == Success) || c->isfixed;
962 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h); /* some windows require this */
964 XMapWindow(dpy, c->win);
965 setclientstate(c, NormalState);
970 mappingnotify(XEvent *e) {
971 XMappingEvent *ev = &e->xmapping;
973 XRefreshKeyboardMapping(ev);
974 if(ev->request == MappingKeyboard)
979 maprequest(XEvent *e) {
980 static XWindowAttributes wa;
981 XMapRequestEvent *ev = &e->xmaprequest;
983 if(!XGetWindowAttributes(dpy, ev->window, &wa))
985 if(wa.override_redirect)
987 if(!getclient(ev->window))
988 manage(ev->window, &wa);
992 movemouse(Client *c) {
993 int x1, y1, ocx, ocy, di, nx, ny;
1000 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1001 None, cursor[CurMove], CurrentTime) != GrabSuccess)
1003 XQueryPointer(dpy, root, &dummy, &dummy, &x1, &y1, &di, &di, &dui);
1005 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
1008 XUngrabPointer(dpy, CurrentTime);
1010 case ConfigureRequest:
1013 handler[ev.type](&ev);
1017 nx = ocx + (ev.xmotion.x - x1);
1018 ny = ocy + (ev.xmotion.y - y1);
1019 if(snap && nx >= wx && nx <= wx + ww
1020 && ny >= wy && ny <= wy + wh) {
1021 if(abs(wx - nx) < snap)
1023 else if(abs((wx + ww) - (nx + c->w + 2 * c->bw)) < snap)
1024 nx = wx + ww - c->w - 2 * c->bw;
1025 if(abs(wy - ny) < snap)
1027 else if(abs((wy + wh) - (ny + c->h + 2 * c->bw)) < snap)
1028 ny = wy + wh - c->h - 2 * c->bw;
1029 if(!c->isfloating && lt->arrange && (abs(nx - c->x) > snap || abs(ny - c->y) > snap))
1030 togglefloating(NULL);
1032 if(!lt->arrange || c->isfloating)
1033 resize(c, nx, ny, c->w, c->h, False);
1040 nexttiled(Client *c) {
1041 for(; c && (c->isfloating || !VISIBLE(c)); c = c->next);
1046 propertynotify(XEvent *e) {
1049 XPropertyEvent *ev = &e->xproperty;
1051 if(ev->state == PropertyDelete)
1052 return; /* ignore */
1053 if((c = getclient(ev->window))) {
1056 case XA_WM_TRANSIENT_FOR:
1057 XGetTransientForHint(dpy, c->win, &trans);
1058 if(!c->isfloating && (c->isfloating = (getclient(trans) != NULL)))
1061 case XA_WM_NORMAL_HINTS:
1069 if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
1078 quit(const void *arg) {
1079 readin = running = False;
1083 resize(Client *c, int x, int y, int w, int h, Bool sizehints) {
1087 /* set minimum possible */
1091 /* temporarily remove base dimensions */
1095 /* adjust for aspect limits */
1096 if(c->minax != c->maxax && c->minay != c->maxay
1097 && c->minax > 0 && c->maxax > 0 && c->minay > 0 && c->maxay > 0) {
1098 if(w * c->maxay > h * c->maxax)
1099 w = h * c->maxax / c->maxay;
1100 else if(w * c->minay < h * c->minax)
1101 h = w * c->minay / c->minax;
1104 /* adjust for increment value */
1110 /* restore base dimensions */
1114 w = MAX(w, c->minw);
1115 h = MAX(h, c->minh);
1118 w = MIN(w, c->maxw);
1121 h = MIN(h, c->maxh);
1123 if(w <= 0 || h <= 0)
1126 x = sw - w - 2 * c->bw;
1128 y = sh - h - 2 * c->bw;
1129 if(x + w + 2 * c->bw < sx)
1131 if(y + h + 2 * c->bw < sy)
1133 if(c->x != x || c->y != y || c->w != w || c->h != h) {
1136 c->w = wc.width = w;
1137 c->h = wc.height = h;
1138 wc.border_width = c->bw;
1139 XConfigureWindow(dpy, c->win,
1140 CWX|CWY|CWWidth|CWHeight|CWBorderWidth, &wc);
1147 resizemouse(Client *c) {
1154 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1155 None, cursor[CurResize], CurrentTime) != GrabSuccess)
1157 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->bw - 1, c->h + c->bw - 1);
1159 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask , &ev);
1162 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0,
1163 c->w + c->bw - 1, c->h + c->bw - 1);
1164 XUngrabPointer(dpy, CurrentTime);
1165 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1167 case ConfigureRequest:
1170 handler[ev.type](&ev);
1174 nw = MAX(ev.xmotion.x - ocx - 2 * c->bw + 1, 1);
1175 nh = MAX(ev.xmotion.y - ocy - 2 * c->bw + 1, 1);
1177 if(snap && nw >= wx && nw <= wx + ww
1178 && nh >= wy && nh <= wy + wh) {
1179 if(!c->isfloating && lt->arrange
1180 && (abs(nw - c->w) > snap || abs(nh - c->h) > snap))
1181 togglefloating(NULL);
1183 if(!lt->arrange || c->isfloating)
1184 resize(c, c->x, c->y, nw, nh, True);
1199 if(sel->isfloating || !lt->arrange)
1200 XRaiseWindow(dpy, sel->win);
1202 wc.stack_mode = Below;
1203 wc.sibling = barwin;
1204 for(c = stack; c; c = c->snext)
1205 if(!c->isfloating && VISIBLE(c)) {
1206 XConfigureWindow(dpy, c->win, CWSibling|CWStackMode, &wc);
1207 wc.sibling = c->win;
1211 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1217 char sbuf[sizeof stext];
1223 /* main event loop, also reads status text from stdin */
1225 xfd = ConnectionNumber(dpy);
1228 len = sizeof stext - 1;
1229 sbuf[len] = stext[len] = '\0'; /* 0-terminator is never touched */
1233 FD_SET(STDIN_FILENO, &rd);
1235 if(select(xfd + 1, &rd, NULL, NULL, NULL) == -1) {
1238 eprint("select failed\n");
1240 if(FD_ISSET(STDIN_FILENO, &rd)) {
1241 switch((r = read(STDIN_FILENO, sbuf + offset, len - offset))) {
1243 strncpy(stext, strerror(errno), len);
1247 strncpy(stext, "EOF", 4);
1251 for(p = sbuf + offset; r > 0; p++, r--, offset++)
1252 if(*p == '\n' || *p == '\0') {
1254 strncpy(stext, sbuf, len);
1255 p += r - 1; /* p is sbuf + offset + r - 1 */
1256 for(r = 0; *(p - r) && *(p - r) != '\n'; r++);
1259 memmove(sbuf, p - r + 1, r);
1266 while(XPending(dpy)) {
1267 XNextEvent(dpy, &ev);
1268 if(handler[ev.type])
1269 (handler[ev.type])(&ev); /* call handler */
1277 Window *wins, d1, d2;
1278 XWindowAttributes wa;
1281 if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1282 for(i = 0; i < num; i++) {
1283 if(!XGetWindowAttributes(dpy, wins[i], &wa)
1284 || wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1286 if(wa.map_state == IsViewable || getstate(wins[i]) == IconicState)
1287 manage(wins[i], &wa);
1289 for(i = 0; i < num; i++) { /* now the transients */
1290 if(!XGetWindowAttributes(dpy, wins[i], &wa))
1292 if(XGetTransientForHint(dpy, wins[i], &d1)
1293 && (wa.map_state == IsViewable || getstate(wins[i]) == IconicState))
1294 manage(wins[i], &wa);
1302 setclientstate(Client *c, long state) {
1303 long data[] = {state, None};
1305 XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1306 PropModeReplace, (unsigned char *)data, 2);
1309 /* arg > 1.0 will set mfact absolutly */
1311 setmfact(const void *arg) {
1312 double d = *((double*) arg);
1314 if(!d || lt->arrange != tile)
1316 d = d < 1.0 ? d + mfact : d - 1.0;
1317 if(d < 0.1 || d > 0.9)
1327 XSetWindowAttributes wa;
1330 screen = DefaultScreen(dpy);
1331 root = RootWindow(dpy, screen);
1335 sw = DisplayWidth(dpy, screen);
1336 sh = DisplayHeight(dpy, screen);
1337 bh = dc.font.height + 2;
1341 wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1342 wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1343 wmatom[WMName] = XInternAtom(dpy, "WM_NAME", False);
1344 wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1345 netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1346 netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1349 wa.cursor = cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1350 cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1351 cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1353 /* init appearance */
1354 dc.norm[ColBorder] = getcolor(NORMBORDERCOLOR);
1355 dc.norm[ColBG] = getcolor(NORMBGCOLOR);
1356 dc.norm[ColFG] = getcolor(NORMFGCOLOR);
1357 dc.sel[ColBorder] = getcolor(SELBORDERCOLOR);
1358 dc.sel[ColBG] = getcolor(SELBGCOLOR);
1359 dc.sel[ColFG] = getcolor(SELFGCOLOR);
1362 dc.drawable = XCreatePixmap(dpy, root, DisplayWidth(dpy, screen), bh, DefaultDepth(dpy, screen));
1363 dc.gc = XCreateGC(dpy, root, 0, 0);
1364 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
1366 XSetFont(dpy, dc.gc, dc.font.xfont->fid);
1369 for(blw = i = 0; LENGTH(layouts) > 1 && i < LENGTH(layouts); i++) {
1370 w = textw(layouts[i].symbol);
1374 wa.override_redirect = 1;
1375 wa.background_pixmap = ParentRelative;
1376 wa.event_mask = ButtonPressMask|ExposureMask;
1378 barwin = XCreateWindow(dpy, root, bx, by, bw, bh, 0, DefaultDepth(dpy, screen),
1379 CopyFromParent, DefaultVisual(dpy, screen),
1380 CWOverrideRedirect|CWBackPixmap|CWEventMask, &wa);
1381 XDefineCursor(dpy, barwin, cursor[CurNormal]);
1382 XMapRaised(dpy, barwin);
1383 strcpy(stext, "dwm-"VERSION);
1386 /* EWMH support per view */
1387 XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1388 PropModeReplace, (unsigned char *) netatom, NetLast);
1390 /* select for events */
1391 wa.event_mask = SubstructureRedirectMask|SubstructureNotifyMask
1392 |EnterWindowMask|LeaveWindowMask|StructureNotifyMask;
1393 XChangeWindowAttributes(dpy, root, CWEventMask|CWCursor, &wa);
1394 XSelectInput(dpy, root, wa.event_mask);
1402 spawn(const void *arg) {
1403 static char *shell = NULL;
1405 if(!shell && !(shell = getenv("SHELL")))
1407 /* The double-fork construct avoids zombie processes and keeps the code
1408 * clean from stupid signal handlers. */
1412 close(ConnectionNumber(dpy));
1414 execl(shell, shell, "-c", (char *)arg, (char *)NULL);
1415 fprintf(stderr, "dwm: execl '%s -c %s'", shell, (char *)arg);
1424 tag(const void *arg) {
1425 if(sel && *(int *)arg & TAGMASK) {
1426 sel->tags = *(int *)arg & TAGMASK;
1432 textnw(const char *text, uint len) {
1436 XmbTextExtents(dc.font.set, text, len, NULL, &r);
1439 return XTextWidth(dc.font.xfont, text, len);
1443 textw(const char *text) {
1444 return textnw(text, strlen(text)) + dc.font.height;
1453 for(n = 0, c = nexttiled(clients); c; c = nexttiled(c->next), n++);
1458 c = nexttiled(clients);
1461 tileresize(c, wx, wy, ww - 2 * c->bw, wh - 2 * c->bw);
1463 tileresize(c, mx, my, mw - 2 * c->bw, mh - 2 * c->bw);
1469 x = (tx > c->x + c->w) ? c->x + c->w + 2 * c->bw : tw;
1471 w = (tx > c->x + c->w) ? wx + ww - x : tw;
1476 for(i = 0, c = nexttiled(c->next); c; c = nexttiled(c->next), i++) {
1477 if(i + 1 == n) /* remainder */
1478 tileresize(c, x, y, w - 2 * c->bw, (ty + th) - y - 2 * c->bw);
1480 tileresize(c, x, y, w - 2 * c->bw, h - 2 * c->bw);
1482 y = c->y + c->h + 2 * c->bw;
1487 tileresize(Client *c, int x, int y, int w, int h) {
1488 resize(c, x, y, w, h, resizehints);
1489 if(resizehints && ((c->h < bh) || (c->h > h) || (c->w < bh) || (c->w > w)))
1490 /* client doesn't accept size constraints */
1491 resize(c, x, y, w, h, False);
1495 togglebar(const void *arg) {
1503 togglefloating(const void *arg) {
1506 sel->isfloating = !sel->isfloating;
1508 resize(sel, sel->x, sel->y, sel->w, sel->h, True);
1513 togglelayout(const void *arg) {
1517 if(++lt == &layouts[LENGTH(layouts)])
1521 for(i = 0; i < LENGTH(layouts); i++)
1522 if(!strcmp((char *)arg, layouts[i].symbol))
1524 if(i == LENGTH(layouts))
1535 toggletag(const void *arg) {
1536 if(sel && (sel->tags ^ ((*(int *)arg) & TAGMASK))) {
1537 sel->tags ^= (*(int *)arg) & TAGMASK;
1543 toggleview(const void *arg) {
1544 if((tagset[seltags] ^ ((*(int *)arg) & TAGMASK))) {
1545 tagset[seltags] ^= (*(int *)arg) & TAGMASK;
1554 XMoveWindow(dpy, c->win, c->x, c->y);
1555 c->isbanned = False;
1559 unmanage(Client *c) {
1562 wc.border_width = c->oldbw;
1563 /* The server grab construct avoids race conditions. */
1565 XSetErrorHandler(xerrordummy);
1566 XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
1571 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1572 setclientstate(c, WithdrawnState);
1575 XSetErrorHandler(xerror);
1581 unmapnotify(XEvent *e) {
1583 XUnmapEvent *ev = &e->xunmap;
1585 if((c = getclient(ev->window)))
1591 if(dc.drawable != 0)
1592 XFreePixmap(dpy, dc.drawable);
1593 dc.drawable = XCreatePixmap(dpy, root, bw, bh, DefaultDepth(dpy, screen));
1594 XMoveResizeWindow(dpy, barwin, bx, by, bw, bh);
1601 XineramaScreenInfo *info = NULL;
1603 /* window area geometry */
1604 if(XineramaIsActive(dpy)) {
1605 info = XineramaQueryScreens(dpy, &i);
1607 wy = showbar && topbar ? info[0].y_org + bh : info[0].y_org;
1609 wh = showbar ? info[0].height - bh : info[0].height;
1616 wy = showbar && topbar ? sy + bh : sy;
1618 wh = showbar ? sh - bh : sh;
1623 by = showbar ? (topbar ? wy - bh : wy + wh) : -bh;
1626 /* update layout geometries */
1627 for(i = 0; i < LENGTH(layouts); i++)
1628 if(layouts[i].updategeom)
1629 layouts[i].updategeom();
1633 updatesizehints(Client *c) {
1637 if(!XGetWMNormalHints(dpy, c->win, &size, &msize) || !size.flags)
1639 c->flags = size.flags;
1640 if(c->flags & PBaseSize) {
1641 c->basew = size.base_width;
1642 c->baseh = size.base_height;
1644 else if(c->flags & PMinSize) {
1645 c->basew = size.min_width;
1646 c->baseh = size.min_height;
1649 c->basew = c->baseh = 0;
1650 if(c->flags & PResizeInc) {
1651 c->incw = size.width_inc;
1652 c->inch = size.height_inc;
1655 c->incw = c->inch = 0;
1656 if(c->flags & PMaxSize) {
1657 c->maxw = size.max_width;
1658 c->maxh = size.max_height;
1661 c->maxw = c->maxh = 0;
1662 if(c->flags & PMinSize) {
1663 c->minw = size.min_width;
1664 c->minh = size.min_height;
1666 else if(c->flags & PBaseSize) {
1667 c->minw = size.base_width;
1668 c->minh = size.base_height;
1671 c->minw = c->minh = 0;
1672 if(c->flags & PAspect) {
1673 c->minax = size.min_aspect.x;
1674 c->maxax = size.max_aspect.x;
1675 c->minay = size.min_aspect.y;
1676 c->maxay = size.max_aspect.y;
1679 c->minax = c->maxax = c->minay = c->maxay = 0;
1680 c->isfixed = (c->maxw && c->minw && c->maxh && c->minh
1681 && c->maxw == c->minw && c->maxh == c->minh);
1685 updatetilegeom(void) {
1686 /* master area geometry */
1692 /* tile area geometry */
1700 updatetitle(Client *c) {
1701 if(!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
1702 gettextprop(c->win, wmatom[WMName], c->name, sizeof c->name);
1706 updatewmhints(Client *c) {
1709 if((wmh = XGetWMHints(dpy, c->win))) {
1711 sel->isurgent = False;
1713 c->isurgent = (wmh->flags & XUrgencyHint) ? True : False;
1719 view(const void *arg) {
1720 if(*(int *)arg & TAGMASK) {
1721 seltags ^= 1; /* toggle sel tagset */
1722 tagset[seltags] = *(int *)arg & TAGMASK;
1728 viewprevtag(const void *arg) {
1729 seltags ^= 1; /* toggle sel tagset */
1733 /* There's no way to check accesses to destroyed windows, thus those cases are
1734 * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
1735 * default error handler, which may call exit. */
1737 xerror(Display *dpy, XErrorEvent *ee) {
1738 if(ee->error_code == BadWindow
1739 || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1740 || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1741 || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1742 || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1743 || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1744 || (ee->request_code == X_GrabButton && ee->error_code == BadAccess)
1745 || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1746 || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1748 fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1749 ee->request_code, ee->error_code);
1750 return xerrorxlib(dpy, ee); /* may call exit */
1754 xerrordummy(Display *dpy, XErrorEvent *ee) {
1758 /* Startup Error handler to check if another window manager
1759 * is already running. */
1761 xerrorstart(Display *dpy, XErrorEvent *ee) {
1767 zoom(const void *arg) {
1770 if(!lt->arrange || sel->isfloating)
1772 if(c == nexttiled(clients))
1773 if(!c || !(c = nexttiled(c->next)))
1782 main(int argc, char *argv[]) {
1783 if(argc == 2 && !strcmp("-v", argv[1]))
1784 eprint("dwm-"VERSION", © 2006-2008 dwm engineers, see LICENSE for details\n");
1786 eprint("usage: dwm [-v]\n");
1788 setlocale(LC_CTYPE, "");
1789 if(!(dpy = XOpenDisplay(0)))
1790 eprint("dwm: cannot open display\n");