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 a bit array to indicate the tags of a
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 ISVISIBLE(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 */
63 enum { ClkTagBar, ClkLtSymbol, ClkStatusText, ClkWinTitle,
64 ClkClientWin, ClkRootWin, ClkLast }; /* clicks */
77 void (*func)(const Arg *arg);
81 typedef struct Client Client;
86 int basew, baseh, incw, inch, maxw, maxh, minw, minh;
89 Bool isfixed, isfloating, isurgent;
97 unsigned long norm[ColLast];
98 unsigned long sel[ColLast];
108 } DC; /* draw context */
113 void (*func)(const Arg *);
119 void (*arrange)(void);
124 const char *instance;
130 /* function declarations */
131 static void applyrules(Client *c);
132 static void arrange(void);
133 static void attach(Client *c);
134 static void attachstack(Client *c);
135 static void buttonpress(XEvent *e);
136 static void checkotherwm(void);
137 static void cleanup(void);
138 static void clearurgent(void);
139 static void configure(Client *c);
140 static void configurenotify(XEvent *e);
141 static void configurerequest(XEvent *e);
142 static void destroynotify(XEvent *e);
143 static void detach(Client *c);
144 static void detachstack(Client *c);
145 static void die(const char *errstr, ...);
146 static void drawbar(void);
147 static void drawsquare(Bool filled, Bool empty, Bool invert, unsigned long col[ColLast]);
148 static void drawtext(const char *text, unsigned long col[ColLast], Bool invert);
149 static void enternotify(XEvent *e);
150 static void expose(XEvent *e);
151 static void focus(Client *c);
152 static void focusin(XEvent *e);
153 static void focusstack(const Arg *arg);
154 static Client *getclient(Window w);
155 static unsigned long getcolor(const char *colstr);
156 static long getstate(Window w);
157 static Bool gettextprop(Window w, Atom atom, char *text, unsigned int size);
158 static void grabbuttons(Client *c, Bool focused);
159 static void grabkeys(void);
160 static void initfont(const char *fontstr);
161 static Bool isoccupied(unsigned int t);
162 static Bool isprotodel(Client *c);
163 static Bool isurgent(unsigned int t);
164 static void keypress(XEvent *e);
165 static void killclient(const Arg *arg);
166 static void manage(Window w, XWindowAttributes *wa);
167 static void mappingnotify(XEvent *e);
168 static void maprequest(XEvent *e);
169 static void monocle(void);
170 static void movemouse(const Arg *arg);
171 static Client *nexttiled(Client *c);
172 static void propertynotify(XEvent *e);
173 static void quit(const Arg *arg);
174 static void resize(Client *c, int x, int y, int w, int h, Bool sizehints);
175 static void resizemouse(const Arg *arg);
176 static void restack(void);
177 static void run(void);
178 static void scan(void);
179 static void setclientstate(Client *c, long state);
180 static void setlayout(const Arg *arg);
181 static void setmfact(const Arg *arg);
182 static void setup(void);
183 static void spawn(const Arg *arg);
184 static void tag(const Arg *arg);
185 static int textnw(const char *text, unsigned int len);
186 static void tile(void);
187 static void togglebar(const Arg *arg);
188 static void togglefloating(const Arg *arg);
189 static void toggletag(const Arg *arg);
190 static void toggleview(const Arg *arg);
191 static void unmanage(Client *c);
192 static void unmapnotify(XEvent *e);
193 static void updatebar(void);
194 static void updategeom(void);
195 static void updatesizehints(Client *c);
196 static void updatetitle(Client *c);
197 static void updatewmhints(Client *c);
198 static void view(const Arg *arg);
199 static int xerror(Display *dpy, XErrorEvent *ee);
200 static int xerrordummy(Display *dpy, XErrorEvent *ee);
201 static int xerrorstart(Display *dpy, XErrorEvent *ee);
202 static void zoom(const Arg *arg);
205 static char stext[256];
206 static int screen, sx, sy, sw, sh;
207 static int by, bh, blw, wx, wy, ww, wh;
208 static unsigned int seltags = 0, sellt = 0;
209 static int (*xerrorxlib)(Display *, XErrorEvent *);
210 static unsigned int numlockmask = 0;
211 static void (*handler[LASTEvent]) (XEvent *) = {
212 [ButtonPress] = buttonpress,
213 [ConfigureRequest] = configurerequest,
214 [ConfigureNotify] = configurenotify,
215 [DestroyNotify] = destroynotify,
216 [EnterNotify] = enternotify,
219 [KeyPress] = keypress,
220 [MappingNotify] = mappingnotify,
221 [MapRequest] = maprequest,
222 [PropertyNotify] = propertynotify,
223 [UnmapNotify] = unmapnotify
225 static Atom wmatom[WMLast], netatom[NetLast];
226 static Bool otherwm, readin;
227 static Bool running = True;
228 static unsigned int tagset[] = {1, 1}; /* after start, first tag is selected */
229 static Client *clients = NULL;
230 static Client *sel = NULL;
231 static Client *stack = NULL;
232 static Cursor cursor[CurLast];
235 static Layout *lt[] = { NULL, NULL };
236 static Window root, barwin;
237 /* configuration, allows nested code to access above variables */
240 /* compile-time check if all tags fit into an unsigned int bit array. */
241 struct NumTags { char limitexceeded[sizeof(unsigned int) * 8 < LENGTH(tags) ? -1 : 1]; };
243 /* function implementations */
245 applyrules(Client *c) {
248 XClassHint ch = { 0 };
251 XGetClassHint(dpy, c->win, &ch);
252 for(i = 0; i < LENGTH(rules); i++) {
254 if((!r->title || strstr(c->name, r->title))
255 && (!r->class || (ch.res_class && strstr(ch.res_class, r->class)))
256 && (!r->instance || (ch.res_name && strstr(ch.res_name, r->instance)))) {
257 c->isfloating = r->isfloating;
258 c->tags |= r->tags & TAGMASK;
266 c->tags = tagset[seltags];
273 for(c = clients; c; c = c->next)
275 XMoveWindow(dpy, c->win, c->x, c->y);
276 if(!lt[sellt]->arrange || c->isfloating)
277 resize(c, c->x, c->y, c->w, c->h, True);
280 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
284 if(lt[sellt]->arrange)
285 lt[sellt]->arrange();
296 attachstack(Client *c) {
302 buttonpress(XEvent *e) {
303 unsigned int i, x, click;
306 XButtonPressedEvent *ev = &e->xbutton;
309 if(ev->window == barwin) {
311 do x += TEXTW(tags[i]); while(ev->x >= x && ++i < LENGTH(tags));
312 if(i < LENGTH(tags)) {
316 else if(ev->x < x + blw)
318 else if(ev->x > wx + ww - TEXTW(stext))
319 click = ClkStatusText;
323 else if((c = getclient(ev->window))) {
325 click = ClkClientWin;
328 for(i = 0; i < LENGTH(buttons); i++)
329 if(click == buttons[i].click && buttons[i].func && buttons[i].button == ev->button
330 && CLEANMASK(buttons[i].mask) == CLEANMASK(ev->state))
331 buttons[i].func(click == ClkTagBar ? &arg : &buttons[i].arg);
337 XSetErrorHandler(xerrorstart);
339 /* this causes an error if some other window manager is running */
340 XSelectInput(dpy, DefaultRootWindow(dpy), SubstructureRedirectMask);
343 die("dwm: another window manager is already running\n");
344 XSetErrorHandler(NULL);
345 xerrorxlib = XSetErrorHandler(xerror);
352 Layout foo = { "", NULL };
360 XFreeFontSet(dpy, dc.font.set);
362 XFreeFont(dpy, dc.font.xfont);
363 XUngrabKey(dpy, AnyKey, AnyModifier, root);
364 XFreePixmap(dpy, dc.drawable);
366 XFreeCursor(dpy, cursor[CurNormal]);
367 XFreeCursor(dpy, cursor[CurResize]);
368 XFreeCursor(dpy, cursor[CurMove]);
369 XDestroyWindow(dpy, barwin);
371 XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime);
379 for(c = clients; c; c = c->next)
380 if(ISVISIBLE(c) && c->isurgent) {
382 if (!(wmh = XGetWMHints(dpy, c->win)))
385 wmh->flags &= ~XUrgencyHint;
386 XSetWMHints(dpy, c->win, wmh);
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 else if(c->isfloating || !lt[sellt]->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)) && !(ev->value_mask & (CWWidth|CWHeight)))
447 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h);
455 wc.width = ev->width;
456 wc.height = ev->height;
457 wc.border_width = ev->border_width;
458 wc.sibling = ev->above;
459 wc.stack_mode = ev->detail;
460 XConfigureWindow(dpy, ev->window, ev->value_mask, &wc);
466 destroynotify(XEvent *e) {
468 XDestroyWindowEvent *ev = &e->xdestroywindow;
470 if((c = getclient(ev->window)))
478 for(tc = &clients; *tc && *tc != c; tc = &(*tc)->next);
483 detachstack(Client *c) {
486 for(tc = &stack; *tc && *tc != c; tc = &(*tc)->snext);
491 die(const char *errstr, ...) {
494 va_start(ap, errstr);
495 vfprintf(stderr, errstr, ap);
505 for(i = 0; i < LENGTH(tags); i++) {
506 dc.w = TEXTW(tags[i]);
507 if(tagset[seltags] & 1 << i) {
508 drawtext(tags[i], dc.sel, isurgent(i));
509 drawsquare(sel && sel->tags & 1 << i, isoccupied(i), isurgent(i), dc.sel);
512 drawtext(tags[i], dc.norm, isurgent(i));
513 drawsquare(sel && sel->tags & 1 << i, isoccupied(i), isurgent(i), dc.norm);
519 drawtext(lt[sellt]->symbol, dc.norm, False);
530 drawtext(stext, dc.norm, False);
531 if((dc.w = dc.x - x) > bh) {
534 drawtext(sel->name, dc.sel, False);
535 drawsquare(sel->isfixed, sel->isfloating, False, dc.sel);
538 drawtext(NULL, dc.norm, False);
540 XCopyArea(dpy, dc.drawable, barwin, dc.gc, 0, 0, ww, bh, 0, 0);
545 drawsquare(Bool filled, Bool empty, Bool invert, unsigned long col[ColLast]) {
548 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
550 gcv.foreground = col[invert ? ColBG : ColFG];
551 XChangeGC(dpy, dc.gc, GCForeground, &gcv);
552 x = (dc.font.ascent + dc.font.descent + 2) / 4;
556 r.width = r.height = x + 1;
557 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
560 r.width = r.height = x;
561 XDrawRectangles(dpy, dc.drawable, dc.gc, &r, 1);
566 drawtext(const char *text, unsigned long col[ColLast], Bool invert) {
567 int i, x, y, h, len, olen;
568 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
571 XSetForeground(dpy, dc.gc, col[invert ? ColFG : ColBG]);
572 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
576 len = MIN(olen, sizeof buf);
577 memcpy(buf, text, len);
578 h = dc.font.ascent + dc.font.descent;
579 y = dc.y + (dc.h / 2) - (h / 2) + dc.font.ascent;
581 /* shorten text if necessary */
582 for(; len && (i = textnw(buf, len)) > dc.w - h; len--);
586 for(i = len; i && i > len - 3; buf[--i] = '.');
587 XSetForeground(dpy, dc.gc, col[invert ? ColBG : ColFG]);
589 XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
591 XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
595 enternotify(XEvent *e) {
597 XCrossingEvent *ev = &e->xcrossing;
599 if((ev->mode != NotifyNormal || ev->detail == NotifyInferior) && ev->window != root)
601 if((c = getclient(ev->window)))
609 XExposeEvent *ev = &e->xexpose;
611 if(ev->count == 0 && (ev->window == barwin))
617 if(!c || !ISVISIBLE(c))
618 for(c = stack; c && !ISVISIBLE(c); c = c->snext);
619 if(sel && sel != c) {
620 grabbuttons(sel, False);
621 XSetWindowBorder(dpy, sel->win, dc.norm[ColBorder]);
626 grabbuttons(c, True);
627 XSetWindowBorder(dpy, c->win, dc.sel[ColBorder]);
628 XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
631 XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
637 focusin(XEvent *e) { /* there are some broken focus acquiring clients */
638 XFocusChangeEvent *ev = &e->xfocus;
640 if(sel && ev->window != sel->win)
641 XSetInputFocus(dpy, sel->win, RevertToPointerRoot, CurrentTime);
645 focusstack(const Arg *arg) {
646 Client *c = NULL, *i;
651 for(c = sel->next; c && !ISVISIBLE(c); c = c->next);
653 for(c = clients; c && !ISVISIBLE(c); c = c->next);
656 for(i = clients; i != sel; i = i->next)
660 for(; i; i = i->next)
671 getclient(Window w) {
674 for(c = clients; c && c->win != w; c = c->next);
679 getcolor(const char *colstr) {
680 Colormap cmap = DefaultColormap(dpy, screen);
683 if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
684 die("error, cannot allocate color '%s'\n", colstr);
692 unsigned char *p = NULL;
693 unsigned long n, extra;
696 status = XGetWindowProperty(dpy, w, wmatom[WMState], 0L, 2L, False, wmatom[WMState],
697 &real, &format, &n, &extra, (unsigned char **)&p);
698 if(status != Success)
707 gettextprop(Window w, Atom atom, char *text, unsigned int size) {
712 if(!text || size == 0)
715 XGetTextProperty(dpy, w, &name, atom);
718 if(name.encoding == XA_STRING)
719 strncpy(text, (char *)name.value, size - 1);
721 if(XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success
723 strncpy(text, *list, size - 1);
724 XFreeStringList(list);
727 text[size - 1] = '\0';
733 grabbuttons(Client *c, Bool focused) {
735 unsigned int modifiers[] = { 0, LockMask, numlockmask, numlockmask|LockMask };
737 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
739 for(i = 0; i < LENGTH(buttons); i++)
740 if(buttons[i].click == ClkClientWin)
741 for(j = 0; j < LENGTH(modifiers); j++)
742 XGrabButton(dpy, buttons[i].button, buttons[i].mask | modifiers[j], c->win, False, BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
744 XGrabButton(dpy, AnyButton, AnyModifier, c->win, False,
745 BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
752 XModifierKeymap *modmap;
754 /* init modifier map */
755 modmap = XGetModifierMapping(dpy);
756 for(i = 0; i < 8; i++)
757 for(j = 0; j < modmap->max_keypermod; j++) {
758 if(modmap->modifiermap[i * modmap->max_keypermod + j] == XKeysymToKeycode(dpy, XK_Num_Lock))
759 numlockmask = (1 << i);
761 XFreeModifiermap(modmap);
763 XUngrabKey(dpy, AnyKey, AnyModifier, root);
764 for(i = 0; i < LENGTH(keys); i++) {
765 code = XKeysymToKeycode(dpy, keys[i].keysym);
766 XGrabKey(dpy, code, keys[i].mod, root, True,
767 GrabModeAsync, GrabModeAsync);
768 XGrabKey(dpy, code, keys[i].mod|LockMask, root, True,
769 GrabModeAsync, GrabModeAsync);
770 XGrabKey(dpy, code, keys[i].mod|numlockmask, root, True,
771 GrabModeAsync, GrabModeAsync);
772 XGrabKey(dpy, code, keys[i].mod|numlockmask|LockMask, root, True,
773 GrabModeAsync, GrabModeAsync);
778 initfont(const char *fontstr) {
779 char *def, **missing;
784 XFreeFontSet(dpy, dc.font.set);
785 dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
788 fprintf(stderr, "dwm: missing fontset: %s\n", missing[n]);
789 XFreeStringList(missing);
792 XFontSetExtents *font_extents;
793 XFontStruct **xfonts;
795 dc.font.ascent = dc.font.descent = 0;
796 font_extents = XExtentsOfFontSet(dc.font.set);
797 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
798 for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
799 dc.font.ascent = MAX(dc.font.ascent, (*xfonts)->ascent);
800 dc.font.descent = MAX(dc.font.descent,(*xfonts)->descent);
806 XFreeFont(dpy, dc.font.xfont);
807 dc.font.xfont = NULL;
808 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr))
809 && !(dc.font.xfont = XLoadQueryFont(dpy, "fixed")))
810 die("error, cannot load font: '%s'\n", fontstr);
811 dc.font.ascent = dc.font.xfont->ascent;
812 dc.font.descent = dc.font.xfont->descent;
814 dc.font.height = dc.font.ascent + dc.font.descent;
818 isoccupied(unsigned int t) {
821 for(c = clients; c; c = c->next)
828 isprotodel(Client *c) {
833 if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
834 for(i = 0; !ret && i < n; i++)
835 if(protocols[i] == wmatom[WMDelete])
843 isurgent(unsigned int t) {
846 for(c = clients; c; c = c->next)
847 if(c->isurgent && c->tags & 1 << t)
853 keypress(XEvent *e) {
859 keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
860 for(i = 0; i < LENGTH(keys); i++)
861 if(keysym == keys[i].keysym
862 && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state)
864 keys[i].func(&(keys[i].arg));
868 killclient(const Arg *arg) {
873 if(isprotodel(sel)) {
874 ev.type = ClientMessage;
875 ev.xclient.window = sel->win;
876 ev.xclient.message_type = wmatom[WMProtocols];
877 ev.xclient.format = 32;
878 ev.xclient.data.l[0] = wmatom[WMDelete];
879 ev.xclient.data.l[1] = CurrentTime;
880 XSendEvent(dpy, sel->win, False, NoEventMask, &ev);
883 XKillClient(dpy, sel->win);
887 manage(Window w, XWindowAttributes *wa) {
888 Client *c, *t = NULL;
893 if(!(c = calloc(1, sizeof(Client))))
894 die("fatal: could not calloc() %u bytes\n", sizeof(Client));
902 c->oldbw = wa->border_width;
903 if(c->w == sw && c->h == sh) {
906 c->bw = wa->border_width;
909 if(c->x + c->w + 2 * c->bw > sx + sw)
910 c->x = sx + sw - c->w - 2 * c->bw;
911 if(c->y + c->h + 2 * c->bw > sy + sh)
912 c->y = sy + sh - c->h - 2 * c->bw;
913 c->x = MAX(c->x, sx);
914 /* only fix client y-offset, if the client center might cover the bar */
915 c->y = MAX(c->y, ((by == 0) && (c->x + (c->w / 2) >= wx) && (c->x + (c->w / 2) < wx + ww)) ? bh : sy);
919 wc.border_width = c->bw;
920 XConfigureWindow(dpy, w, CWBorderWidth, &wc);
921 XSetWindowBorder(dpy, w, dc.norm[ColBorder]);
922 configure(c); /* propagates border_width, if size doesn't change */
924 XSelectInput(dpy, w, EnterWindowMask|FocusChangeMask|PropertyChangeMask|StructureNotifyMask);
925 grabbuttons(c, False);
927 if((rettrans = XGetTransientForHint(dpy, w, &trans) == Success))
928 for(t = clients; t && t->win != trans; t = t->next);
934 c->isfloating = (rettrans == Success) || c->isfixed;
936 XRaiseWindow(dpy, c->win);
939 XMoveResizeWindow(dpy, c->win, c->x + 2 * sw, c->y, c->w, c->h); /* some windows require this */
940 XMapWindow(dpy, c->win);
941 setclientstate(c, NormalState);
946 mappingnotify(XEvent *e) {
947 XMappingEvent *ev = &e->xmapping;
949 XRefreshKeyboardMapping(ev);
950 if(ev->request == MappingKeyboard)
955 maprequest(XEvent *e) {
956 static XWindowAttributes wa;
957 XMapRequestEvent *ev = &e->xmaprequest;
959 if(!XGetWindowAttributes(dpy, ev->window, &wa))
961 if(wa.override_redirect)
963 if(!getclient(ev->window))
964 manage(ev->window, &wa);
971 for(c = nexttiled(clients); c; c = nexttiled(c->next))
972 resize(c, wx, wy, ww - 2 * c->bw, wh - 2 * c->bw, resizehints);
976 movemouse(const Arg *arg) {
977 int x1, y1, ocx, ocy, di, nx, ny;
988 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
989 None, cursor[CurMove], CurrentTime) != GrabSuccess)
991 XQueryPointer(dpy, root, &dummy, &dummy, &x1, &y1, &di, &di, &dui);
993 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
996 XUngrabPointer(dpy, CurrentTime);
998 case ConfigureRequest:
1001 handler[ev.type](&ev);
1005 nx = ocx + (ev.xmotion.x - x1);
1006 ny = ocy + (ev.xmotion.y - y1);
1007 if(snap && nx >= wx && nx <= wx + ww
1008 && ny >= wy && ny <= wy + wh) {
1009 if(abs(wx - nx) < snap)
1011 else if(abs((wx + ww) - (nx + c->w + 2 * c->bw)) < snap)
1012 nx = wx + ww - c->w - 2 * c->bw;
1013 if(abs(wy - ny) < snap)
1015 else if(abs((wy + wh) - (ny + c->h + 2 * c->bw)) < snap)
1016 ny = wy + wh - c->h - 2 * c->bw;
1017 if(!c->isfloating && lt[sellt]->arrange && (abs(nx - c->x) > snap || abs(ny - c->y) > snap))
1018 togglefloating(NULL);
1020 if(!lt[sellt]->arrange || c->isfloating)
1021 resize(c, nx, ny, c->w, c->h, False);
1028 nexttiled(Client *c) {
1029 for(; c && (c->isfloating || !ISVISIBLE(c)); c = c->next);
1034 propertynotify(XEvent *e) {
1037 XPropertyEvent *ev = &e->xproperty;
1039 if(ev->state == PropertyDelete)
1040 return; /* ignore */
1041 if((c = getclient(ev->window))) {
1044 case XA_WM_TRANSIENT_FOR:
1045 XGetTransientForHint(dpy, c->win, &trans);
1046 if(!c->isfloating && (c->isfloating = (getclient(trans) != NULL)))
1049 case XA_WM_NORMAL_HINTS:
1057 if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
1066 quit(const Arg *arg) {
1067 readin = running = False;
1071 resize(Client *c, int x, int y, int w, int h, Bool sizehints) {
1075 /* set minimum possible */
1079 /* temporarily remove base dimensions */
1083 /* adjust for aspect limits */
1084 if(c->mina > 0 && c->maxa > 0) {
1085 if(c->maxa < (float) w/h)
1087 else if(c->mina > (float) h/w)
1091 /* adjust for increment value */
1097 /* restore base dimensions */
1101 w = MAX(w, c->minw);
1102 h = MAX(h, c->minh);
1105 w = MIN(w, c->maxw);
1108 h = MIN(h, c->maxh);
1110 if(w <= 0 || h <= 0)
1113 x = sw - w - 2 * c->bw;
1115 y = sh - h - 2 * c->bw;
1116 if(x + w + 2 * c->bw < sx)
1118 if(y + h + 2 * c->bw < sy)
1124 if(c->x != x || c->y != y || c->w != w || c->h != h) {
1127 c->w = wc.width = w;
1128 c->h = wc.height = h;
1129 wc.border_width = c->bw;
1130 XConfigureWindow(dpy, c->win,
1131 CWX|CWY|CWWidth|CWHeight|CWBorderWidth, &wc);
1138 resizemouse(const Arg *arg) {
1149 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1150 None, cursor[CurResize], CurrentTime) != GrabSuccess)
1152 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->bw - 1, c->h + c->bw - 1);
1154 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask , &ev);
1157 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0,
1158 c->w + c->bw - 1, c->h + c->bw - 1);
1159 XUngrabPointer(dpy, CurrentTime);
1160 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1162 case ConfigureRequest:
1165 handler[ev.type](&ev);
1169 nw = MAX(ev.xmotion.x - ocx - 2 * c->bw + 1, 1);
1170 nh = MAX(ev.xmotion.y - ocy - 2 * c->bw + 1, 1);
1172 if(snap && nw >= wx && nw <= wx + ww
1173 && nh >= wy && nh <= wy + wh) {
1174 if(!c->isfloating && lt[sellt]->arrange
1175 && (abs(nw - c->w) > snap || abs(nh - c->h) > snap))
1176 togglefloating(NULL);
1178 if(!lt[sellt]->arrange || c->isfloating)
1179 resize(c, c->x, c->y, nw, nh, True);
1194 if(sel->isfloating || !lt[sellt]->arrange)
1195 XRaiseWindow(dpy, sel->win);
1196 if(lt[sellt]->arrange) {
1197 wc.stack_mode = Below;
1198 wc.sibling = barwin;
1199 for(c = stack; c; c = c->snext)
1200 if(!c->isfloating && ISVISIBLE(c)) {
1201 XConfigureWindow(dpy, c->win, CWSibling|CWStackMode, &wc);
1202 wc.sibling = c->win;
1206 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1212 char sbuf[sizeof stext];
1215 unsigned int len, offset;
1218 /* main event loop, also reads status text from stdin */
1220 xfd = ConnectionNumber(dpy);
1223 len = sizeof stext - 1;
1224 sbuf[len] = stext[len] = '\0'; /* 0-terminator is never touched */
1228 FD_SET(STDIN_FILENO, &rd);
1230 if(select(xfd + 1, &rd, NULL, NULL, NULL) == -1) {
1233 die("select failed\n");
1235 if(FD_ISSET(STDIN_FILENO, &rd)) {
1236 switch((r = read(STDIN_FILENO, sbuf + offset, len - offset))) {
1238 strncpy(stext, strerror(errno), len);
1242 strncpy(stext, "EOF", 4);
1246 for(p = sbuf + offset; r > 0; p++, r--, offset++)
1247 if(*p == '\n' || *p == '\0') {
1249 strncpy(stext, sbuf, len);
1250 p += r - 1; /* p is sbuf + offset + r - 1 */
1251 for(r = 0; *(p - r) && *(p - r) != '\n'; r++);
1254 memmove(sbuf, p - r + 1, r);
1261 while(XPending(dpy)) {
1262 XNextEvent(dpy, &ev);
1263 if(handler[ev.type])
1264 (handler[ev.type])(&ev); /* call handler */
1271 unsigned int i, num;
1272 Window *wins, d1, d2;
1273 XWindowAttributes wa;
1276 if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1277 for(i = 0; i < num; i++) {
1278 if(!XGetWindowAttributes(dpy, wins[i], &wa)
1279 || wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1281 if(wa.map_state == IsViewable || getstate(wins[i]) == IconicState)
1282 manage(wins[i], &wa);
1284 for(i = 0; i < num; i++) { /* now the transients */
1285 if(!XGetWindowAttributes(dpy, wins[i], &wa))
1287 if(XGetTransientForHint(dpy, wins[i], &d1)
1288 && (wa.map_state == IsViewable || getstate(wins[i]) == IconicState))
1289 manage(wins[i], &wa);
1297 setclientstate(Client *c, long state) {
1298 long data[] = {state, None};
1300 XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1301 PropModeReplace, (unsigned char *)data, 2);
1305 setlayout(const Arg *arg) {
1306 if(!arg || !arg->v || arg->v != lt[sellt])
1309 lt[sellt] = (Layout *)arg->v;
1316 /* arg > 1.0 will set mfact absolutly */
1318 setmfact(const Arg *arg) {
1321 if(!arg || !lt[sellt]->arrange)
1323 f = arg->f < 1.0 ? arg->f + mfact : arg->f - 1.0;
1324 if(f < 0.1 || f > 0.9)
1334 XSetWindowAttributes wa;
1337 screen = DefaultScreen(dpy);
1338 root = RootWindow(dpy, screen);
1342 sw = DisplayWidth(dpy, screen);
1343 sh = DisplayHeight(dpy, screen);
1344 bh = dc.h = dc.font.height + 2;
1345 lt[0] = &layouts[0];
1346 lt[1] = &layouts[1 % LENGTH(layouts)];
1350 wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1351 wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1352 wmatom[WMName] = XInternAtom(dpy, "WM_NAME", False);
1353 wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1354 netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1355 netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1358 wa.cursor = cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1359 cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1360 cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1362 /* init appearance */
1363 dc.norm[ColBorder] = getcolor(normbordercolor);
1364 dc.norm[ColBG] = getcolor(normbgcolor);
1365 dc.norm[ColFG] = getcolor(normfgcolor);
1366 dc.sel[ColBorder] = getcolor(selbordercolor);
1367 dc.sel[ColBG] = getcolor(selbgcolor);
1368 dc.sel[ColFG] = getcolor(selfgcolor);
1369 dc.drawable = XCreatePixmap(dpy, root, DisplayWidth(dpy, screen), bh, DefaultDepth(dpy, screen));
1370 dc.gc = XCreateGC(dpy, root, 0, 0);
1371 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
1373 XSetFont(dpy, dc.gc, dc.font.xfont->fid);
1376 for(blw = i = 0; LENGTH(layouts) > 1 && i < LENGTH(layouts); i++) {
1377 w = TEXTW(layouts[i].symbol);
1381 wa.override_redirect = 1;
1382 wa.background_pixmap = ParentRelative;
1383 wa.event_mask = ButtonPressMask|ExposureMask;
1385 barwin = XCreateWindow(dpy, root, wx, by, ww, bh, 0, DefaultDepth(dpy, screen),
1386 CopyFromParent, DefaultVisual(dpy, screen),
1387 CWOverrideRedirect|CWBackPixmap|CWEventMask, &wa);
1388 XDefineCursor(dpy, barwin, cursor[CurNormal]);
1389 XMapRaised(dpy, barwin);
1390 strcpy(stext, "dwm-"VERSION);
1393 /* EWMH support per view */
1394 XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1395 PropModeReplace, (unsigned char *) netatom, NetLast);
1397 /* select for events */
1398 wa.event_mask = SubstructureRedirectMask|SubstructureNotifyMask|ButtonPressMask
1399 |EnterWindowMask|LeaveWindowMask|StructureNotifyMask;
1400 XChangeWindowAttributes(dpy, root, CWEventMask|CWCursor, &wa);
1401 XSelectInput(dpy, root, wa.event_mask);
1409 spawn(const Arg *arg) {
1410 /* The double-fork construct avoids zombie processes and keeps the code
1411 * clean from stupid signal handlers. */
1415 close(ConnectionNumber(dpy));
1417 execvp(((char **)arg->v)[0], (char **)arg->v);
1418 fprintf(stderr, "dwm: execvp %s", ((char **)arg->v)[0]);
1427 tag(const Arg *arg) {
1428 if(sel && arg->ui & TAGMASK) {
1429 sel->tags = arg->ui & TAGMASK;
1435 textnw(const char *text, unsigned int len) {
1439 XmbTextExtents(dc.font.set, text, len, NULL, &r);
1442 return XTextWidth(dc.font.xfont, text, len);
1451 for(n = 0, c = nexttiled(clients); c; c = nexttiled(c->next), n++);
1456 c = nexttiled(clients);
1458 resize(c, wx, wy, (n == 1 ? ww : mw) - 2 * c->bw, wh - 2 * c->bw, resizehints);
1464 x = (wx + mw > c->x + c->w) ? c->x + c->w + 2 * c->bw : wx + mw;
1466 w = (wx + mw > c->x + c->w) ? wx + ww - x : ww - mw;
1471 for(i = 0, c = nexttiled(c->next); c; c = nexttiled(c->next), i++) {
1472 resize(c, x, y, w - 2 * c->bw, /* remainder */ ((i + 1 == n)
1473 ? (wy + wh) - y : h) - 2 * c->bw, resizehints);
1475 y = c->y + c->h + 2 * c->bw;
1480 togglebar(const Arg *arg) {
1488 togglefloating(const Arg *arg) {
1491 sel->isfloating = !sel->isfloating || sel->isfixed;
1493 resize(sel, sel->x, sel->y, sel->w, sel->h, True);
1498 toggletag(const Arg *arg) {
1499 unsigned int mask = sel->tags ^ (arg->ui & TAGMASK);
1508 toggleview(const Arg *arg) {
1509 unsigned int mask = tagset[seltags] ^ (arg->ui & TAGMASK);
1512 tagset[seltags] = mask;
1519 unmanage(Client *c) {
1522 wc.border_width = c->oldbw;
1523 /* The server grab construct avoids race conditions. */
1525 XSetErrorHandler(xerrordummy);
1526 XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
1531 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1532 setclientstate(c, WithdrawnState);
1535 XSetErrorHandler(xerror);
1541 unmapnotify(XEvent *e) {
1543 XUnmapEvent *ev = &e->xunmap;
1545 if((c = getclient(ev->window)))
1551 if(dc.drawable != 0)
1552 XFreePixmap(dpy, dc.drawable);
1553 dc.drawable = XCreatePixmap(dpy, root, ww, bh, DefaultDepth(dpy, screen));
1554 XMoveResizeWindow(dpy, barwin, wx, by, ww, bh);
1561 XineramaScreenInfo *info = NULL;
1563 /* window area geometry */
1564 if(XineramaIsActive(dpy)) {
1565 info = XineramaQueryScreens(dpy, &i);
1566 wx = info[xidx].x_org;
1567 wy = showbar && topbar ? info[xidx].y_org + bh : info[xidx].y_org;
1568 ww = info[xidx].width;
1569 wh = showbar ? info[xidx].height - bh : info[xidx].height;
1576 wy = showbar && topbar ? sy + bh : sy;
1578 wh = showbar ? sh - bh : sh;
1582 by = showbar ? (topbar ? wy - bh : wy + wh) : -bh;
1586 updatesizehints(Client *c) {
1590 XGetWMNormalHints(dpy, c->win, &size, &msize);
1591 if(size.flags & PBaseSize) {
1592 c->basew = size.base_width;
1593 c->baseh = size.base_height;
1595 else if(size.flags & PMinSize) {
1596 c->basew = size.min_width;
1597 c->baseh = size.min_height;
1600 c->basew = c->baseh = 0;
1601 if(size.flags & PResizeInc) {
1602 c->incw = size.width_inc;
1603 c->inch = size.height_inc;
1606 c->incw = c->inch = 0;
1607 if(size.flags & PMaxSize) {
1608 c->maxw = size.max_width;
1609 c->maxh = size.max_height;
1612 c->maxw = c->maxh = 0;
1613 if(size.flags & PMinSize) {
1614 c->minw = size.min_width;
1615 c->minh = size.min_height;
1617 else if(size.flags & PBaseSize) {
1618 c->minw = size.base_width;
1619 c->minh = size.base_height;
1622 c->minw = c->minh = 0;
1623 if(size.flags & PAspect) {
1624 c->mina = (float)size.min_aspect.y / (float)size.min_aspect.x;
1625 c->maxa = (float)size.max_aspect.x / (float)size.max_aspect.y;
1628 c->maxa = c->mina = 0.0;
1629 c->isfixed = (c->maxw && c->minw && c->maxh && c->minh
1630 && c->maxw == c->minw && c->maxh == c->minh);
1634 updatetitle(Client *c) {
1635 if(!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
1636 gettextprop(c->win, wmatom[WMName], c->name, sizeof c->name);
1640 updatewmhints(Client *c) {
1643 if((wmh = XGetWMHints(dpy, c->win))) {
1644 if(ISVISIBLE(c) && wmh->flags & XUrgencyHint) {
1645 wmh->flags &= ~XUrgencyHint;
1646 XSetWMHints(dpy, c->win, wmh);
1649 c->isurgent = (wmh->flags & XUrgencyHint) ? True : False;
1656 view(const Arg *arg) {
1657 if(arg && (arg->i & TAGMASK) == tagset[seltags])
1659 seltags ^= 1; /* toggle sel tagset */
1660 if(arg && (arg->ui & TAGMASK))
1661 tagset[seltags] = arg->i & TAGMASK;
1666 /* There's no way to check accesses to destroyed windows, thus those cases are
1667 * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
1668 * default error handler, which may call exit. */
1670 xerror(Display *dpy, XErrorEvent *ee) {
1671 if(ee->error_code == BadWindow
1672 || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1673 || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1674 || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1675 || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1676 || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1677 || (ee->request_code == X_GrabButton && ee->error_code == BadAccess)
1678 || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1679 || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1681 fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1682 ee->request_code, ee->error_code);
1683 return xerrorxlib(dpy, ee); /* may call exit */
1687 xerrordummy(Display *dpy, XErrorEvent *ee) {
1691 /* Startup Error handler to check if another window manager
1692 * is already running. */
1694 xerrorstart(Display *dpy, XErrorEvent *ee) {
1700 zoom(const Arg *arg) {
1703 if(!lt[sellt]->arrange || lt[sellt]->arrange == monocle || (sel && sel->isfloating))
1705 if(c == nexttiled(clients))
1706 if(!c || !(c = nexttiled(c->next)))
1715 main(int argc, char *argv[]) {
1716 if(argc == 2 && !strcmp("-v", argv[1]))
1717 die("dwm-"VERSION", © 2006-2008 dwm engineers, see LICENSE for details\n");
1719 die("usage: dwm [-v]\n");
1721 if(!setlocale(LC_CTYPE, "") || !XSupportsLocale())
1722 fprintf(stderr, "warning: no locale support\n");
1724 if(!(dpy = XOpenDisplay(0)))
1725 die("dwm: cannot open display\n");