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 TEXTW(x) (textnw(x, strlen(x)) + dc.font.height)
56 #define VISIBLE(x) ((x)->tags & tagset[seltags])
59 enum { CurNormal, CurResize, CurMove, CurLast }; /* cursor */
60 enum { ColBorder, ColFG, ColBG, ColLast }; /* color */
61 enum { NetSupported, NetWMName, NetLast }; /* EWMH atoms */
62 enum { WMProtocols, WMDelete, WMName, WMState, WMLast };/* default atoms */
65 typedef unsigned int uint;
66 typedef unsigned long ulong;
67 typedef struct Client Client;
71 int basew, baseh, incw, inch, maxw, maxh, minw, minh;
72 int minax, maxax, minay, maxay;
75 Bool isbanned, isfixed, isfloating, ismax, isurgent;
96 } DC; /* draw context */
101 void (*func)(const void *arg);
107 void (*arrange)(void);
112 const char *instance;
118 /* function declarations */
119 void applyrules(Client *c);
121 void attach(Client *c);
122 void attachstack(Client *c);
123 void buttonpress(XEvent *e);
124 void checkotherwm(void);
126 void configure(Client *c);
127 void configurenotify(XEvent *e);
128 void configurerequest(XEvent *e);
129 void destroynotify(XEvent *e);
130 void detach(Client *c);
131 void detachstack(Client *c);
133 void drawsquare(Bool filled, Bool empty, Bool invert, ulong col[ColLast]);
134 void drawtext(const char *text, ulong col[ColLast], Bool invert);
135 void enternotify(XEvent *e);
136 void eprint(const char *errstr, ...);
137 void expose(XEvent *e);
138 void focus(Client *c);
139 void focusin(XEvent *e);
140 void focusnext(const void *arg);
141 void focusprev(const void *arg);
142 Client *getclient(Window w);
143 ulong getcolor(const char *colstr);
144 long getstate(Window w);
145 Bool gettextprop(Window w, Atom atom, char *text, uint size);
146 void grabbuttons(Client *c, Bool focused);
148 void initfont(const char *fontstr);
149 Bool isoccupied(uint t);
150 Bool isprotodel(Client *c);
151 Bool isurgent(uint t);
152 void keypress(XEvent *e);
153 void killclient(const void *arg);
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 void *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 setmfact(const void *arg);
169 void spawn(const void *arg);
170 void tag(const void *arg);
171 uint textnw(const char *text, uint len);
173 void togglebar(const void *arg);
174 void togglefloating(const void *arg);
175 void togglelayout(const void *arg);
176 void togglemax(const void *arg);
177 void toggletag(const void *arg);
178 void toggleview(const void *arg);
179 void unmanage(Client *c);
180 void unmapnotify(XEvent *e);
181 void updatebar(void);
182 void updategeom(void);
183 void updatesizehints(Client *c);
184 void updatetitle(Client *c);
185 void updatewmhints(Client *c);
186 void view(const void *arg);
187 void viewprevtag(const void *arg);
188 int xerror(Display *dpy, XErrorEvent *ee);
189 int xerrordummy(Display *dpy, XErrorEvent *ee);
190 int xerrorstart(Display *dpy, XErrorEvent *ee);
191 void zoom(const void *arg);
195 int screen, sx, sy, sw, sh;
196 int bx, by, bw, bh, blw, wx, wy, ww, wh;
198 int (*xerrorxlib)(Display *, XErrorEvent *);
199 uint numlockmask = 0;
200 void (*handler[LASTEvent]) (XEvent *) = {
201 [ButtonPress] = buttonpress,
202 [ConfigureRequest] = configurerequest,
203 [ConfigureNotify] = configurenotify,
204 [DestroyNotify] = destroynotify,
205 [EnterNotify] = enternotify,
208 [KeyPress] = keypress,
209 [MappingNotify] = mappingnotify,
210 [MapRequest] = maprequest,
211 [PropertyNotify] = propertynotify,
212 [UnmapNotify] = unmapnotify
214 Atom wmatom[WMLast], netatom[NetLast];
216 Bool otherwm, readin;
218 uint tagset[] = {1, 1}; /* after start, first tag is selected */
219 Client *clients = NULL;
221 Client *stack = NULL;
222 Cursor cursor[CurLast];
226 Layout *lt = layouts;
229 /* configuration, allows nested code to access above variables */
232 /* compile-time check if all tags fit into an uint bit array. */
233 struct NumTags { char limitexceeded[sizeof(uint) * 8 < LENGTH(tags) ? -1 : 1]; };
235 /* function implementations */
237 applyrules(Client *c) {
240 XClassHint ch = { 0 };
243 XGetClassHint(dpy, c->win, &ch);
244 for(i = 0; i < LENGTH(rules); i++) {
246 if((!r->title || strstr(c->name, r->title))
247 && (!r->class || (ch.res_class && strstr(ch.res_class, r->class)))
248 && (!r->instance || (ch.res_name && strstr(ch.res_name, r->instance)))) {
249 c->isfloating = r->isfloating;
250 c->tags |= r->tags & TAGMASK;
258 c->tags = tagset[seltags];
265 for(c = clients; c; c = c->next)
267 if(!lt->arrange || c->isfloating)
268 resize(c, c->x, c->y, c->w, c->h, True);
270 else if(!c->isbanned) {
271 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
276 if(lt->arrange && !domax)
290 attachstack(Client *c) {
296 buttonpress(XEvent *e) {
299 XButtonPressedEvent *ev = &e->xbutton;
301 if(ev->window == barwin) {
303 for(i = 0; i < LENGTH(tags); i++) {
307 if(ev->button == Button1) {
308 if(ev->state & MODKEY)
313 else if(ev->button == Button3) {
314 if(ev->state & MODKEY)
322 if(ev->x < x + blw) {
323 if(ev->button == Button1)
325 else if(ev->button == Button3)
329 else if((c = getclient(ev->window))) {
331 if(CLEANMASK(ev->state) != MODKEY || domax)
333 if(ev->button == Button1)
335 else if(ev->button == Button2)
336 togglefloating(NULL);
337 else if(ev->button == Button3 && !c->isfixed)
345 XSetErrorHandler(xerrorstart);
347 /* this causes an error if some other window manager is running */
348 XSelectInput(dpy, DefaultRootWindow(dpy), SubstructureRedirectMask);
351 eprint("dwm: another window manager is already running\n");
353 XSetErrorHandler(NULL);
354 xerrorxlib = XSetErrorHandler(xerror);
365 XFreeFontSet(dpy, dc.font.set);
367 XFreeFont(dpy, dc.font.xfont);
368 XUngrabKey(dpy, AnyKey, AnyModifier, root);
369 XFreePixmap(dpy, dc.drawable);
371 XFreeCursor(dpy, cursor[CurNormal]);
372 XFreeCursor(dpy, cursor[CurResize]);
373 XFreeCursor(dpy, cursor[CurMove]);
374 XDestroyWindow(dpy, barwin);
376 XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime);
380 configure(Client *c) {
383 ce.type = ConfigureNotify;
391 ce.border_width = c->bw;
393 ce.override_redirect = False;
394 XSendEvent(dpy, c->win, False, StructureNotifyMask, (XEvent *)&ce);
398 configurenotify(XEvent *e) {
399 XConfigureEvent *ev = &e->xconfigure;
401 if(ev->window == root && (ev->width != sw || ev->height != sh)) {
411 configurerequest(XEvent *e) {
413 XConfigureRequestEvent *ev = &e->xconfigurerequest;
416 if((c = getclient(ev->window))) {
417 if(ev->value_mask & CWBorderWidth)
418 c->bw = ev->border_width;
419 if(c->isfixed || c->isfloating || !lt->arrange) {
420 if(ev->value_mask & CWX)
422 if(ev->value_mask & CWY)
424 if(ev->value_mask & CWWidth)
426 if(ev->value_mask & CWHeight)
428 if((c->x - sx + c->w) > sw && c->isfloating)
429 c->x = sx + (sw / 2 - c->w / 2); /* center in x direction */
430 if((c->y - sy + c->h) > sh && c->isfloating)
431 c->y = sy + (sh / 2 - c->h / 2); /* center in y direction */
432 if((ev->value_mask & (CWX|CWY))
433 && !(ev->value_mask & (CWWidth|CWHeight)))
436 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h);
444 wc.width = ev->width;
445 wc.height = ev->height;
446 wc.border_width = ev->border_width;
447 wc.sibling = ev->above;
448 wc.stack_mode = ev->detail;
449 XConfigureWindow(dpy, ev->window, ev->value_mask, &wc);
455 destroynotify(XEvent *e) {
457 XDestroyWindowEvent *ev = &e->xdestroywindow;
459 if((c = getclient(ev->window)))
466 c->prev->next = c->next;
468 c->next->prev = c->prev;
471 c->next = c->prev = NULL;
475 detachstack(Client *c) {
478 for(tc = &stack; *tc && *tc != c; tc = &(*tc)->snext);
488 for(c = stack; c && !VISIBLE(c); c = c->snext);
489 for(i = 0; i < LENGTH(tags); i++) {
490 dc.w = TEXTW(tags[i]);
491 if(tagset[seltags] & 1 << i) {
492 drawtext(tags[i], dc.sel, isurgent(i));
493 drawsquare(c && c->tags & 1 << i, isoccupied(i), isurgent(i), dc.sel);
496 drawtext(tags[i], dc.norm, isurgent(i));
497 drawsquare(c && c->tags & 1 << i, isoccupied(i), isurgent(i), dc.norm);
503 drawtext(lt->symbol, dc.norm, domax);
514 drawtext(stext, dc.norm, False);
515 if((dc.w = dc.x - x) > bh) {
518 drawtext(c->name, dc.sel, False);
519 drawsquare(False, c->isfloating, False, dc.sel);
522 drawtext(NULL, dc.norm, False);
524 XCopyArea(dpy, dc.drawable, barwin, dc.gc, 0, 0, bw, bh, 0, 0);
529 drawsquare(Bool filled, Bool empty, Bool invert, ulong col[ColLast]) {
532 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
534 gcv.foreground = col[invert ? ColBG : ColFG];
535 XChangeGC(dpy, dc.gc, GCForeground, &gcv);
536 x = (dc.font.ascent + dc.font.descent + 2) / 4;
540 r.width = r.height = x + 1;
541 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
544 r.width = r.height = x;
545 XDrawRectangles(dpy, dc.drawable, dc.gc, &r, 1);
550 drawtext(const char *text, ulong col[ColLast], Bool invert) {
553 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
556 XSetForeground(dpy, dc.gc, col[invert ? ColFG : ColBG]);
557 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
561 len = MIN(olen, sizeof buf);
562 memcpy(buf, text, len);
564 h = dc.font.ascent + dc.font.descent;
565 y = dc.y + (dc.h / 2) - (h / 2) + dc.font.ascent;
567 /* shorten text if necessary */
568 for(; len && (w = textnw(buf, len)) > dc.w - h; len--);
579 XSetForeground(dpy, dc.gc, col[invert ? ColBG : ColFG]);
581 XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
583 XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
587 enternotify(XEvent *e) {
589 XCrossingEvent *ev = &e->xcrossing;
591 if((ev->mode != NotifyNormal || ev->detail == NotifyInferior) && ev->window != root)
593 if((c = getclient(ev->window)))
600 eprint(const char *errstr, ...) {
603 va_start(ap, errstr);
604 vfprintf(stderr, errstr, ap);
611 XExposeEvent *ev = &e->xexpose;
613 if(ev->count == 0 && (ev->window == barwin))
619 if(!c || (c && !VISIBLE(c)))
620 for(c = stack; c && !VISIBLE(c); c = c->snext);
621 if(sel && sel != c) {
622 grabbuttons(sel, False);
623 XSetWindowBorder(dpy, sel->win, dc.norm[ColBorder]);
628 grabbuttons(c, True);
633 XMoveResizeWindow(dpy, c->win, wx, wy, ww - 2 * c->bw, wh - 2 * c->bw);
636 XSetWindowBorder(dpy, c->win, dc.sel[ColBorder]);
637 XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
640 XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
645 focusin(XEvent *e) { /* there are some broken focus acquiring clients */
646 XFocusChangeEvent *ev = &e->xfocus;
648 if(sel && ev->window != sel->win)
649 XSetInputFocus(dpy, sel->win, RevertToPointerRoot, CurrentTime);
653 focusnext(const void *arg) {
658 for(c = sel->next; c && !VISIBLE(c); c = c->next);
660 for(c = clients; c && !VISIBLE(c); c = c->next);
668 focusprev(const void *arg) {
673 for(c = sel->prev; c && !VISIBLE(c); c = c->prev);
675 for(c = clients; c && c->next; c = c->next);
676 for(; c && !VISIBLE(c); c = c->prev);
685 getclient(Window w) {
688 for(c = clients; c && c->win != w; c = c->next);
693 getcolor(const char *colstr) {
694 Colormap cmap = DefaultColormap(dpy, screen);
697 if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
698 eprint("error, cannot allocate color '%s'\n", colstr);
706 unsigned char *p = NULL;
710 status = XGetWindowProperty(dpy, w, wmatom[WMState], 0L, 2L, False, wmatom[WMState],
711 &real, &format, &n, &extra, (unsigned char **)&p);
712 if(status != Success)
721 gettextprop(Window w, Atom atom, char *text, uint size) {
726 if(!text || size == 0)
729 XGetTextProperty(dpy, w, &name, atom);
732 if(name.encoding == XA_STRING)
733 strncpy(text, (char *)name.value, size - 1);
735 if(XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success
737 strncpy(text, *list, size - 1);
738 XFreeStringList(list);
741 text[size - 1] = '\0';
747 grabbuttons(Client *c, Bool focused) {
749 uint buttons[] = { Button1, Button2, Button3 };
750 uint modifiers[] = { MODKEY, MODKEY|LockMask, MODKEY|numlockmask,
751 MODKEY|numlockmask|LockMask} ;
753 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
755 for(i = 0; i < LENGTH(buttons); i++)
756 for(j = 0; j < LENGTH(modifiers); j++)
757 XGrabButton(dpy, buttons[i], modifiers[j], c->win, False,
758 BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
760 XGrabButton(dpy, AnyButton, AnyModifier, c->win, False,
761 BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
768 XModifierKeymap *modmap;
770 /* init modifier map */
771 modmap = XGetModifierMapping(dpy);
772 for(i = 0; i < 8; i++)
773 for(j = 0; j < modmap->max_keypermod; j++) {
774 if(modmap->modifiermap[i * modmap->max_keypermod + j] == XKeysymToKeycode(dpy, XK_Num_Lock))
775 numlockmask = (1 << i);
777 XFreeModifiermap(modmap);
779 XUngrabKey(dpy, AnyKey, AnyModifier, root);
780 for(i = 0; i < LENGTH(keys); i++) {
781 code = XKeysymToKeycode(dpy, keys[i].keysym);
782 XGrabKey(dpy, code, keys[i].mod, root, True,
783 GrabModeAsync, GrabModeAsync);
784 XGrabKey(dpy, code, keys[i].mod|LockMask, root, True,
785 GrabModeAsync, GrabModeAsync);
786 XGrabKey(dpy, code, keys[i].mod|numlockmask, root, True,
787 GrabModeAsync, GrabModeAsync);
788 XGrabKey(dpy, code, keys[i].mod|numlockmask|LockMask, root, True,
789 GrabModeAsync, GrabModeAsync);
794 initfont(const char *fontstr) {
795 char *def, **missing;
800 XFreeFontSet(dpy, dc.font.set);
801 dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
804 fprintf(stderr, "dwm: missing fontset: %s\n", missing[n]);
805 XFreeStringList(missing);
808 XFontSetExtents *font_extents;
809 XFontStruct **xfonts;
811 dc.font.ascent = dc.font.descent = 0;
812 font_extents = XExtentsOfFontSet(dc.font.set);
813 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
814 for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
815 dc.font.ascent = MAX(dc.font.ascent, (*xfonts)->ascent);
816 dc.font.descent = MAX(dc.font.descent,(*xfonts)->descent);
822 XFreeFont(dpy, dc.font.xfont);
823 dc.font.xfont = NULL;
824 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr))
825 && !(dc.font.xfont = XLoadQueryFont(dpy, "fixed")))
826 eprint("error, cannot load font: '%s'\n", fontstr);
827 dc.font.ascent = dc.font.xfont->ascent;
828 dc.font.descent = dc.font.xfont->descent;
830 dc.font.height = dc.font.ascent + dc.font.descent;
837 for(c = clients; c; c = c->next)
844 isprotodel(Client *c) {
849 if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
850 for(i = 0; !ret && i < n; i++)
851 if(protocols[i] == wmatom[WMDelete])
862 for(c = clients; c; c = c->next)
863 if(c->isurgent && c->tags & 1 << t)
869 keypress(XEvent *e) {
875 keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
876 for(i = 0; i < LENGTH(keys); i++)
877 if(keysym == keys[i].keysym
878 && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state))
881 keys[i].func(keys[i].arg);
886 killclient(const void *arg) {
891 if(isprotodel(sel)) {
892 ev.type = ClientMessage;
893 ev.xclient.window = sel->win;
894 ev.xclient.message_type = wmatom[WMProtocols];
895 ev.xclient.format = 32;
896 ev.xclient.data.l[0] = wmatom[WMDelete];
897 ev.xclient.data.l[1] = CurrentTime;
898 XSendEvent(dpy, sel->win, False, NoEventMask, &ev);
901 XKillClient(dpy, sel->win);
905 manage(Window w, XWindowAttributes *wa) {
906 Client *c, *t = NULL;
911 if(!(c = calloc(1, sizeof(Client))))
912 eprint("fatal: could not calloc() %u bytes\n", sizeof(Client));
920 c->oldbw = wa->border_width;
921 if(c->w == sw && c->h == sh) {
924 c->bw = wa->border_width;
927 if(c->x + c->w + 2 * c->bw > sx + sw)
928 c->x = sx + sw - c->w - 2 * c->bw;
929 if(c->y + c->h + 2 * c->bw > sy + sh)
930 c->y = sy + sh - c->h - 2 * c->bw;
931 c->x = MAX(c->x, sx);
932 c->y = MAX(c->y, by == 0 ? bh : sy);
936 wc.border_width = c->bw;
937 XConfigureWindow(dpy, w, CWBorderWidth, &wc);
938 XSetWindowBorder(dpy, w, dc.norm[ColBorder]);
939 configure(c); /* propagates border_width, if size doesn't change */
941 XSelectInput(dpy, w, EnterWindowMask|FocusChangeMask|PropertyChangeMask|StructureNotifyMask);
942 grabbuttons(c, False);
944 if((rettrans = XGetTransientForHint(dpy, w, &trans) == Success))
945 for(t = clients; t && t->win != trans; t = t->next);
951 c->isfloating = (rettrans == Success) || c->isfixed;
954 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h); /* some windows require this */
955 XMapWindow(dpy, c->win);
956 setclientstate(c, NormalState);
961 mappingnotify(XEvent *e) {
962 XMappingEvent *ev = &e->xmapping;
964 XRefreshKeyboardMapping(ev);
965 if(ev->request == MappingKeyboard)
970 maprequest(XEvent *e) {
971 static XWindowAttributes wa;
972 XMapRequestEvent *ev = &e->xmaprequest;
974 if(!XGetWindowAttributes(dpy, ev->window, &wa))
976 if(wa.override_redirect)
978 if(!getclient(ev->window))
979 manage(ev->window, &wa);
983 movemouse(Client *c) {
984 int x1, y1, ocx, ocy, di, nx, ny;
992 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
993 None, cursor[CurMove], CurrentTime) != GrabSuccess)
995 XQueryPointer(dpy, root, &dummy, &dummy, &x1, &y1, &di, &di, &dui);
997 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
1000 XUngrabPointer(dpy, CurrentTime);
1002 case ConfigureRequest:
1005 handler[ev.type](&ev);
1009 nx = ocx + (ev.xmotion.x - x1);
1010 ny = ocy + (ev.xmotion.y - y1);
1011 if(snap && nx >= wx && nx <= wx + ww
1012 && ny >= wy && ny <= wy + wh) {
1013 if(abs(wx - nx) < snap)
1015 else if(abs((wx + ww) - (nx + c->w + 2 * c->bw)) < snap)
1016 nx = wx + ww - c->w - 2 * c->bw;
1017 if(abs(wy - ny) < snap)
1019 else if(abs((wy + wh) - (ny + c->h + 2 * c->bw)) < snap)
1020 ny = wy + wh - c->h - 2 * c->bw;
1021 if(!c->isfloating && lt->arrange && (abs(nx - c->x) > snap || abs(ny - c->y) > snap))
1022 togglefloating(NULL);
1024 if(!lt->arrange || c->isfloating)
1025 resize(c, nx, ny, c->w, c->h, False);
1032 nexttiled(Client *c) {
1033 for(; c && (c->isfloating || !VISIBLE(c)); c = c->next);
1038 propertynotify(XEvent *e) {
1041 XPropertyEvent *ev = &e->xproperty;
1043 if(ev->state == PropertyDelete)
1044 return; /* ignore */
1045 if((c = getclient(ev->window))) {
1048 case XA_WM_TRANSIENT_FOR:
1049 XGetTransientForHint(dpy, c->win, &trans);
1050 if(!c->isfloating && (c->isfloating = (getclient(trans) != NULL)))
1053 case XA_WM_NORMAL_HINTS:
1061 if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
1070 quit(const void *arg) {
1071 readin = running = False;
1075 resize(Client *c, int x, int y, int w, int h, Bool sizehints) {
1079 /* set minimum possible */
1083 /* temporarily remove base dimensions */
1087 /* adjust for aspect limits */
1088 if(c->minax != c->maxax && c->minay != c->maxay
1089 && c->minax > 0 && c->maxax > 0 && c->minay > 0 && c->maxay > 0) {
1090 if(w * c->maxay > h * c->maxax)
1091 w = h * c->maxax / c->maxay;
1092 else if(w * c->minay < h * c->minax)
1093 h = w * c->minay / c->minax;
1096 /* adjust for increment value */
1102 /* restore base dimensions */
1106 w = MAX(w, c->minw);
1107 h = MAX(h, c->minh);
1110 w = MIN(w, c->maxw);
1113 h = MIN(h, c->maxh);
1115 if(w <= 0 || h <= 0)
1118 x = sw - w - 2 * c->bw;
1120 y = sh - h - 2 * c->bw;
1121 if(x + w + 2 * c->bw < sx)
1123 if(y + h + 2 * c->bw < sy)
1129 if(c->x != x || c->y != y || c->w != w || c->h != h || c->isbanned || c->ismax) {
1130 c->isbanned = c->ismax = False;
1133 c->w = wc.width = w;
1134 c->h = wc.height = h;
1135 wc.border_width = c->bw;
1136 XConfigureWindow(dpy, c->win,
1137 CWX|CWY|CWWidth|CWHeight|CWBorderWidth, &wc);
1144 resizemouse(Client *c) {
1152 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1153 None, cursor[CurResize], CurrentTime) != GrabSuccess)
1155 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->bw - 1, c->h + c->bw - 1);
1157 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask , &ev);
1160 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0,
1161 c->w + c->bw - 1, c->h + c->bw - 1);
1162 XUngrabPointer(dpy, CurrentTime);
1163 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1165 case ConfigureRequest:
1168 handler[ev.type](&ev);
1172 nw = MAX(ev.xmotion.x - ocx - 2 * c->bw + 1, 1);
1173 nh = MAX(ev.xmotion.y - ocy - 2 * c->bw + 1, 1);
1175 if(snap && nw >= wx && nw <= wx + ww
1176 && nh >= wy && nh <= wy + wh) {
1177 if(!c->isfloating && lt->arrange
1178 && (abs(nw - c->w) > snap || abs(nh - c->h) > snap))
1179 togglefloating(NULL);
1181 if(!lt->arrange || c->isfloating)
1182 resize(c, c->x, c->y, nw, nh, True);
1197 if(domax || sel->isfloating || !lt->arrange)
1198 XRaiseWindow(dpy, sel->win);
1199 if(!domax && lt->arrange) {
1200 wc.stack_mode = Below;
1201 wc.sibling = barwin;
1202 for(c = stack; c; c = c->snext)
1203 if(!c->isfloating && VISIBLE(c)) {
1204 XConfigureWindow(dpy, c->win, CWSibling|CWStackMode, &wc);
1205 wc.sibling = c->win;
1209 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1215 char sbuf[sizeof stext];
1221 /* main event loop, also reads status text from stdin */
1223 xfd = ConnectionNumber(dpy);
1226 len = sizeof stext - 1;
1227 sbuf[len] = stext[len] = '\0'; /* 0-terminator is never touched */
1231 FD_SET(STDIN_FILENO, &rd);
1233 if(select(xfd + 1, &rd, NULL, NULL, NULL) == -1) {
1236 eprint("select failed\n");
1238 if(FD_ISSET(STDIN_FILENO, &rd)) {
1239 switch((r = read(STDIN_FILENO, sbuf + offset, len - offset))) {
1241 strncpy(stext, strerror(errno), len);
1245 strncpy(stext, "EOF", 4);
1249 for(p = sbuf + offset; r > 0; p++, r--, offset++)
1250 if(*p == '\n' || *p == '\0') {
1252 strncpy(stext, sbuf, len);
1253 p += r - 1; /* p is sbuf + offset + r - 1 */
1254 for(r = 0; *(p - r) && *(p - r) != '\n'; r++);
1257 memmove(sbuf, p - r + 1, r);
1264 while(XPending(dpy)) {
1265 XNextEvent(dpy, &ev);
1266 if(handler[ev.type])
1267 (handler[ev.type])(&ev); /* call handler */
1275 Window *wins, d1, d2;
1276 XWindowAttributes wa;
1279 if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1280 for(i = 0; i < num; i++) {
1281 if(!XGetWindowAttributes(dpy, wins[i], &wa)
1282 || wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1284 if(wa.map_state == IsViewable || getstate(wins[i]) == IconicState)
1285 manage(wins[i], &wa);
1287 for(i = 0; i < num; i++) { /* now the transients */
1288 if(!XGetWindowAttributes(dpy, wins[i], &wa))
1290 if(XGetTransientForHint(dpy, wins[i], &d1)
1291 && (wa.map_state == IsViewable || getstate(wins[i]) == IconicState))
1292 manage(wins[i], &wa);
1300 setclientstate(Client *c, long state) {
1301 long data[] = {state, None};
1303 XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1304 PropModeReplace, (unsigned char *)data, 2);
1307 /* arg > 1.0 will set mfact absolutly */
1309 setmfact(const void *arg) {
1310 double d = *((double*) arg);
1312 if(!d || lt->arrange != tile)
1314 d = d < 1.0 ? d + mfact : d - 1.0;
1315 if(d < 0.1 || d > 0.9)
1324 XSetWindowAttributes wa;
1327 screen = DefaultScreen(dpy);
1328 root = RootWindow(dpy, screen);
1332 sw = DisplayWidth(dpy, screen);
1333 sh = DisplayHeight(dpy, screen);
1334 bh = dc.font.height + 2;
1338 wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1339 wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1340 wmatom[WMName] = XInternAtom(dpy, "WM_NAME", False);
1341 wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1342 netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1343 netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1346 wa.cursor = cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1347 cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1348 cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1350 /* init appearance */
1351 dc.norm[ColBorder] = getcolor(NORMBORDERCOLOR);
1352 dc.norm[ColBG] = getcolor(NORMBGCOLOR);
1353 dc.norm[ColFG] = getcolor(NORMFGCOLOR);
1354 dc.sel[ColBorder] = getcolor(SELBORDERCOLOR);
1355 dc.sel[ColBG] = getcolor(SELBGCOLOR);
1356 dc.sel[ColFG] = getcolor(SELFGCOLOR);
1359 dc.drawable = XCreatePixmap(dpy, root, DisplayWidth(dpy, screen), bh, DefaultDepth(dpy, screen));
1360 dc.gc = XCreateGC(dpy, root, 0, 0);
1361 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
1363 XSetFont(dpy, dc.gc, dc.font.xfont->fid);
1366 for(blw = i = 0; LENGTH(layouts) > 1 && i < LENGTH(layouts); i++) {
1367 w = TEXTW(layouts[i].symbol);
1371 wa.override_redirect = 1;
1372 wa.background_pixmap = ParentRelative;
1373 wa.event_mask = ButtonPressMask|ExposureMask;
1375 barwin = XCreateWindow(dpy, root, bx, by, bw, bh, 0, DefaultDepth(dpy, screen),
1376 CopyFromParent, DefaultVisual(dpy, screen),
1377 CWOverrideRedirect|CWBackPixmap|CWEventMask, &wa);
1378 XDefineCursor(dpy, barwin, cursor[CurNormal]);
1379 XMapRaised(dpy, barwin);
1380 strcpy(stext, "dwm-"VERSION);
1383 /* EWMH support per view */
1384 XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1385 PropModeReplace, (unsigned char *) netatom, NetLast);
1387 /* select for events */
1388 wa.event_mask = SubstructureRedirectMask|SubstructureNotifyMask
1389 |EnterWindowMask|LeaveWindowMask|StructureNotifyMask;
1390 XChangeWindowAttributes(dpy, root, CWEventMask|CWCursor, &wa);
1391 XSelectInput(dpy, root, wa.event_mask);
1399 spawn(const void *arg) {
1400 static char *shell = NULL;
1402 if(!shell && !(shell = getenv("SHELL")))
1404 /* The double-fork construct avoids zombie processes and keeps the code
1405 * clean from stupid signal handlers. */
1409 close(ConnectionNumber(dpy));
1411 execl(shell, shell, "-c", (char *)arg, (char *)NULL);
1412 fprintf(stderr, "dwm: execl '%s -c %s'", shell, (char *)arg);
1421 tag(const void *arg) {
1422 if(sel && *(int *)arg & TAGMASK) {
1423 sel->tags = *(int *)arg & TAGMASK;
1429 textnw(const char *text, uint len) {
1433 XmbTextExtents(dc.font.set, text, len, NULL, &r);
1436 return XTextWidth(dc.font.xfont, text, len);
1445 for(n = 0, c = nexttiled(clients); c; c = nexttiled(c->next), n++);
1450 c = nexttiled(clients);
1452 resize(c, wx, wy, ((n == 1) ? ww : mw) - 2 * c->bw, wh - 2 * c->bw, resizehints);
1458 x = (wx + mw > c->x + c->w) ? c->x + c->w + 2 * c->bw : ww - mw;
1460 w = (wx + mw > c->x + c->w) ? wx + ww - x : ww - mw;
1465 for(i = 0, c = nexttiled(c->next); c; c = nexttiled(c->next), i++) {
1466 resize(c, x, y, w - 2 * c->bw, /* remainder */ ((i + 1 == n)
1467 ? (wy + wh) - y : h) - 2 * c->bw, resizehints);
1469 y = c->y + c->h + 2 * c->bw;
1474 togglebar(const void *arg) {
1482 togglefloating(const void *arg) {
1485 sel->isfloating = !sel->isfloating;
1487 resize(sel, sel->x, sel->y, sel->w, sel->h, True);
1492 togglelayout(const void *arg) {
1496 if(++lt == &layouts[LENGTH(layouts)])
1500 for(i = 0; i < LENGTH(layouts); i++)
1501 if(!strcmp((char *)arg, layouts[i].symbol))
1503 if(i == LENGTH(layouts))
1514 togglemax(const void *arg) {
1520 toggletag(const void *arg) {
1521 if(sel && (sel->tags ^ ((*(int *)arg) & TAGMASK))) {
1522 sel->tags ^= (*(int *)arg) & TAGMASK;
1528 toggleview(const void *arg) {
1529 if((tagset[seltags] ^ ((*(int *)arg) & TAGMASK))) {
1530 tagset[seltags] ^= (*(int *)arg) & TAGMASK;
1536 unmanage(Client *c) {
1539 wc.border_width = c->oldbw;
1540 /* The server grab construct avoids race conditions. */
1542 XSetErrorHandler(xerrordummy);
1543 XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
1548 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1549 setclientstate(c, WithdrawnState);
1552 XSetErrorHandler(xerror);
1558 unmapnotify(XEvent *e) {
1560 XUnmapEvent *ev = &e->xunmap;
1562 if((c = getclient(ev->window)))
1568 if(dc.drawable != 0)
1569 XFreePixmap(dpy, dc.drawable);
1570 dc.drawable = XCreatePixmap(dpy, root, bw, bh, DefaultDepth(dpy, screen));
1571 XMoveResizeWindow(dpy, barwin, bx, by, bw, bh);
1578 XineramaScreenInfo *info = NULL;
1580 /* window area geometry */
1581 if(XineramaIsActive(dpy)) {
1582 info = XineramaQueryScreens(dpy, &i);
1584 wy = showbar && topbar ? info[0].y_org + bh : info[0].y_org;
1586 wh = showbar ? info[0].height - bh : info[0].height;
1593 wy = showbar && topbar ? sy + bh : sy;
1595 wh = showbar ? sh - bh : sh;
1600 by = showbar ? (topbar ? wy - bh : wy + wh) : -bh;
1605 updatesizehints(Client *c) {
1609 if(!XGetWMNormalHints(dpy, c->win, &size, &msize) || !size.flags)
1611 c->flags = size.flags;
1612 if(c->flags & PBaseSize) {
1613 c->basew = size.base_width;
1614 c->baseh = size.base_height;
1616 else if(c->flags & PMinSize) {
1617 c->basew = size.min_width;
1618 c->baseh = size.min_height;
1621 c->basew = c->baseh = 0;
1622 if(c->flags & PResizeInc) {
1623 c->incw = size.width_inc;
1624 c->inch = size.height_inc;
1627 c->incw = c->inch = 0;
1628 if(c->flags & PMaxSize) {
1629 c->maxw = size.max_width;
1630 c->maxh = size.max_height;
1633 c->maxw = c->maxh = 0;
1634 if(c->flags & PMinSize) {
1635 c->minw = size.min_width;
1636 c->minh = size.min_height;
1638 else if(c->flags & PBaseSize) {
1639 c->minw = size.base_width;
1640 c->minh = size.base_height;
1643 c->minw = c->minh = 0;
1644 if(c->flags & PAspect) {
1645 c->minax = size.min_aspect.x;
1646 c->maxax = size.max_aspect.x;
1647 c->minay = size.min_aspect.y;
1648 c->maxay = size.max_aspect.y;
1651 c->minax = c->maxax = c->minay = c->maxay = 0;
1652 c->isfixed = (c->maxw && c->minw && c->maxh && c->minh
1653 && c->maxw == c->minw && c->maxh == c->minh);
1657 updatetitle(Client *c) {
1658 if(!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
1659 gettextprop(c->win, wmatom[WMName], c->name, sizeof c->name);
1663 updatewmhints(Client *c) {
1666 if((wmh = XGetWMHints(dpy, c->win))) {
1668 sel->isurgent = False;
1670 c->isurgent = (wmh->flags & XUrgencyHint) ? True : False;
1676 view(const void *arg) {
1677 if(*(int *)arg & TAGMASK) {
1678 seltags ^= 1; /* toggle sel tagset */
1679 tagset[seltags] = *(int *)arg & TAGMASK;
1685 viewprevtag(const void *arg) {
1686 seltags ^= 1; /* toggle sel tagset */
1690 /* There's no way to check accesses to destroyed windows, thus those cases are
1691 * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
1692 * default error handler, which may call exit. */
1694 xerror(Display *dpy, XErrorEvent *ee) {
1695 if(ee->error_code == BadWindow
1696 || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1697 || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1698 || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1699 || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1700 || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1701 || (ee->request_code == X_GrabButton && ee->error_code == BadAccess)
1702 || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1703 || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1705 fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1706 ee->request_code, ee->error_code);
1707 return xerrorxlib(dpy, ee); /* may call exit */
1711 xerrordummy(Display *dpy, XErrorEvent *ee) {
1715 /* Startup Error handler to check if another window manager
1716 * is already running. */
1718 xerrorstart(Display *dpy, XErrorEvent *ee) {
1724 zoom(const void *arg) {
1727 if(!lt->arrange || sel->isfloating)
1729 if(c == nexttiled(clients))
1730 if(!c || !(c = nexttiled(c->next)))
1739 main(int argc, char *argv[]) {
1740 if(argc == 2 && !strcmp("-v", argv[1]))
1741 eprint("dwm-"VERSION", © 2006-2008 dwm engineers, see LICENSE for details\n");
1743 eprint("usage: dwm [-v]\n");
1745 setlocale(LC_CTYPE, "");
1746 if(!(dpy = XOpenDisplay(0)))
1747 eprint("dwm: cannot open display\n");