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))
57 enum { CurNormal, CurResize, CurMove, CurLast }; /* cursor */
58 enum { ColBorder, ColFG, ColBG, ColLast }; /* color */
59 enum { NetSupported, NetWMName, NetLast }; /* EWMH atoms */
60 enum { WMProtocols, WMDelete, WMName, WMState, WMLast };/* default atoms */
63 typedef unsigned int uint;
64 typedef unsigned long ulong;
65 typedef struct Client Client;
69 int basew, baseh, incw, inch, maxw, maxh, minw, minh;
70 int minax, maxax, minay, maxay;
73 Bool isbanned, isfixed, isfloating, isurgent;
94 } DC; /* draw context */
99 void (*func)(const void *arg);
105 void (*arrange)(void);
106 void (*updategeom)(void);
111 const char *instance;
117 /* function declarations */
118 void applyrules(Client *c);
120 void attach(Client *c);
121 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 Bool isvisible(Client *c);
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 && !isvisible(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 && !isvisible(c)))
632 for(c = stack; c && !isvisible(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 && !isvisible(c); c = c->next);
668 for(c = clients; c && !isvisible(c); c = c->next);
676 focusprev(const void *arg) {
681 for(c = sel->prev; c && !isvisible(c); c = c->prev);
683 for(c = clients; c && c->next; c = c->next);
684 for(; c && !isvisible(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 isvisible(Client *c) {
878 return c->tags & tagset[seltags];
882 keypress(XEvent *e) {
888 keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
889 for(i = 0; i < LENGTH(keys); i++)
890 if(keysym == keys[i].keysym
891 && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state))
894 keys[i].func(keys[i].arg);
899 killclient(const void *arg) {
904 if(isprotodel(sel)) {
905 ev.type = ClientMessage;
906 ev.xclient.window = sel->win;
907 ev.xclient.message_type = wmatom[WMProtocols];
908 ev.xclient.format = 32;
909 ev.xclient.data.l[0] = wmatom[WMDelete];
910 ev.xclient.data.l[1] = CurrentTime;
911 XSendEvent(dpy, sel->win, False, NoEventMask, &ev);
914 XKillClient(dpy, sel->win);
918 manage(Window w, XWindowAttributes *wa) {
919 Client *c, *t = NULL;
924 if(!(c = calloc(1, sizeof(Client))))
925 eprint("fatal: could not calloc() %u bytes\n", sizeof(Client));
933 c->oldbw = wa->border_width;
934 if(c->w == sw && c->h == sh) {
937 c->bw = wa->border_width;
940 if(c->x + c->w + 2 * c->bw > sx + sw)
941 c->x = sx + sw - c->w - 2 * c->bw;
942 if(c->y + c->h + 2 * c->bw > sy + sh)
943 c->y = sy + sh - c->h - 2 * c->bw;
944 c->x = MAX(c->x, sx);
945 c->y = MAX(c->y, by == 0 ? bh : sy);
949 wc.border_width = c->bw;
950 XConfigureWindow(dpy, w, CWBorderWidth, &wc);
951 XSetWindowBorder(dpy, w, dc.norm[ColBorder]);
952 configure(c); /* propagates border_width, if size doesn't change */
954 XSelectInput(dpy, w, EnterWindowMask|FocusChangeMask|PropertyChangeMask|StructureNotifyMask);
955 grabbuttons(c, False);
957 if((rettrans = XGetTransientForHint(dpy, w, &trans) == Success))
958 for(t = clients; t && t->win != trans; t = t->next);
964 c->isfloating = (rettrans == Success) || c->isfixed;
967 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h); /* some windows require this */
969 XMapWindow(dpy, c->win);
970 setclientstate(c, NormalState);
975 mappingnotify(XEvent *e) {
976 XMappingEvent *ev = &e->xmapping;
978 XRefreshKeyboardMapping(ev);
979 if(ev->request == MappingKeyboard)
984 maprequest(XEvent *e) {
985 static XWindowAttributes wa;
986 XMapRequestEvent *ev = &e->xmaprequest;
988 if(!XGetWindowAttributes(dpy, ev->window, &wa))
990 if(wa.override_redirect)
992 if(!getclient(ev->window))
993 manage(ev->window, &wa);
997 movemouse(Client *c) {
998 int x1, y1, ocx, ocy, di, nx, ny;
1005 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1006 None, cursor[CurMove], CurrentTime) != GrabSuccess)
1008 XQueryPointer(dpy, root, &dummy, &dummy, &x1, &y1, &di, &di, &dui);
1010 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
1013 XUngrabPointer(dpy, CurrentTime);
1015 case ConfigureRequest:
1018 handler[ev.type](&ev);
1022 nx = ocx + (ev.xmotion.x - x1);
1023 ny = ocy + (ev.xmotion.y - y1);
1024 if(snap && nx >= wx && nx <= wx + ww
1025 && ny >= wy && ny <= wy + wh) {
1026 if(abs(wx - nx) < snap)
1028 else if(abs((wx + ww) - (nx + c->w + 2 * c->bw)) < snap)
1029 nx = wx + ww - c->w - 2 * c->bw;
1030 if(abs(wy - ny) < snap)
1032 else if(abs((wy + wh) - (ny + c->h + 2 * c->bw)) < snap)
1033 ny = wy + wh - c->h - 2 * c->bw;
1034 if(!c->isfloating && lt->arrange && (abs(nx - c->x) > snap || abs(ny - c->y) > snap))
1035 togglefloating(NULL);
1037 if(!lt->arrange || c->isfloating)
1038 resize(c, nx, ny, c->w, c->h, False);
1045 nexttiled(Client *c) {
1046 for(; c && (c->isfloating || !isvisible(c)); c = c->next);
1051 propertynotify(XEvent *e) {
1054 XPropertyEvent *ev = &e->xproperty;
1056 if(ev->state == PropertyDelete)
1057 return; /* ignore */
1058 if((c = getclient(ev->window))) {
1061 case XA_WM_TRANSIENT_FOR:
1062 XGetTransientForHint(dpy, c->win, &trans);
1063 if(!c->isfloating && (c->isfloating = (getclient(trans) != NULL)))
1066 case XA_WM_NORMAL_HINTS:
1074 if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
1083 quit(const void *arg) {
1084 readin = running = False;
1088 resize(Client *c, int x, int y, int w, int h, Bool sizehints) {
1092 /* set minimum possible */
1096 /* temporarily remove base dimensions */
1100 /* adjust for aspect limits */
1101 if(c->minax != c->maxax && c->minay != c->maxay
1102 && c->minax > 0 && c->maxax > 0 && c->minay > 0 && c->maxay > 0) {
1103 if(w * c->maxay > h * c->maxax)
1104 w = h * c->maxax / c->maxay;
1105 else if(w * c->minay < h * c->minax)
1106 h = w * c->minay / c->minax;
1109 /* adjust for increment value */
1115 /* restore base dimensions */
1119 w = MAX(w, c->minw);
1120 h = MAX(h, c->minh);
1123 w = MIN(w, c->maxw);
1126 h = MIN(h, c->maxh);
1128 if(w <= 0 || h <= 0)
1131 x = sw - w - 2 * c->bw;
1133 y = sh - h - 2 * c->bw;
1134 if(x + w + 2 * c->bw < sx)
1136 if(y + h + 2 * c->bw < sy)
1138 if(c->x != x || c->y != y || c->w != w || c->h != h) {
1141 c->w = wc.width = w;
1142 c->h = wc.height = h;
1143 wc.border_width = c->bw;
1144 XConfigureWindow(dpy, c->win,
1145 CWX|CWY|CWWidth|CWHeight|CWBorderWidth, &wc);
1152 resizemouse(Client *c) {
1159 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1160 None, cursor[CurResize], CurrentTime) != GrabSuccess)
1162 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->bw - 1, c->h + c->bw - 1);
1164 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask , &ev);
1167 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0,
1168 c->w + c->bw - 1, c->h + c->bw - 1);
1169 XUngrabPointer(dpy, CurrentTime);
1170 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1172 case ConfigureRequest:
1175 handler[ev.type](&ev);
1179 nw = MAX(ev.xmotion.x - ocx - 2 * c->bw + 1, 1);
1180 nh = MAX(ev.xmotion.y - ocy - 2 * c->bw + 1, 1);
1182 if(snap && nw >= wx && nw <= wx + ww
1183 && nh >= wy && nh <= wy + wh) {
1184 if(!c->isfloating && lt->arrange
1185 && (abs(nw - c->w) > snap || abs(nh - c->h) > snap))
1186 togglefloating(NULL);
1188 if(!lt->arrange || c->isfloating)
1189 resize(c, c->x, c->y, nw, nh, True);
1204 if(sel->isfloating || !lt->arrange)
1205 XRaiseWindow(dpy, sel->win);
1207 wc.stack_mode = Below;
1208 wc.sibling = barwin;
1209 for(c = stack; c; c = c->snext)
1210 if(!c->isfloating && isvisible(c)) {
1211 XConfigureWindow(dpy, c->win, CWSibling|CWStackMode, &wc);
1212 wc.sibling = c->win;
1216 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1222 char sbuf[sizeof stext];
1228 /* main event loop, also reads status text from stdin */
1230 xfd = ConnectionNumber(dpy);
1233 len = sizeof stext - 1;
1234 sbuf[len] = stext[len] = '\0'; /* 0-terminator is never touched */
1238 FD_SET(STDIN_FILENO, &rd);
1240 if(select(xfd + 1, &rd, NULL, NULL, NULL) == -1) {
1243 eprint("select failed\n");
1245 if(FD_ISSET(STDIN_FILENO, &rd)) {
1246 switch((r = read(STDIN_FILENO, sbuf + offset, len - offset))) {
1248 strncpy(stext, strerror(errno), len);
1252 strncpy(stext, "EOF", 4);
1256 for(p = sbuf + offset; r > 0; p++, r--, offset++)
1257 if(*p == '\n' || *p == '\0') {
1259 strncpy(stext, sbuf, len);
1260 p += r - 1; /* p is sbuf + offset + r - 1 */
1261 for(r = 0; *(p - r) && *(p - r) != '\n'; r++);
1264 memmove(sbuf, p - r + 1, r);
1271 while(XPending(dpy)) {
1272 XNextEvent(dpy, &ev);
1273 if(handler[ev.type])
1274 (handler[ev.type])(&ev); /* call handler */
1282 Window *wins, d1, d2;
1283 XWindowAttributes wa;
1286 if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1287 for(i = 0; i < num; i++) {
1288 if(!XGetWindowAttributes(dpy, wins[i], &wa)
1289 || wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1291 if(wa.map_state == IsViewable || getstate(wins[i]) == IconicState)
1292 manage(wins[i], &wa);
1294 for(i = 0; i < num; i++) { /* now the transients */
1295 if(!XGetWindowAttributes(dpy, wins[i], &wa))
1297 if(XGetTransientForHint(dpy, wins[i], &d1)
1298 && (wa.map_state == IsViewable || getstate(wins[i]) == IconicState))
1299 manage(wins[i], &wa);
1307 setclientstate(Client *c, long state) {
1308 long data[] = {state, None};
1310 XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1311 PropModeReplace, (unsigned char *)data, 2);
1314 /* arg > 1.0 will set mfact absolutly */
1316 setmfact(const void *arg) {
1317 double d = *((double*) arg);
1319 if(!d || lt->arrange != tile)
1321 d = d < 1.0 ? d + mfact : d - 1.0;
1322 if(d < 0.1 || d > 0.9)
1332 XSetWindowAttributes wa;
1335 screen = DefaultScreen(dpy);
1336 root = RootWindow(dpy, screen);
1340 sw = DisplayWidth(dpy, screen);
1341 sh = DisplayHeight(dpy, screen);
1342 bh = dc.font.height + 2;
1346 wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1347 wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1348 wmatom[WMName] = XInternAtom(dpy, "WM_NAME", False);
1349 wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1350 netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1351 netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1354 wa.cursor = cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1355 cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1356 cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1358 /* init appearance */
1359 dc.norm[ColBorder] = getcolor(NORMBORDERCOLOR);
1360 dc.norm[ColBG] = getcolor(NORMBGCOLOR);
1361 dc.norm[ColFG] = getcolor(NORMFGCOLOR);
1362 dc.sel[ColBorder] = getcolor(SELBORDERCOLOR);
1363 dc.sel[ColBG] = getcolor(SELBGCOLOR);
1364 dc.sel[ColFG] = getcolor(SELFGCOLOR);
1367 dc.drawable = XCreatePixmap(dpy, root, DisplayWidth(dpy, screen), bh, DefaultDepth(dpy, screen));
1368 dc.gc = XCreateGC(dpy, root, 0, 0);
1369 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
1371 XSetFont(dpy, dc.gc, dc.font.xfont->fid);
1374 for(blw = i = 0; LENGTH(layouts) > 1 && i < LENGTH(layouts); i++) {
1375 w = textw(layouts[i].symbol);
1379 wa.override_redirect = 1;
1380 wa.background_pixmap = ParentRelative;
1381 wa.event_mask = ButtonPressMask|ExposureMask;
1383 barwin = XCreateWindow(dpy, root, bx, by, bw, bh, 0, DefaultDepth(dpy, screen),
1384 CopyFromParent, DefaultVisual(dpy, screen),
1385 CWOverrideRedirect|CWBackPixmap|CWEventMask, &wa);
1386 XDefineCursor(dpy, barwin, cursor[CurNormal]);
1387 XMapRaised(dpy, barwin);
1388 strcpy(stext, "dwm-"VERSION);
1391 /* EWMH support per view */
1392 XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1393 PropModeReplace, (unsigned char *) netatom, NetLast);
1395 /* select for events */
1396 wa.event_mask = SubstructureRedirectMask|SubstructureNotifyMask
1397 |EnterWindowMask|LeaveWindowMask|StructureNotifyMask;
1398 XChangeWindowAttributes(dpy, root, CWEventMask|CWCursor, &wa);
1399 XSelectInput(dpy, root, wa.event_mask);
1407 spawn(const void *arg) {
1408 static char *shell = NULL;
1410 if(!shell && !(shell = getenv("SHELL")))
1412 /* The double-fork construct avoids zombie processes and keeps the code
1413 * clean from stupid signal handlers. */
1417 close(ConnectionNumber(dpy));
1419 execl(shell, shell, "-c", (char *)arg, (char *)NULL);
1420 fprintf(stderr, "dwm: execl '%s -c %s'", shell, (char *)arg);
1429 tag(const void *arg) {
1430 if(sel && *(int *)arg & TAGMASK) {
1431 sel->tags = *(int *)arg & TAGMASK;
1437 textnw(const char *text, uint len) {
1441 XmbTextExtents(dc.font.set, text, len, NULL, &r);
1444 return XTextWidth(dc.font.xfont, text, len);
1448 textw(const char *text) {
1449 return textnw(text, strlen(text)) + dc.font.height;
1458 for(n = 0, c = nexttiled(clients); c; c = nexttiled(c->next), n++);
1463 c = nexttiled(clients);
1466 tileresize(c, wx, wy, ww - 2 * c->bw, wh - 2 * c->bw);
1468 tileresize(c, mx, my, mw - 2 * c->bw, mh - 2 * c->bw);
1474 x = (tx > c->x + c->w) ? c->x + c->w + 2 * c->bw : tw;
1476 w = (tx > c->x + c->w) ? wx + ww - x : tw;
1481 for(i = 0, c = nexttiled(c->next); c; c = nexttiled(c->next), i++) {
1482 if(i + 1 == n) /* remainder */
1483 tileresize(c, x, y, w - 2 * c->bw, (ty + th) - y - 2 * c->bw);
1485 tileresize(c, x, y, w - 2 * c->bw, h - 2 * c->bw);
1487 y = c->y + c->h + 2 * c->bw;
1492 tileresize(Client *c, int x, int y, int w, int h) {
1493 resize(c, x, y, w, h, resizehints);
1494 if(resizehints && ((c->h < bh) || (c->h > h) || (c->w < bh) || (c->w > w)))
1495 /* client doesn't accept size constraints */
1496 resize(c, x, y, w, h, False);
1500 togglebar(const void *arg) {
1508 togglefloating(const void *arg) {
1511 sel->isfloating = !sel->isfloating;
1513 resize(sel, sel->x, sel->y, sel->w, sel->h, True);
1518 togglelayout(const void *arg) {
1522 if(++lt == &layouts[LENGTH(layouts)])
1526 for(i = 0; i < LENGTH(layouts); i++)
1527 if(!strcmp((char *)arg, layouts[i].symbol))
1529 if(i == LENGTH(layouts))
1540 toggletag(const void *arg) {
1541 if(sel && (sel->tags ^ ((*(int *)arg) & TAGMASK))) {
1542 sel->tags ^= (*(int *)arg) & TAGMASK;
1548 toggleview(const void *arg) {
1549 if((tagset[seltags] ^ ((*(int *)arg) & TAGMASK))) {
1550 tagset[seltags] ^= (*(int *)arg) & TAGMASK;
1559 XMoveWindow(dpy, c->win, c->x, c->y);
1560 c->isbanned = False;
1564 unmanage(Client *c) {
1567 wc.border_width = c->oldbw;
1568 /* The server grab construct avoids race conditions. */
1570 XSetErrorHandler(xerrordummy);
1571 XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
1576 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1577 setclientstate(c, WithdrawnState);
1580 XSetErrorHandler(xerror);
1586 unmapnotify(XEvent *e) {
1588 XUnmapEvent *ev = &e->xunmap;
1590 if((c = getclient(ev->window)))
1596 if(dc.drawable != 0)
1597 XFreePixmap(dpy, dc.drawable);
1598 dc.drawable = XCreatePixmap(dpy, root, bw, bh, DefaultDepth(dpy, screen));
1599 XMoveResizeWindow(dpy, barwin, bx, by, bw, bh);
1606 XineramaScreenInfo *info = NULL;
1608 /* window area geometry */
1609 if(XineramaIsActive(dpy)) {
1610 info = XineramaQueryScreens(dpy, &i);
1612 wy = showbar && topbar ? info[0].y_org + bh : info[0].y_org;
1614 wh = showbar ? info[0].height - bh : info[0].height;
1621 wy = showbar && topbar ? sy + bh : sy;
1623 wh = showbar ? sh - bh : sh;
1628 by = showbar ? (topbar ? wy - bh : wy + wh) : -bh;
1631 /* update layout geometries */
1632 for(i = 0; i < LENGTH(layouts); i++)
1633 if(layouts[i].updategeom)
1634 layouts[i].updategeom();
1638 updatesizehints(Client *c) {
1642 if(!XGetWMNormalHints(dpy, c->win, &size, &msize) || !size.flags)
1644 c->flags = size.flags;
1645 if(c->flags & PBaseSize) {
1646 c->basew = size.base_width;
1647 c->baseh = size.base_height;
1649 else if(c->flags & PMinSize) {
1650 c->basew = size.min_width;
1651 c->baseh = size.min_height;
1654 c->basew = c->baseh = 0;
1655 if(c->flags & PResizeInc) {
1656 c->incw = size.width_inc;
1657 c->inch = size.height_inc;
1660 c->incw = c->inch = 0;
1661 if(c->flags & PMaxSize) {
1662 c->maxw = size.max_width;
1663 c->maxh = size.max_height;
1666 c->maxw = c->maxh = 0;
1667 if(c->flags & PMinSize) {
1668 c->minw = size.min_width;
1669 c->minh = size.min_height;
1671 else if(c->flags & PBaseSize) {
1672 c->minw = size.base_width;
1673 c->minh = size.base_height;
1676 c->minw = c->minh = 0;
1677 if(c->flags & PAspect) {
1678 c->minax = size.min_aspect.x;
1679 c->maxax = size.max_aspect.x;
1680 c->minay = size.min_aspect.y;
1681 c->maxay = size.max_aspect.y;
1684 c->minax = c->maxax = c->minay = c->maxay = 0;
1685 c->isfixed = (c->maxw && c->minw && c->maxh && c->minh
1686 && c->maxw == c->minw && c->maxh == c->minh);
1690 updatetilegeom(void) {
1691 /* master area geometry */
1697 /* tile area geometry */
1705 updatetitle(Client *c) {
1706 if(!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
1707 gettextprop(c->win, wmatom[WMName], c->name, sizeof c->name);
1711 updatewmhints(Client *c) {
1714 if((wmh = XGetWMHints(dpy, c->win))) {
1716 sel->isurgent = False;
1718 c->isurgent = (wmh->flags & XUrgencyHint) ? True : False;
1724 view(const void *arg) {
1725 if(*(int *)arg & TAGMASK) {
1726 seltags ^= 1; /* toggle sel tagset */
1727 tagset[seltags] = *(int *)arg & TAGMASK;
1733 viewprevtag(const void *arg) {
1734 seltags ^= 1; /* toggle sel tagset */
1738 /* There's no way to check accesses to destroyed windows, thus those cases are
1739 * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
1740 * default error handler, which may call exit. */
1742 xerror(Display *dpy, XErrorEvent *ee) {
1743 if(ee->error_code == BadWindow
1744 || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1745 || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1746 || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1747 || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1748 || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1749 || (ee->request_code == X_GrabButton && ee->error_code == BadAccess)
1750 || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1751 || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1753 fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1754 ee->request_code, ee->error_code);
1755 return xerrorxlib(dpy, ee); /* may call exit */
1759 xerrordummy(Display *dpy, XErrorEvent *ee) {
1763 /* Startup Error handler to check if another window manager
1764 * is already running. */
1766 xerrorstart(Display *dpy, XErrorEvent *ee) {
1772 zoom(const void *arg) {
1775 if(!lt->arrange || sel->isfloating)
1777 if(c == nexttiled(clients))
1778 if(!c || !(c = nexttiled(c->next)))
1787 main(int argc, char *argv[]) {
1788 if(argc == 2 && !strcmp("-v", argv[1]))
1789 eprint("dwm-"VERSION", © 2006-2008 dwm engineers, see LICENSE for details\n");
1791 eprint("usage: dwm [-v]\n");
1793 setlocale(LC_CTYPE, "");
1794 if(!(dpy = XOpenDisplay(0)))
1795 eprint("dwm: cannot open display\n");