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 BUTTONMASK (ButtonPressMask|ButtonReleaseMask)
48 #define CLEANMASK(mask) (mask & ~(numlockmask|LockMask))
49 #define INRECT(X,Y,RX,RY,RW,RH) ((X) >= (RX) && (X) < (RX) + (RW) && (Y) >= (RY) && (Y) < (RY) + (RH))
50 #define ISVISIBLE(x) (x->tags & tagset[seltags])
51 #define LENGTH(x) (sizeof x / sizeof x[0])
52 #define MAX(a, b) ((a) > (b) ? (a) : (b))
53 #define MIN(a, b) ((a) < (b) ? (a) : (b))
55 #define MOUSEMASK (BUTTONMASK|PointerMotionMask)
56 #define TAGMASK ((int)((1LL << LENGTH(tags)) - 1))
57 #define TEXTW(x) (textnw(x, strlen(x)) + dc.font.height)
60 enum { CurNormal, CurResize, CurMove, CurLast }; /* cursor */
61 enum { ColBorder, ColFG, ColBG, ColLast }; /* color */
62 enum { NetSupported, NetWMName, NetLast }; /* EWMH atoms */
63 enum { WMProtocols, WMDelete, WMName, WMState, WMLast };/* default atoms */
64 enum { ClkTagBar, ClkLtSymbol, ClkStatusText, ClkWinTitle,
65 ClkClientWin, ClkRootWin, ClkLast }; /* clicks */
78 void (*func)(const Arg *arg);
82 typedef struct Client Client;
87 int basew, baseh, incw, inch, maxw, maxh, minw, minh;
90 Bool isfixed, isfloating, isurgent;
98 unsigned long norm[ColLast];
99 unsigned long sel[ColLast];
109 } DC; /* draw context */
114 void (*func)(const Arg *);
120 void (*arrange)(void);
125 const char *instance;
131 /* function declarations */
132 static void applyrules(Client *c);
133 static void arrange(void);
134 static void attach(Client *c);
135 static void attachstack(Client *c);
136 static void buttonpress(XEvent *e);
137 static void checkotherwm(void);
138 static void cleanup(void);
139 static void clearurgent(void);
140 static void configure(Client *c);
141 static void configurenotify(XEvent *e);
142 static void configurerequest(XEvent *e);
143 static void destroynotify(XEvent *e);
144 static void detach(Client *c);
145 static void detachstack(Client *c);
146 static void die(const char *errstr, ...);
147 static void drawbar(void);
148 static void drawsquare(Bool filled, Bool empty, Bool invert, unsigned long col[ColLast]);
149 static void drawtext(const char *text, unsigned long col[ColLast], Bool invert);
150 static void enternotify(XEvent *e);
151 static void expose(XEvent *e);
152 static void focus(Client *c);
153 static void focusin(XEvent *e);
154 static void focusstack(const Arg *arg);
155 static Client *getclient(Window w);
156 static unsigned long getcolor(const char *colstr);
157 static long getstate(Window w);
158 static Bool gettextprop(Window w, Atom atom, char *text, unsigned int size);
159 static void grabbuttons(Client *c, Bool focused);
160 static void grabkeys(void);
161 static void initfont(const char *fontstr);
162 static Bool isoccupied(unsigned int t);
163 static Bool isprotodel(Client *c);
164 static Bool isurgent(unsigned int t);
165 static void keypress(XEvent *e);
166 static void killclient(const Arg *arg);
167 static void manage(Window w, XWindowAttributes *wa);
168 static void mappingnotify(XEvent *e);
169 static void maprequest(XEvent *e);
170 static void monocle(void);
171 static void movemouse(const Arg *arg);
172 static Client *nexttiled(Client *c);
173 static void propertynotify(XEvent *e);
174 static void quit(const Arg *arg);
175 static void resize(Client *c, int x, int y, int w, int h, Bool sizehints);
176 static void resizemouse(const Arg *arg);
177 static void restack(void);
178 static void run(void);
179 static void scan(void);
180 static void setclientstate(Client *c, long state);
181 static void setlayout(const Arg *arg);
182 static void setmfact(const Arg *arg);
183 static void setup(void);
184 static void spawn(const Arg *arg);
185 static void tag(const Arg *arg);
186 static int textnw(const char *text, unsigned int len);
187 static void tile(void);
188 static void togglebar(const Arg *arg);
189 static void togglefloating(const Arg *arg);
190 static void toggletag(const Arg *arg);
191 static void toggleview(const Arg *arg);
192 static void unmanage(Client *c);
193 static void unmapnotify(XEvent *e);
194 static void updatebar(void);
195 static void updategeom(void);
196 static void updatesizehints(Client *c);
197 static void updatetitle(Client *c);
198 static void updatewmhints(Client *c);
199 static void view(const Arg *arg);
200 static int xerror(Display *dpy, XErrorEvent *ee);
201 static int xerrordummy(Display *dpy, XErrorEvent *ee);
202 static int xerrorstart(Display *dpy, XErrorEvent *ee);
203 static void zoom(const Arg *arg);
206 static char stext[256];
207 static int screen, sx, sy, sw, sh;
208 static int by, bh, blw, wx, wy, ww, wh;
209 static unsigned int seltags = 0, sellt = 0;
210 static int (*xerrorxlib)(Display *, XErrorEvent *);
211 static unsigned int numlockmask = 0;
212 static void (*handler[LASTEvent]) (XEvent *) = {
213 [ButtonPress] = buttonpress,
214 [ConfigureRequest] = configurerequest,
215 [ConfigureNotify] = configurenotify,
216 [DestroyNotify] = destroynotify,
217 [EnterNotify] = enternotify,
220 [KeyPress] = keypress,
221 [MappingNotify] = mappingnotify,
222 [MapRequest] = maprequest,
223 [PropertyNotify] = propertynotify,
224 [UnmapNotify] = unmapnotify
226 static Atom wmatom[WMLast], netatom[NetLast];
227 static Bool otherwm, readin;
228 static Bool running = True;
229 static unsigned int tagset[] = {1, 1}; /* after start, first tag is selected */
230 static Client *clients = NULL;
231 static Client *sel = NULL;
232 static Client *stack = NULL;
233 static Cursor cursor[CurLast];
236 static Layout *lt[] = { NULL, NULL };
237 static Window root, barwin;
238 /* configuration, allows nested code to access above variables */
241 /* compile-time check if all tags fit into an unsigned int bit array. */
242 struct NumTags { char limitexceeded[sizeof(unsigned int) * 8 < LENGTH(tags) ? -1 : 1]; };
244 /* function implementations */
246 applyrules(Client *c) {
249 XClassHint ch = { 0 };
252 XGetClassHint(dpy, c->win, &ch);
253 for(i = 0; i < LENGTH(rules); i++) {
255 if((!r->title || strstr(c->name, r->title))
256 && (!r->class || (ch.res_class && strstr(ch.res_class, r->class)))
257 && (!r->instance || (ch.res_name && strstr(ch.res_name, r->instance)))) {
258 c->isfloating = r->isfloating;
259 c->tags |= r->tags & TAGMASK;
267 c->tags = tagset[seltags];
274 for(c = clients; c; c = c->next)
276 XMoveWindow(dpy, c->win, c->x, c->y);
277 if(!lt[sellt]->arrange || c->isfloating)
278 resize(c, c->x, c->y, c->w, c->h, True);
281 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
285 if(lt[sellt]->arrange)
286 lt[sellt]->arrange();
297 attachstack(Client *c) {
303 buttonpress(XEvent *e) {
304 unsigned int i, x, click;
307 XButtonPressedEvent *ev = &e->xbutton;
310 if(ev->window == barwin) {
312 do x += TEXTW(tags[i]); while(ev->x >= x && ++i < LENGTH(tags));
313 if(i < LENGTH(tags)) {
317 else if(ev->x < x + blw)
319 else if(ev->x > wx + ww - TEXTW(stext))
320 click = ClkStatusText;
324 else if((c = getclient(ev->window))) {
326 click = ClkClientWin;
329 for(i = 0; i < LENGTH(buttons); i++)
330 if(click == buttons[i].click && buttons[i].func && buttons[i].button == ev->button
331 && CLEANMASK(buttons[i].mask) == CLEANMASK(ev->state))
332 buttons[i].func(click == ClkTagBar ? &arg : &buttons[i].arg);
338 XSetErrorHandler(xerrorstart);
340 /* this causes an error if some other window manager is running */
341 XSelectInput(dpy, DefaultRootWindow(dpy), SubstructureRedirectMask);
344 die("dwm: another window manager is already running\n");
345 XSetErrorHandler(NULL);
346 xerrorxlib = XSetErrorHandler(xerror);
353 Layout foo = { "", NULL };
361 XFreeFontSet(dpy, dc.font.set);
363 XFreeFont(dpy, dc.font.xfont);
364 XUngrabKey(dpy, AnyKey, AnyModifier, root);
365 XFreePixmap(dpy, dc.drawable);
367 XFreeCursor(dpy, cursor[CurNormal]);
368 XFreeCursor(dpy, cursor[CurResize]);
369 XFreeCursor(dpy, cursor[CurMove]);
370 XDestroyWindow(dpy, barwin);
372 XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime);
380 for(c = clients; c; c = c->next)
381 if(ISVISIBLE(c) && c->isurgent) {
383 if (!(wmh = XGetWMHints(dpy, c->win)))
386 wmh->flags &= ~XUrgencyHint;
387 XSetWMHints(dpy, c->win, wmh);
393 configure(Client *c) {
396 ce.type = ConfigureNotify;
404 ce.border_width = c->bw;
406 ce.override_redirect = False;
407 XSendEvent(dpy, c->win, False, StructureNotifyMask, (XEvent *)&ce);
411 configurenotify(XEvent *e) {
412 XConfigureEvent *ev = &e->xconfigure;
414 if(ev->window == root && (ev->width != sw || ev->height != sh)) {
424 configurerequest(XEvent *e) {
426 XConfigureRequestEvent *ev = &e->xconfigurerequest;
429 if((c = getclient(ev->window))) {
430 if(ev->value_mask & CWBorderWidth)
431 c->bw = ev->border_width;
432 else if(c->isfloating || !lt[sellt]->arrange) {
433 if(ev->value_mask & CWX)
435 if(ev->value_mask & CWY)
437 if(ev->value_mask & CWWidth)
439 if(ev->value_mask & CWHeight)
441 if((c->x - sx + c->w) > sw && c->isfloating)
442 c->x = sx + (sw / 2 - c->w / 2); /* center in x direction */
443 if((c->y - sy + c->h) > sh && c->isfloating)
444 c->y = sy + (sh / 2 - c->h / 2); /* center in y direction */
445 if((ev->value_mask & (CWX|CWY)) && !(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)))
479 for(tc = &clients; *tc && *tc != c; tc = &(*tc)->next);
484 detachstack(Client *c) {
487 for(tc = &stack; *tc && *tc != c; tc = &(*tc)->snext);
492 die(const char *errstr, ...) {
495 va_start(ap, errstr);
496 vfprintf(stderr, errstr, ap);
506 for(i = 0; i < LENGTH(tags); i++) {
507 dc.w = TEXTW(tags[i]);
508 if(tagset[seltags] & 1 << i) {
509 drawtext(tags[i], dc.sel, isurgent(i));
510 drawsquare(sel && sel->tags & 1 << i, isoccupied(i), isurgent(i), dc.sel);
513 drawtext(tags[i], dc.norm, isurgent(i));
514 drawsquare(sel && sel->tags & 1 << i, isoccupied(i), isurgent(i), dc.norm);
520 drawtext(lt[sellt]->symbol, dc.norm, False);
531 drawtext(stext, dc.norm, False);
532 if((dc.w = dc.x - x) > bh) {
535 drawtext(sel->name, dc.sel, False);
536 drawsquare(sel->isfixed, sel->isfloating, False, dc.sel);
539 drawtext(NULL, dc.norm, False);
541 XCopyArea(dpy, dc.drawable, barwin, dc.gc, 0, 0, ww, bh, 0, 0);
546 drawsquare(Bool filled, Bool empty, Bool invert, unsigned long col[ColLast]) {
549 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
551 gcv.foreground = col[invert ? ColBG : ColFG];
552 XChangeGC(dpy, dc.gc, GCForeground, &gcv);
553 x = (dc.font.ascent + dc.font.descent + 2) / 4;
557 r.width = r.height = x + 1;
558 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
561 r.width = r.height = x;
562 XDrawRectangles(dpy, dc.drawable, dc.gc, &r, 1);
567 drawtext(const char *text, unsigned long col[ColLast], Bool invert) {
568 int i, x, y, h, len, olen;
569 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
572 XSetForeground(dpy, dc.gc, col[invert ? ColFG : ColBG]);
573 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
577 len = MIN(olen, sizeof buf);
578 memcpy(buf, text, len);
579 h = dc.font.ascent + dc.font.descent;
580 y = dc.y + (dc.h / 2) - (h / 2) + dc.font.ascent;
582 /* shorten text if necessary */
583 for(; len && (i = textnw(buf, len)) > dc.w - h; len--);
587 for(i = len; i && i > len - 3; buf[--i] = '.');
588 XSetForeground(dpy, dc.gc, col[invert ? ColBG : ColFG]);
590 XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
592 XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
596 enternotify(XEvent *e) {
598 XCrossingEvent *ev = &e->xcrossing;
600 if((ev->mode != NotifyNormal || ev->detail == NotifyInferior) && ev->window != root)
602 if((c = getclient(ev->window)))
610 XExposeEvent *ev = &e->xexpose;
612 if(ev->count == 0 && (ev->window == barwin))
618 if(!c || !ISVISIBLE(c))
619 for(c = stack; c && !ISVISIBLE(c); c = c->snext);
620 if(sel && sel != c) {
621 grabbuttons(sel, False);
622 XSetWindowBorder(dpy, sel->win, dc.norm[ColBorder]);
627 grabbuttons(c, True);
628 XSetWindowBorder(dpy, c->win, dc.sel[ColBorder]);
629 XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
632 XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
638 focusin(XEvent *e) { /* there are some broken focus acquiring clients */
639 XFocusChangeEvent *ev = &e->xfocus;
641 if(sel && ev->window != sel->win)
642 XSetInputFocus(dpy, sel->win, RevertToPointerRoot, CurrentTime);
646 focusstack(const Arg *arg) {
647 Client *c = NULL, *i;
652 for(c = sel->next; c && !ISVISIBLE(c); c = c->next);
654 for(c = clients; c && !ISVISIBLE(c); c = c->next);
657 for(i = clients; i != sel; i = i->next)
661 for(; i; i = i->next)
672 getclient(Window w) {
675 for(c = clients; c && c->win != w; c = c->next);
680 getcolor(const char *colstr) {
681 Colormap cmap = DefaultColormap(dpy, screen);
684 if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
685 die("error, cannot allocate color '%s'\n", colstr);
693 unsigned char *p = NULL;
694 unsigned long n, extra;
697 status = XGetWindowProperty(dpy, w, wmatom[WMState], 0L, 2L, False, wmatom[WMState],
698 &real, &format, &n, &extra, (unsigned char **)&p);
699 if(status != Success)
708 gettextprop(Window w, Atom atom, char *text, unsigned int size) {
713 if(!text || size == 0)
716 XGetTextProperty(dpy, w, &name, atom);
719 if(name.encoding == XA_STRING)
720 strncpy(text, (char *)name.value, size - 1);
722 if(XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success
724 strncpy(text, *list, size - 1);
725 XFreeStringList(list);
728 text[size - 1] = '\0';
734 grabbuttons(Client *c, Bool focused) {
736 unsigned int modifiers[] = { 0, LockMask, numlockmask, numlockmask|LockMask };
738 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
740 for(i = 0; i < LENGTH(buttons); i++)
741 if(buttons[i].click == ClkClientWin)
742 for(j = 0; j < LENGTH(modifiers); j++)
743 XGrabButton(dpy, buttons[i].button, buttons[i].mask | modifiers[j], c->win, False, BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
745 XGrabButton(dpy, AnyButton, AnyModifier, c->win, False,
746 BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
753 XModifierKeymap *modmap;
755 /* init modifier map */
756 modmap = XGetModifierMapping(dpy);
757 for(i = 0; i < 8; i++)
758 for(j = 0; j < modmap->max_keypermod; j++) {
759 if(modmap->modifiermap[i * modmap->max_keypermod + j] == XKeysymToKeycode(dpy, XK_Num_Lock))
760 numlockmask = (1 << i);
762 XFreeModifiermap(modmap);
764 XUngrabKey(dpy, AnyKey, AnyModifier, root);
765 for(i = 0; i < LENGTH(keys); i++) {
766 code = XKeysymToKeycode(dpy, keys[i].keysym);
767 XGrabKey(dpy, code, keys[i].mod, root, True,
768 GrabModeAsync, GrabModeAsync);
769 XGrabKey(dpy, code, keys[i].mod|LockMask, root, True,
770 GrabModeAsync, GrabModeAsync);
771 XGrabKey(dpy, code, keys[i].mod|numlockmask, root, True,
772 GrabModeAsync, GrabModeAsync);
773 XGrabKey(dpy, code, keys[i].mod|numlockmask|LockMask, root, True,
774 GrabModeAsync, GrabModeAsync);
779 initfont(const char *fontstr) {
780 char *def, **missing;
785 XFreeFontSet(dpy, dc.font.set);
786 dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
789 fprintf(stderr, "dwm: missing fontset: %s\n", missing[n]);
790 XFreeStringList(missing);
793 XFontSetExtents *font_extents;
794 XFontStruct **xfonts;
796 dc.font.ascent = dc.font.descent = 0;
797 font_extents = XExtentsOfFontSet(dc.font.set);
798 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
799 for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
800 dc.font.ascent = MAX(dc.font.ascent, (*xfonts)->ascent);
801 dc.font.descent = MAX(dc.font.descent,(*xfonts)->descent);
807 XFreeFont(dpy, dc.font.xfont);
808 dc.font.xfont = NULL;
809 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr))
810 && !(dc.font.xfont = XLoadQueryFont(dpy, "fixed")))
811 die("error, cannot load font: '%s'\n", fontstr);
812 dc.font.ascent = dc.font.xfont->ascent;
813 dc.font.descent = dc.font.xfont->descent;
815 dc.font.height = dc.font.ascent + dc.font.descent;
819 isoccupied(unsigned int t) {
822 for(c = clients; c; c = c->next)
829 isprotodel(Client *c) {
834 if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
835 for(i = 0; !ret && i < n; i++)
836 if(protocols[i] == wmatom[WMDelete])
844 isurgent(unsigned int t) {
847 for(c = clients; c; c = c->next)
848 if(c->isurgent && c->tags & 1 << t)
854 keypress(XEvent *e) {
860 keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
861 for(i = 0; i < LENGTH(keys); i++)
862 if(keysym == keys[i].keysym
863 && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state)
865 keys[i].func(&(keys[i].arg));
869 killclient(const Arg *arg) {
874 if(isprotodel(sel)) {
875 ev.type = ClientMessage;
876 ev.xclient.window = sel->win;
877 ev.xclient.message_type = wmatom[WMProtocols];
878 ev.xclient.format = 32;
879 ev.xclient.data.l[0] = wmatom[WMDelete];
880 ev.xclient.data.l[1] = CurrentTime;
881 XSendEvent(dpy, sel->win, False, NoEventMask, &ev);
884 XKillClient(dpy, sel->win);
888 manage(Window w, XWindowAttributes *wa) {
889 Client *c, *t = NULL;
894 if(!(c = calloc(1, sizeof(Client))))
895 die("fatal: could not calloc() %u bytes\n", sizeof(Client));
903 c->oldbw = wa->border_width;
904 if(c->w == sw && c->h == sh) {
907 c->bw = wa->border_width;
910 if(c->x + c->w + 2 * c->bw > sx + sw)
911 c->x = sx + sw - c->w - 2 * c->bw;
912 if(c->y + c->h + 2 * c->bw > sy + sh)
913 c->y = sy + sh - c->h - 2 * c->bw;
914 c->x = MAX(c->x, sx);
915 /* only fix client y-offset, if the client center might cover the bar */
916 c->y = MAX(c->y, ((by == 0) && (c->x + (c->w / 2) >= wx) && (c->x + (c->w / 2) < wx + ww)) ? bh : sy);
920 wc.border_width = c->bw;
921 XConfigureWindow(dpy, w, CWBorderWidth, &wc);
922 XSetWindowBorder(dpy, w, dc.norm[ColBorder]);
923 configure(c); /* propagates border_width, if size doesn't change */
925 XSelectInput(dpy, w, EnterWindowMask|FocusChangeMask|PropertyChangeMask|StructureNotifyMask);
926 grabbuttons(c, False);
928 if((rettrans = XGetTransientForHint(dpy, w, &trans) == Success))
929 for(t = clients; t && t->win != trans; t = t->next);
935 c->isfloating = (rettrans == Success) || c->isfixed;
937 XRaiseWindow(dpy, c->win);
940 XMoveResizeWindow(dpy, c->win, c->x + 2 * sw, c->y, c->w, c->h); /* some windows require this */
941 XMapWindow(dpy, c->win);
942 setclientstate(c, NormalState);
947 mappingnotify(XEvent *e) {
948 XMappingEvent *ev = &e->xmapping;
950 XRefreshKeyboardMapping(ev);
951 if(ev->request == MappingKeyboard)
956 maprequest(XEvent *e) {
957 static XWindowAttributes wa;
958 XMapRequestEvent *ev = &e->xmaprequest;
960 if(!XGetWindowAttributes(dpy, ev->window, &wa))
962 if(wa.override_redirect)
964 if(!getclient(ev->window))
965 manage(ev->window, &wa);
972 for(c = nexttiled(clients); c; c = nexttiled(c->next))
973 resize(c, wx, wy, ww - 2 * c->bw, wh - 2 * c->bw, resizehints);
977 movemouse(const Arg *arg) {
978 int x, y, ocx, ocy, di, nx, ny;
989 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
990 None, cursor[CurMove], CurrentTime) != GrabSuccess)
992 XQueryPointer(dpy, root, &dummy, &dummy, &x, &y, &di, &di, &dui);
994 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
997 XUngrabPointer(dpy, CurrentTime);
999 case ConfigureRequest:
1002 handler[ev.type](&ev);
1006 nx = ocx + (ev.xmotion.x - x);
1007 ny = ocy + (ev.xmotion.y - y);
1008 if(snap && nx >= wx && nx <= wx + ww
1009 && ny >= wy && ny <= wy + wh) {
1010 if(abs(wx - nx) < snap)
1012 else if(abs((wx + ww) - (nx + c->w + 2 * c->bw)) < snap)
1013 nx = wx + ww - c->w - 2 * c->bw;
1014 if(abs(wy - ny) < snap)
1016 else if(abs((wy + wh) - (ny + c->h + 2 * c->bw)) < snap)
1017 ny = wy + wh - c->h - 2 * c->bw;
1018 if(!c->isfloating && lt[sellt]->arrange && (abs(nx - c->x) > snap || abs(ny - c->y) > snap))
1019 togglefloating(NULL);
1021 if(!lt[sellt]->arrange || c->isfloating)
1022 resize(c, nx, ny, c->w, c->h, False);
1029 nexttiled(Client *c) {
1030 for(; c && (c->isfloating || !ISVISIBLE(c)); c = c->next);
1035 propertynotify(XEvent *e) {
1038 XPropertyEvent *ev = &e->xproperty;
1040 if(ev->state == PropertyDelete)
1041 return; /* ignore */
1042 if((c = getclient(ev->window))) {
1045 case XA_WM_TRANSIENT_FOR:
1046 XGetTransientForHint(dpy, c->win, &trans);
1047 if(!c->isfloating && (c->isfloating = (getclient(trans) != NULL)))
1050 case XA_WM_NORMAL_HINTS:
1058 if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
1067 quit(const Arg *arg) {
1068 readin = running = False;
1072 resize(Client *c, int x, int y, int w, int h, Bool sizehints) {
1076 /* set minimum possible */
1080 /* temporarily remove base dimensions */
1084 /* adjust for aspect limits */
1085 if(c->mina > 0 && c->maxa > 0) {
1086 if(c->maxa < (float) w/h)
1088 else if(c->mina > (float) h/w)
1092 /* adjust for increment value */
1098 /* restore base dimensions */
1102 w = MAX(w, c->minw);
1103 h = MAX(h, c->minh);
1106 w = MIN(w, c->maxw);
1109 h = MIN(h, c->maxh);
1111 if(w <= 0 || h <= 0)
1114 x = sw - w - 2 * c->bw;
1116 y = sh - h - 2 * c->bw;
1117 if(x + w + 2 * c->bw < sx)
1119 if(y + h + 2 * c->bw < sy)
1125 if(c->x != x || c->y != y || c->w != w || c->h != h) {
1128 c->w = wc.width = w;
1129 c->h = wc.height = h;
1130 wc.border_width = c->bw;
1131 XConfigureWindow(dpy, c->win,
1132 CWX|CWY|CWWidth|CWHeight|CWBorderWidth, &wc);
1139 resizemouse(const Arg *arg) {
1150 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1151 None, cursor[CurResize], CurrentTime) != GrabSuccess)
1153 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->bw - 1, c->h + c->bw - 1);
1155 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask , &ev);
1158 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0,
1159 c->w + c->bw - 1, c->h + c->bw - 1);
1160 XUngrabPointer(dpy, CurrentTime);
1161 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1163 case ConfigureRequest:
1166 handler[ev.type](&ev);
1170 nw = MAX(ev.xmotion.x - ocx - 2 * c->bw + 1, 1);
1171 nh = MAX(ev.xmotion.y - ocy - 2 * c->bw + 1, 1);
1173 if(snap && nw >= wx && nw <= wx + ww
1174 && nh >= wy && nh <= wy + wh) {
1175 if(!c->isfloating && lt[sellt]->arrange
1176 && (abs(nw - c->w) > snap || abs(nh - c->h) > snap))
1177 togglefloating(NULL);
1179 if(!lt[sellt]->arrange || c->isfloating)
1180 resize(c, c->x, c->y, nw, nh, True);
1195 if(sel->isfloating || !lt[sellt]->arrange)
1196 XRaiseWindow(dpy, sel->win);
1197 if(lt[sellt]->arrange) {
1198 wc.stack_mode = Below;
1199 wc.sibling = barwin;
1200 for(c = stack; c; c = c->snext)
1201 if(!c->isfloating && ISVISIBLE(c)) {
1202 XConfigureWindow(dpy, c->win, CWSibling|CWStackMode, &wc);
1203 wc.sibling = c->win;
1207 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1213 char sbuf[sizeof stext];
1216 unsigned int len, offset;
1219 /* main event loop, also reads status text from stdin */
1221 xfd = ConnectionNumber(dpy);
1224 len = sizeof stext - 1;
1225 sbuf[len] = stext[len] = '\0'; /* 0-terminator is never touched */
1229 FD_SET(STDIN_FILENO, &rd);
1231 if(select(xfd + 1, &rd, NULL, NULL, NULL) == -1) {
1234 die("select failed\n");
1236 if(FD_ISSET(STDIN_FILENO, &rd)) {
1237 switch((r = read(STDIN_FILENO, sbuf + offset, len - offset))) {
1239 strncpy(stext, strerror(errno), len);
1243 strncpy(stext, "EOF", 4);
1247 for(p = sbuf + offset; r > 0; p++, r--, offset++)
1248 if(*p == '\n' || *p == '\0') {
1250 strncpy(stext, sbuf, len);
1251 p += r - 1; /* p is sbuf + offset + r - 1 */
1252 for(r = 0; *(p - r) && *(p - r) != '\n'; r++);
1255 memmove(sbuf, p - r + 1, r);
1262 while(XPending(dpy)) {
1263 XNextEvent(dpy, &ev);
1264 if(handler[ev.type])
1265 (handler[ev.type])(&ev); /* call handler */
1272 unsigned int i, num;
1273 Window *wins, d1, d2;
1274 XWindowAttributes wa;
1277 if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1278 for(i = 0; i < num; i++) {
1279 if(!XGetWindowAttributes(dpy, wins[i], &wa)
1280 || wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1282 if(wa.map_state == IsViewable || getstate(wins[i]) == IconicState)
1283 manage(wins[i], &wa);
1285 for(i = 0; i < num; i++) { /* now the transients */
1286 if(!XGetWindowAttributes(dpy, wins[i], &wa))
1288 if(XGetTransientForHint(dpy, wins[i], &d1)
1289 && (wa.map_state == IsViewable || getstate(wins[i]) == IconicState))
1290 manage(wins[i], &wa);
1298 setclientstate(Client *c, long state) {
1299 long data[] = {state, None};
1301 XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1302 PropModeReplace, (unsigned char *)data, 2);
1306 setlayout(const Arg *arg) {
1307 if(!arg || !arg->v || arg->v != lt[sellt])
1310 lt[sellt] = (Layout *)arg->v;
1317 /* arg > 1.0 will set mfact absolutly */
1319 setmfact(const Arg *arg) {
1322 if(!arg || !lt[sellt]->arrange)
1324 f = arg->f < 1.0 ? arg->f + mfact : arg->f - 1.0;
1325 if(f < 0.1 || f > 0.9)
1335 XSetWindowAttributes wa;
1338 screen = DefaultScreen(dpy);
1339 root = RootWindow(dpy, screen);
1343 sw = DisplayWidth(dpy, screen);
1344 sh = DisplayHeight(dpy, screen);
1345 bh = dc.h = dc.font.height + 2;
1346 lt[0] = &layouts[0];
1347 lt[1] = &layouts[1 % LENGTH(layouts)];
1351 wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1352 wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1353 wmatom[WMName] = XInternAtom(dpy, "WM_NAME", False);
1354 wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1355 netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1356 netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1359 wa.cursor = cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1360 cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1361 cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1363 /* init appearance */
1364 dc.norm[ColBorder] = getcolor(normbordercolor);
1365 dc.norm[ColBG] = getcolor(normbgcolor);
1366 dc.norm[ColFG] = getcolor(normfgcolor);
1367 dc.sel[ColBorder] = getcolor(selbordercolor);
1368 dc.sel[ColBG] = getcolor(selbgcolor);
1369 dc.sel[ColFG] = getcolor(selfgcolor);
1370 dc.drawable = XCreatePixmap(dpy, root, DisplayWidth(dpy, screen), bh, DefaultDepth(dpy, screen));
1371 dc.gc = XCreateGC(dpy, root, 0, 0);
1372 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
1374 XSetFont(dpy, dc.gc, dc.font.xfont->fid);
1377 for(blw = i = 0; LENGTH(layouts) > 1 && i < LENGTH(layouts); i++) {
1378 w = TEXTW(layouts[i].symbol);
1382 wa.override_redirect = 1;
1383 wa.background_pixmap = ParentRelative;
1384 wa.event_mask = ButtonPressMask|ExposureMask;
1386 barwin = XCreateWindow(dpy, root, wx, by, ww, bh, 0, DefaultDepth(dpy, screen),
1387 CopyFromParent, DefaultVisual(dpy, screen),
1388 CWOverrideRedirect|CWBackPixmap|CWEventMask, &wa);
1389 XDefineCursor(dpy, barwin, cursor[CurNormal]);
1390 XMapRaised(dpy, barwin);
1391 strcpy(stext, "dwm-"VERSION);
1394 /* EWMH support per view */
1395 XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1396 PropModeReplace, (unsigned char *) netatom, NetLast);
1398 /* select for events */
1399 wa.event_mask = SubstructureRedirectMask|SubstructureNotifyMask|ButtonPressMask
1400 |EnterWindowMask|LeaveWindowMask|StructureNotifyMask;
1401 XChangeWindowAttributes(dpy, root, CWEventMask|CWCursor, &wa);
1402 XSelectInput(dpy, root, wa.event_mask);
1410 spawn(const Arg *arg) {
1411 /* The double-fork construct avoids zombie processes and keeps the code
1412 * clean from stupid signal handlers. */
1416 close(ConnectionNumber(dpy));
1418 execvp(((char **)arg->v)[0], (char **)arg->v);
1419 fprintf(stderr, "dwm: execvp %s", ((char **)arg->v)[0]);
1428 tag(const Arg *arg) {
1429 if(sel && arg->ui & TAGMASK) {
1430 sel->tags = arg->ui & TAGMASK;
1436 textnw(const char *text, unsigned int len) {
1440 XmbTextExtents(dc.font.set, text, len, NULL, &r);
1443 return XTextWidth(dc.font.xfont, text, len);
1452 for(n = 0, c = nexttiled(clients); c; c = nexttiled(c->next), n++);
1457 c = nexttiled(clients);
1459 resize(c, wx, wy, (n == 1 ? ww : mw) - 2 * c->bw, wh - 2 * c->bw, resizehints);
1465 x = (wx + mw > c->x + c->w) ? c->x + c->w + 2 * c->bw : wx + mw;
1467 w = (wx + mw > c->x + c->w) ? wx + ww - x : ww - mw;
1472 for(i = 0, c = nexttiled(c->next); c; c = nexttiled(c->next), i++) {
1473 resize(c, x, y, w - 2 * c->bw, /* remainder */ ((i + 1 == n)
1474 ? (wy + wh) - y : h) - 2 * c->bw, resizehints);
1476 y = c->y + c->h + 2 * c->bw;
1481 togglebar(const Arg *arg) {
1489 togglefloating(const Arg *arg) {
1492 sel->isfloating = !sel->isfloating || sel->isfixed;
1494 resize(sel, sel->x, sel->y, sel->w, sel->h, True);
1499 toggletag(const Arg *arg) {
1500 unsigned int mask = sel->tags ^ (arg->ui & TAGMASK);
1509 toggleview(const Arg *arg) {
1510 unsigned int mask = tagset[seltags] ^ (arg->ui & TAGMASK);
1513 tagset[seltags] = mask;
1520 unmanage(Client *c) {
1523 wc.border_width = c->oldbw;
1524 /* The server grab construct avoids race conditions. */
1526 XSetErrorHandler(xerrordummy);
1527 XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
1532 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1533 setclientstate(c, WithdrawnState);
1536 XSetErrorHandler(xerror);
1542 unmapnotify(XEvent *e) {
1544 XUnmapEvent *ev = &e->xunmap;
1546 if((c = getclient(ev->window)))
1552 if(dc.drawable != 0)
1553 XFreePixmap(dpy, dc.drawable);
1554 dc.drawable = XCreatePixmap(dpy, root, ww, bh, DefaultDepth(dpy, screen));
1555 XMoveResizeWindow(dpy, barwin, wx, by, ww, bh);
1562 unsigned int xidx = 0;
1563 XineramaScreenInfo *info = NULL;
1565 /* window area geometry */
1566 if(XineramaIsActive(dpy)) {
1567 info = XineramaQueryScreens(dpy, &n);
1572 if(XQueryPointer(dpy, root, &dummy, &dummy, &x, &y, &di, &di, &dui))
1573 for(i = 0; i < n; i++)
1574 if(INRECT(x, y, info[i].x_org, info[i].y_org, info[i].width, info[i].height)) {
1579 wx = info[xidx].x_org;
1580 wy = showbar && topbar ? info[xidx].y_org + bh : info[xidx].y_org;
1581 ww = info[xidx].width;
1582 wh = showbar ? info[xidx].height - bh : info[xidx].height;
1589 wy = showbar && topbar ? sy + bh : sy;
1591 wh = showbar ? sh - bh : sh;
1595 by = showbar ? (topbar ? wy - bh : wy + wh) : -bh;
1599 updatesizehints(Client *c) {
1603 XGetWMNormalHints(dpy, c->win, &size, &msize);
1604 if(size.flags & PBaseSize) {
1605 c->basew = size.base_width;
1606 c->baseh = size.base_height;
1608 else if(size.flags & PMinSize) {
1609 c->basew = size.min_width;
1610 c->baseh = size.min_height;
1613 c->basew = c->baseh = 0;
1614 if(size.flags & PResizeInc) {
1615 c->incw = size.width_inc;
1616 c->inch = size.height_inc;
1619 c->incw = c->inch = 0;
1620 if(size.flags & PMaxSize) {
1621 c->maxw = size.max_width;
1622 c->maxh = size.max_height;
1625 c->maxw = c->maxh = 0;
1626 if(size.flags & PMinSize) {
1627 c->minw = size.min_width;
1628 c->minh = size.min_height;
1630 else if(size.flags & PBaseSize) {
1631 c->minw = size.base_width;
1632 c->minh = size.base_height;
1635 c->minw = c->minh = 0;
1636 if(size.flags & PAspect) {
1637 c->mina = (float)size.min_aspect.y / (float)size.min_aspect.x;
1638 c->maxa = (float)size.max_aspect.x / (float)size.max_aspect.y;
1641 c->maxa = c->mina = 0.0;
1642 c->isfixed = (c->maxw && c->minw && c->maxh && c->minh
1643 && c->maxw == c->minw && c->maxh == c->minh);
1647 updatetitle(Client *c) {
1648 if(!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
1649 gettextprop(c->win, wmatom[WMName], c->name, sizeof c->name);
1653 updatewmhints(Client *c) {
1656 if((wmh = XGetWMHints(dpy, c->win))) {
1657 if(ISVISIBLE(c) && wmh->flags & XUrgencyHint) {
1658 wmh->flags &= ~XUrgencyHint;
1659 XSetWMHints(dpy, c->win, wmh);
1662 c->isurgent = (wmh->flags & XUrgencyHint) ? True : False;
1669 view(const Arg *arg) {
1670 if(arg && (arg->i & TAGMASK) == tagset[seltags])
1672 seltags ^= 1; /* toggle sel tagset */
1673 if(arg && (arg->ui & TAGMASK))
1674 tagset[seltags] = arg->i & TAGMASK;
1679 /* There's no way to check accesses to destroyed windows, thus those cases are
1680 * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
1681 * default error handler, which may call exit. */
1683 xerror(Display *dpy, XErrorEvent *ee) {
1684 if(ee->error_code == BadWindow
1685 || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1686 || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1687 || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1688 || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1689 || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1690 || (ee->request_code == X_GrabButton && ee->error_code == BadAccess)
1691 || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1692 || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1694 fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1695 ee->request_code, ee->error_code);
1696 return xerrorxlib(dpy, ee); /* may call exit */
1700 xerrordummy(Display *dpy, XErrorEvent *ee) {
1704 /* Startup Error handler to check if another window manager
1705 * is already running. */
1707 xerrorstart(Display *dpy, XErrorEvent *ee) {
1713 zoom(const Arg *arg) {
1716 if(!lt[sellt]->arrange || lt[sellt]->arrange == monocle || (sel && sel->isfloating))
1718 if(c == nexttiled(clients))
1719 if(!c || !(c = nexttiled(c->next)))
1728 main(int argc, char *argv[]) {
1729 if(argc == 2 && !strcmp("-v", argv[1]))
1730 die("dwm-"VERSION", © 2006-2008 dwm engineers, see LICENSE for details\n");
1732 die("usage: dwm [-v]\n");
1734 if(!setlocale(LC_CTYPE, "") || !XSupportsLocale())
1735 fprintf(stderr, "warning: no locale support\n");
1737 if(!(dpy = XOpenDisplay(0)))
1738 die("dwm: cannot open display\n");