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)
58 enum { CurNormal, CurResize, CurMove, CurLast }; /* cursor */
59 enum { ColBorder, ColFG, ColBG, ColLast }; /* color */
60 enum { NetSupported, NetWMName, NetLast }; /* EWMH atoms */
61 enum { WMProtocols, WMDelete, WMName, WMState, WMLast };/* default atoms */
62 enum { ClkLtSymbol = 64, ClkStatusText, ClkWinTitle,
63 ClkClientWin, ClkRootWin, ClkLast }; /* clicks */
66 typedef unsigned int uint;
67 typedef unsigned long ulong;
80 void (*func)(const Arg *arg);
84 typedef struct Client Client;
89 int basew, baseh, incw, inch, maxw, maxh, minw, minh;
92 Bool isbanned, isfixed, isfloating, ismoved, isurgent;
111 } DC; /* draw context */
116 void (*func)(const Arg *);
122 void (*arrange)(void);
127 const char *instance;
133 /* function declarations */
134 static void applyrules(Client *c);
135 static void arrange(void);
136 static void attach(Client *c);
137 static void attachstack(Client *c);
138 static void buttonpress(XEvent *e);
139 static void checkotherwm(void);
140 static void cleanup(void);
141 static void configure(Client *c);
142 static void configurenotify(XEvent *e);
143 static void configurerequest(XEvent *e);
144 static void destroynotify(XEvent *e);
145 static void detach(Client *c);
146 static void detachstack(Client *c);
147 static void drawbar(void);
148 static void drawsquare(Bool filled, Bool empty, Bool invert, ulong col[ColLast]);
149 static void drawtext(const char *text, ulong col[ColLast], Bool invert);
150 static void enternotify(XEvent *e);
151 static void eprint(const char *errstr, ...);
152 static void expose(XEvent *e);
153 static void focus(Client *c);
154 static void focusin(XEvent *e);
155 static void focusstack(const Arg *arg);
156 static Client *getclient(Window w);
157 static ulong getcolor(const char *colstr);
158 static long getstate(Window w);
159 static Bool gettextprop(Window w, Atom atom, char *text, uint size);
160 static void grabbuttons(Client *c, Bool focused);
161 static void grabkeys(void);
162 static void initfont(const char *fontstr);
163 static Bool isoccupied(uint t);
164 static Bool isprotodel(Client *c);
165 static Bool isurgent(uint t);
166 static void keypress(XEvent *e);
167 static void killclient(const Arg *arg);
168 static void manage(Window w, XWindowAttributes *wa);
169 static void mappingnotify(XEvent *e);
170 static void maprequest(XEvent *e);
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 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, uint len);
186 static void tile(void);
187 static void togglebar(const Arg *arg);
188 static void togglefloating(const Arg *arg);
189 static void togglelayout(const Arg *arg);
190 static void togglemax(const Arg *arg);
191 static void toggletag(const Arg *arg);
192 static void toggleview(const Arg *arg);
193 static void unmanage(Client *c);
194 static void unmapnotify(XEvent *e);
195 static void updatebar(void);
196 static void updategeom(void);
197 static void updatesizehints(Client *c);
198 static void updatetitle(Client *c);
199 static void updatewmhints(Client *c);
200 static void view(const Arg *arg);
201 static int xerror(Display *dpy, XErrorEvent *ee);
202 static int xerrordummy(Display *dpy, XErrorEvent *ee);
203 static int xerrorstart(Display *dpy, XErrorEvent *ee);
204 static void zoom(const Arg *arg);
207 static char stext[256];
208 static int screen, sx, sy, sw, sh;
209 static int by, bh, blw, wx, wy, ww, wh;
210 static uint seltags = 0;
211 static int (*xerrorxlib)(Display *, XErrorEvent *);
212 static uint numlockmask = 0;
213 static void (*handler[LASTEvent]) (XEvent *) = {
214 [ButtonPress] = buttonpress,
215 [ConfigureRequest] = configurerequest,
216 [ConfigureNotify] = configurenotify,
217 [DestroyNotify] = destroynotify,
218 [EnterNotify] = enternotify,
221 [KeyPress] = keypress,
222 [MappingNotify] = mappingnotify,
223 [MapRequest] = maprequest,
224 [PropertyNotify] = propertynotify,
225 [UnmapNotify] = unmapnotify
227 static Atom wmatom[WMLast], netatom[NetLast];
228 static Bool ismax = False;
229 static Bool otherwm, readin;
230 static Bool running = True;
231 static uint tagset[] = {1, 1}; /* after start, first tag is selected */
232 static Client *clients = NULL;
233 static Client *sel = NULL;
234 static Client *stack = NULL;
235 static Cursor cursor[CurLast];
238 static Layout *lt = NULL;
239 static Window root, barwin;
240 /* configuration, allows nested code to access above variables */
243 /* compile-time check if all tags fit into an uint bit array. */
244 struct NumTags { char limitexceeded[sizeof(uint) * 8 < LENGTH(tags) ? -1 : 1]; };
246 /* function implementations */
248 applyrules(Client *c) {
251 XClassHint ch = { 0 };
254 XGetClassHint(dpy, c->win, &ch);
255 for(i = 0; i < LENGTH(rules); i++) {
257 if((!r->title || strstr(c->name, r->title))
258 && (!r->class || (ch.res_class && strstr(ch.res_class, r->class)))
259 && (!r->instance || (ch.res_name && strstr(ch.res_name, r->instance)))) {
260 c->isfloating = r->isfloating;
261 c->tags |= r->tags & TAGMASK;
269 c->tags = tagset[seltags];
276 for(c = clients; c; c = c->next)
277 if(c->tags & tagset[seltags]) { /* is visible */
278 if(ismax && !c->isfixed) {
279 XMoveResizeWindow(dpy, c->win, wx, wy, ww - 2 * c->bw, wh - 2 * c->bw);
282 else if(!lt->arrange || c->isfloating)
283 resize(c, c->x, c->y, c->w, c->h, True);
286 else if(!c->isbanned) {
287 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
288 c->isbanned = c->ismoved = True;
292 if(lt->arrange && !ismax)
304 attachstack(Client *c) {
310 buttonpress(XEvent *e) {
313 XButtonPressedEvent *ev = &e->xbutton;
316 if(ev->window == barwin) {
320 while(ev->x >= x && ++i < LENGTH(tags));
323 else if(ev->x < x + blw)
325 else if(ev->x > wx + ww - TEXTW(stext))
326 click = ClkStatusText;
330 else if((c = getclient(ev->window))) {
332 click = ClkClientWin;
335 for(i = 0; i < LENGTH(buttons); i++)
336 if(click == buttons[i].click && buttons[i].func && buttons[i].button == ev->button
337 && CLEANMASK(buttons[i].mask) == CLEANMASK(ev->state))
338 buttons[i].func(&buttons[i].arg);
344 XSetErrorHandler(xerrorstart);
346 /* this causes an error if some other window manager is running */
347 XSelectInput(dpy, DefaultRootWindow(dpy), SubstructureRedirectMask);
350 eprint("dwm: another window manager is already running\n");
351 XSetErrorHandler(NULL);
352 xerrorxlib = XSetErrorHandler(xerror);
359 Layout foo = { "", NULL };
367 XFreeFontSet(dpy, dc.font.set);
369 XFreeFont(dpy, dc.font.xfont);
370 XUngrabKey(dpy, AnyKey, AnyModifier, root);
371 XFreePixmap(dpy, dc.drawable);
373 XFreeCursor(dpy, cursor[CurNormal]);
374 XFreeCursor(dpy, cursor[CurResize]);
375 XFreeCursor(dpy, cursor[CurMove]);
376 XDestroyWindow(dpy, barwin);
378 XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime);
382 configure(Client *c) {
385 ce.type = ConfigureNotify;
393 ce.border_width = c->bw;
395 ce.override_redirect = False;
396 XSendEvent(dpy, c->win, False, StructureNotifyMask, (XEvent *)&ce);
400 configurenotify(XEvent *e) {
401 XConfigureEvent *ev = &e->xconfigure;
403 if(ev->window == root && (ev->width != sw || ev->height != sh)) {
413 configurerequest(XEvent *e) {
415 XConfigureRequestEvent *ev = &e->xconfigurerequest;
418 if((c = getclient(ev->window))) {
419 if(ev->value_mask & CWBorderWidth)
420 c->bw = ev->border_width;
421 if(ismax && !c->isbanned && !c->isfixed)
422 XMoveResizeWindow(dpy, c->win, wx, wy, ww - 2 * c->bw, wh + 2 * c->bw);
423 else if(c->isfloating || !lt->arrange) {
424 if(ev->value_mask & CWX)
426 if(ev->value_mask & CWY)
428 if(ev->value_mask & CWWidth)
430 if(ev->value_mask & CWHeight)
432 if((c->x - sx + c->w) > sw && c->isfloating)
433 c->x = sx + (sw / 2 - c->w / 2); /* center in x direction */
434 if((c->y - sy + c->h) > sh && c->isfloating)
435 c->y = sy + (sh / 2 - c->h / 2); /* center in y direction */
436 if((ev->value_mask & (CWX|CWY))
437 && !(ev->value_mask & (CWWidth|CWHeight)))
440 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h);
448 wc.width = ev->width;
449 wc.height = ev->height;
450 wc.border_width = ev->border_width;
451 wc.sibling = ev->above;
452 wc.stack_mode = ev->detail;
453 XConfigureWindow(dpy, ev->window, ev->value_mask, &wc);
459 destroynotify(XEvent *e) {
461 XDestroyWindowEvent *ev = &e->xdestroywindow;
463 if((c = getclient(ev->window)))
472 for(i = clients; i->next != c; i = i->next);
482 detachstack(Client *c) {
485 for(tc = &stack; *tc && *tc != c; tc = &(*tc)->snext);
495 for(c = stack; c && c->isbanned; c = c->snext);
496 for(i = 0; i < LENGTH(tags); i++) {
497 dc.w = TEXTW(tags[i]);
498 if(tagset[seltags] & 1 << i) {
499 drawtext(tags[i], dc.sel, isurgent(i));
500 drawsquare(c && c->tags & 1 << i, isoccupied(i), isurgent(i), dc.sel);
503 drawtext(tags[i], dc.norm, isurgent(i));
504 drawsquare(c && c->tags & 1 << i, isoccupied(i), isurgent(i), dc.norm);
510 drawtext(lt->symbol, dc.norm, ismax);
521 drawtext(stext, dc.norm, False);
522 if((dc.w = dc.x - x) > bh) {
525 drawtext(c->name, dc.sel, False);
526 drawsquare(c->isfixed, c->isfloating, False, dc.sel);
529 drawtext(NULL, dc.norm, False);
531 XCopyArea(dpy, dc.drawable, barwin, dc.gc, 0, 0, ww, bh, 0, 0);
536 drawsquare(Bool filled, Bool empty, Bool invert, ulong col[ColLast]) {
539 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
541 gcv.foreground = col[invert ? ColBG : ColFG];
542 XChangeGC(dpy, dc.gc, GCForeground, &gcv);
543 x = (dc.font.ascent + dc.font.descent + 2) / 4;
547 r.width = r.height = x + 1;
548 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
551 r.width = r.height = x;
552 XDrawRectangles(dpy, dc.drawable, dc.gc, &r, 1);
557 drawtext(const char *text, ulong col[ColLast], Bool invert) {
558 int i, x, y, h, len, olen;
559 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
562 XSetForeground(dpy, dc.gc, col[invert ? ColFG : ColBG]);
563 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
567 len = MIN(olen, sizeof buf);
568 memcpy(buf, text, len);
569 h = dc.font.ascent + dc.font.descent;
570 y = dc.y + (dc.h / 2) - (h / 2) + dc.font.ascent;
572 /* shorten text if necessary */
573 for(; len && (i = textnw(buf, len)) > dc.w - h; len--);
577 for(i = len; i && i > len - 3; buf[--i] = '.');
578 XSetForeground(dpy, dc.gc, col[invert ? ColBG : ColFG]);
580 XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
582 XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
586 enternotify(XEvent *e) {
588 XCrossingEvent *ev = &e->xcrossing;
590 if((ev->mode != NotifyNormal || ev->detail == NotifyInferior) && ev->window != root)
592 if((c = getclient(ev->window)))
599 eprint(const char *errstr, ...) {
602 va_start(ap, errstr);
603 vfprintf(stderr, errstr, ap);
610 XExposeEvent *ev = &e->xexpose;
612 if(ev->count == 0 && (ev->window == barwin))
618 if(!c || c->isbanned)
619 for(c = stack; c && c->isbanned; 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 && c->isbanned; c = c->next);
654 for(c = clients; c && c->isbanned; 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 eprint("error, cannot allocate color '%s'\n", colstr);
693 unsigned char *p = NULL;
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, uint 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 uint buttons[] = { Button1, Button2, Button3 };
737 uint modifiers[] = { MODKEY, MODKEY|LockMask, MODKEY|numlockmask, MODKEY|numlockmask|LockMask };
739 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
741 for(i = 0; i < LENGTH(buttons); i++)
742 for(j = 0; j < LENGTH(modifiers); j++)
743 XGrabButton(dpy, buttons[i], modifiers[j], c->win, False,
744 BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
746 XGrabButton(dpy, AnyButton, AnyModifier, c->win, False,
747 BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
754 XModifierKeymap *modmap;
756 /* init modifier map */
757 modmap = XGetModifierMapping(dpy);
758 for(i = 0; i < 8; i++)
759 for(j = 0; j < modmap->max_keypermod; j++) {
760 if(modmap->modifiermap[i * modmap->max_keypermod + j] == XKeysymToKeycode(dpy, XK_Num_Lock))
761 numlockmask = (1 << i);
763 XFreeModifiermap(modmap);
765 XUngrabKey(dpy, AnyKey, AnyModifier, root);
766 for(i = 0; i < LENGTH(keys); i++) {
767 code = XKeysymToKeycode(dpy, keys[i].keysym);
768 XGrabKey(dpy, code, keys[i].mod, root, True,
769 GrabModeAsync, GrabModeAsync);
770 XGrabKey(dpy, code, keys[i].mod|LockMask, root, True,
771 GrabModeAsync, GrabModeAsync);
772 XGrabKey(dpy, code, keys[i].mod|numlockmask, root, True,
773 GrabModeAsync, GrabModeAsync);
774 XGrabKey(dpy, code, keys[i].mod|numlockmask|LockMask, root, True,
775 GrabModeAsync, GrabModeAsync);
780 initfont(const char *fontstr) {
781 char *def, **missing;
786 XFreeFontSet(dpy, dc.font.set);
787 dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
790 fprintf(stderr, "dwm: missing fontset: %s\n", missing[n]);
791 XFreeStringList(missing);
794 XFontSetExtents *font_extents;
795 XFontStruct **xfonts;
797 dc.font.ascent = dc.font.descent = 0;
798 font_extents = XExtentsOfFontSet(dc.font.set);
799 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
800 for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
801 dc.font.ascent = MAX(dc.font.ascent, (*xfonts)->ascent);
802 dc.font.descent = MAX(dc.font.descent,(*xfonts)->descent);
808 XFreeFont(dpy, dc.font.xfont);
809 dc.font.xfont = NULL;
810 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr))
811 && !(dc.font.xfont = XLoadQueryFont(dpy, "fixed")))
812 eprint("error, cannot load font: '%s'\n", fontstr);
813 dc.font.ascent = dc.font.xfont->ascent;
814 dc.font.descent = dc.font.xfont->descent;
816 dc.font.height = dc.font.ascent + dc.font.descent;
823 for(c = clients; c; c = c->next)
830 isprotodel(Client *c) {
835 if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
836 for(i = 0; !ret && i < n; i++)
837 if(protocols[i] == wmatom[WMDelete])
848 for(c = clients; c; c = c->next)
849 if(c->isurgent && c->tags & 1 << t)
855 keypress(XEvent *e) {
861 keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
862 for(i = 0; i < LENGTH(keys); i++)
863 if(keysym == keys[i].keysym
864 && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state)
866 keys[i].func(&(keys[i].arg));
870 killclient(const Arg *arg) {
875 if(isprotodel(sel)) {
876 ev.type = ClientMessage;
877 ev.xclient.window = sel->win;
878 ev.xclient.message_type = wmatom[WMProtocols];
879 ev.xclient.format = 32;
880 ev.xclient.data.l[0] = wmatom[WMDelete];
881 ev.xclient.data.l[1] = CurrentTime;
882 XSendEvent(dpy, sel->win, False, NoEventMask, &ev);
885 XKillClient(dpy, sel->win);
889 manage(Window w, XWindowAttributes *wa) {
890 Client *c, *t = NULL;
895 if(!(c = calloc(1, sizeof(Client))))
896 eprint("fatal: could not calloc() %u bytes\n", sizeof(Client));
904 c->oldbw = wa->border_width;
905 if(c->w == sw && c->h == sh) {
908 c->bw = wa->border_width;
911 if(c->x + c->w + 2 * c->bw > sx + sw)
912 c->x = sx + sw - c->w - 2 * c->bw;
913 if(c->y + c->h + 2 * c->bw > sy + sh)
914 c->y = sy + sh - c->h - 2 * c->bw;
915 c->x = MAX(c->x, sx);
916 c->y = MAX(c->y, by == 0 ? 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, 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);
969 movemouse(const Arg *arg) {
970 int x1, y1, ocx, ocy, di, nx, ny;
981 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
982 None, cursor[CurMove], CurrentTime) != GrabSuccess)
984 XQueryPointer(dpy, root, &dummy, &dummy, &x1, &y1, &di, &di, &dui);
986 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
989 XUngrabPointer(dpy, CurrentTime);
991 case ConfigureRequest:
994 handler[ev.type](&ev);
998 nx = ocx + (ev.xmotion.x - x1);
999 ny = ocy + (ev.xmotion.y - y1);
1000 if(snap && nx >= wx && nx <= wx + ww
1001 && ny >= wy && ny <= wy + wh) {
1002 if(abs(wx - nx) < snap)
1004 else if(abs((wx + ww) - (nx + c->w + 2 * c->bw)) < snap)
1005 nx = wx + ww - c->w - 2 * c->bw;
1006 if(abs(wy - ny) < snap)
1008 else if(abs((wy + wh) - (ny + c->h + 2 * c->bw)) < snap)
1009 ny = wy + wh - c->h - 2 * c->bw;
1010 if(!c->isfloating && lt->arrange && (abs(nx - c->x) > snap || abs(ny - c->y) > snap))
1011 togglefloating(NULL);
1013 if(!lt->arrange || c->isfloating)
1014 resize(c, nx, ny, c->w, c->h, False);
1021 nexttiled(Client *c) {
1022 for(; c && (c->isfloating || c->isbanned); c = c->next);
1027 propertynotify(XEvent *e) {
1030 XPropertyEvent *ev = &e->xproperty;
1032 if(ev->state == PropertyDelete)
1033 return; /* ignore */
1034 if((c = getclient(ev->window))) {
1037 case XA_WM_TRANSIENT_FOR:
1038 XGetTransientForHint(dpy, c->win, &trans);
1039 if(!c->isfloating && (c->isfloating = (getclient(trans) != NULL)))
1042 case XA_WM_NORMAL_HINTS:
1050 if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
1059 quit(const Arg *arg) {
1060 readin = running = False;
1064 resize(Client *c, int x, int y, int w, int h, Bool sizehints) {
1068 /* set minimum possible */
1072 /* temporarily remove base dimensions */
1076 /* adjust for aspect limits */
1077 if(c->mina > 0 && c->maxa > 0) {
1078 if(c->maxa < (float) w/h)
1080 else if(c->mina > (float) h/w)
1084 /* adjust for increment value */
1090 /* restore base dimensions */
1094 w = MAX(w, c->minw);
1095 h = MAX(h, c->minh);
1098 w = MIN(w, c->maxw);
1101 h = MIN(h, c->maxh);
1103 if(w <= 0 || h <= 0)
1106 x = sw - w - 2 * c->bw;
1108 y = sh - h - 2 * c->bw;
1109 if(x + w + 2 * c->bw < sx)
1111 if(y + h + 2 * c->bw < sy)
1117 if(c->x != x || c->y != y || c->w != w || c->h != h || c->ismoved) {
1121 c->w = wc.width = w;
1122 c->h = wc.height = h;
1123 wc.border_width = c->bw;
1124 XConfigureWindow(dpy, c->win,
1125 CWX|CWY|CWWidth|CWHeight|CWBorderWidth, &wc);
1132 resizemouse(const Arg *arg) {
1143 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1144 None, cursor[CurResize], CurrentTime) != GrabSuccess)
1146 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->bw - 1, c->h + c->bw - 1);
1148 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask , &ev);
1151 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0,
1152 c->w + c->bw - 1, c->h + c->bw - 1);
1153 XUngrabPointer(dpy, CurrentTime);
1154 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1156 case ConfigureRequest:
1159 handler[ev.type](&ev);
1163 nw = MAX(ev.xmotion.x - ocx - 2 * c->bw + 1, 1);
1164 nh = MAX(ev.xmotion.y - ocy - 2 * c->bw + 1, 1);
1166 if(snap && nw >= wx && nw <= wx + ww
1167 && nh >= wy && nh <= wy + wh) {
1168 if(!c->isfloating && lt->arrange
1169 && (abs(nw - c->w) > snap || abs(nh - c->h) > snap))
1170 togglefloating(NULL);
1172 if(!lt->arrange || c->isfloating)
1173 resize(c, c->x, c->y, nw, nh, True);
1188 if(ismax || sel->isfloating || !lt->arrange)
1189 XRaiseWindow(dpy, sel->win);
1190 if(!ismax && lt->arrange) {
1191 wc.stack_mode = Below;
1192 wc.sibling = barwin;
1193 for(c = stack; c; c = c->snext)
1194 if(!c->isfloating && !c->isbanned) {
1195 XConfigureWindow(dpy, c->win, CWSibling|CWStackMode, &wc);
1196 wc.sibling = c->win;
1200 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1206 char sbuf[sizeof stext];
1212 /* main event loop, also reads status text from stdin */
1214 xfd = ConnectionNumber(dpy);
1217 len = sizeof stext - 1;
1218 sbuf[len] = stext[len] = '\0'; /* 0-terminator is never touched */
1222 FD_SET(STDIN_FILENO, &rd);
1224 if(select(xfd + 1, &rd, NULL, NULL, NULL) == -1) {
1227 eprint("select failed\n");
1229 if(FD_ISSET(STDIN_FILENO, &rd)) {
1230 switch((r = read(STDIN_FILENO, sbuf + offset, len - offset))) {
1232 strncpy(stext, strerror(errno), len);
1236 strncpy(stext, "EOF", 4);
1240 for(p = sbuf + offset; r > 0; p++, r--, offset++)
1241 if(*p == '\n' || *p == '\0') {
1243 strncpy(stext, sbuf, len);
1244 p += r - 1; /* p is sbuf + offset + r - 1 */
1245 for(r = 0; *(p - r) && *(p - r) != '\n'; r++);
1248 memmove(sbuf, p - r + 1, r);
1255 while(XPending(dpy)) {
1256 XNextEvent(dpy, &ev);
1257 if(handler[ev.type])
1258 (handler[ev.type])(&ev); /* call handler */
1266 Window *wins, d1, d2;
1267 XWindowAttributes wa;
1270 if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1271 for(i = 0; i < num; i++) {
1272 if(!XGetWindowAttributes(dpy, wins[i], &wa)
1273 || wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1275 if(wa.map_state == IsViewable || getstate(wins[i]) == IconicState)
1276 manage(wins[i], &wa);
1278 for(i = 0; i < num; i++) { /* now the transients */
1279 if(!XGetWindowAttributes(dpy, wins[i], &wa))
1281 if(XGetTransientForHint(dpy, wins[i], &d1)
1282 && (wa.map_state == IsViewable || getstate(wins[i]) == IconicState))
1283 manage(wins[i], &wa);
1291 setclientstate(Client *c, long state) {
1292 long data[] = {state, None};
1294 XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1295 PropModeReplace, (unsigned char *)data, 2);
1298 /* arg > 1.0 will set mfact absolutly */
1300 setmfact(const Arg *arg) {
1303 if(!arg || !lt->arrange)
1305 f = arg->f < 1.0 ? arg->f + mfact : arg->f - 1.0;
1306 if(f < 0.1 || f > 0.9)
1316 XSetWindowAttributes wa;
1319 screen = DefaultScreen(dpy);
1320 root = RootWindow(dpy, screen);
1324 sw = DisplayWidth(dpy, screen);
1325 sh = DisplayHeight(dpy, screen);
1326 bh = dc.h = dc.font.height + 2;
1331 wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1332 wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1333 wmatom[WMName] = XInternAtom(dpy, "WM_NAME", False);
1334 wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1335 netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1336 netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1339 wa.cursor = cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1340 cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1341 cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1343 /* init appearance */
1344 dc.norm[ColBorder] = getcolor(normbordercolor);
1345 dc.norm[ColBG] = getcolor(normbgcolor);
1346 dc.norm[ColFG] = getcolor(normfgcolor);
1347 dc.sel[ColBorder] = getcolor(selbordercolor);
1348 dc.sel[ColBG] = getcolor(selbgcolor);
1349 dc.sel[ColFG] = getcolor(selfgcolor);
1350 dc.drawable = XCreatePixmap(dpy, root, DisplayWidth(dpy, screen), bh, DefaultDepth(dpy, screen));
1351 dc.gc = XCreateGC(dpy, root, 0, 0);
1352 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
1354 XSetFont(dpy, dc.gc, dc.font.xfont->fid);
1357 for(blw = i = 0; LENGTH(layouts) > 1 && i < LENGTH(layouts); i++) {
1358 w = TEXTW(layouts[i].symbol);
1362 wa.override_redirect = 1;
1363 wa.background_pixmap = ParentRelative;
1364 wa.event_mask = ButtonPressMask|ExposureMask;
1366 barwin = XCreateWindow(dpy, root, wx, by, ww, bh, 0, DefaultDepth(dpy, screen),
1367 CopyFromParent, DefaultVisual(dpy, screen),
1368 CWOverrideRedirect|CWBackPixmap|CWEventMask, &wa);
1369 XDefineCursor(dpy, barwin, cursor[CurNormal]);
1370 XMapRaised(dpy, barwin);
1371 strcpy(stext, "dwm-"VERSION);
1374 /* EWMH support per view */
1375 XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1376 PropModeReplace, (unsigned char *) netatom, NetLast);
1378 /* select for events */
1379 wa.event_mask = SubstructureRedirectMask|SubstructureNotifyMask|ButtonPressMask
1380 |EnterWindowMask|LeaveWindowMask|StructureNotifyMask;
1381 XChangeWindowAttributes(dpy, root, CWEventMask|CWCursor, &wa);
1382 XSelectInput(dpy, root, wa.event_mask);
1390 spawn(const Arg *arg) {
1391 /* The double-fork construct avoids zombie processes and keeps the code
1392 * clean from stupid signal handlers. */
1396 close(ConnectionNumber(dpy));
1398 execvp(((char **)arg->v)[0], (char **)arg->v);
1399 fprintf(stderr, "dwm: execvp %s", ((char **)arg->v)[0]);
1408 tag(const Arg *arg) {
1409 if(sel && arg->ui & TAGMASK) {
1410 sel->tags = arg->ui & TAGMASK;
1416 textnw(const char *text, uint len) {
1420 XmbTextExtents(dc.font.set, text, len, NULL, &r);
1423 return XTextWidth(dc.font.xfont, text, len);
1432 for(n = 0, c = nexttiled(clients); c; c = nexttiled(c->next), n++);
1437 c = nexttiled(clients);
1439 resize(c, wx, wy, (n == 1 ? ww : mw) - 2 * c->bw, wh - 2 * c->bw, resizehints);
1445 x = (wx + mw > c->x + c->w) ? c->x + c->w + 2 * c->bw : wx + mw;
1447 w = (wx + mw > c->x + c->w) ? wx + ww - x : ww - mw;
1452 for(i = 0, c = nexttiled(c->next); c; c = nexttiled(c->next), i++) {
1453 resize(c, x, y, w - 2 * c->bw, /* remainder */ ((i + 1 == n)
1454 ? (wy + wh) - y : h) - 2 * c->bw, resizehints);
1456 y = c->y + c->h + 2 * c->bw;
1461 togglebar(const Arg *arg) {
1469 togglefloating(const Arg *arg) {
1472 sel->isfloating = !sel->isfloating || sel->isfixed;
1474 resize(sel, sel->x, sel->y, sel->w, sel->h, True);
1479 togglelayout(const Arg *arg) {
1481 lt = (Layout *)arg->v;
1482 else if(++lt == &layouts[LENGTH(layouts)])
1491 togglemax(const Arg *arg) {
1497 toggletag(const Arg *arg) {
1498 if(sel && (sel->tags ^= (arg->ui & TAGMASK)))
1503 toggleview(const Arg *arg) {
1504 if((tagset[seltags] ^= (arg->ui & TAGMASK)))
1509 unmanage(Client *c) {
1512 wc.border_width = c->oldbw;
1513 /* The server grab construct avoids race conditions. */
1515 XSetErrorHandler(xerrordummy);
1516 XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
1521 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1522 setclientstate(c, WithdrawnState);
1525 XSetErrorHandler(xerror);
1531 unmapnotify(XEvent *e) {
1533 XUnmapEvent *ev = &e->xunmap;
1535 if((c = getclient(ev->window)))
1541 if(dc.drawable != 0)
1542 XFreePixmap(dpy, dc.drawable);
1543 dc.drawable = XCreatePixmap(dpy, root, ww, bh, DefaultDepth(dpy, screen));
1544 XMoveResizeWindow(dpy, barwin, wx, by, ww, bh);
1551 XineramaScreenInfo *info = NULL;
1553 /* window area geometry */
1554 if(XineramaIsActive(dpy)) {
1555 info = XineramaQueryScreens(dpy, &i);
1556 wx = info[xidx].x_org;
1557 wy = showbar && topbar ? info[xidx].y_org + bh : info[xidx].y_org;
1558 ww = info[xidx].width;
1559 wh = showbar ? info[xidx].height - bh : info[xidx].height;
1566 wy = showbar && topbar ? sy + bh : sy;
1568 wh = showbar ? sh - bh : sh;
1572 by = showbar ? (topbar ? wy - bh : wy + wh) : -bh;
1576 updatesizehints(Client *c) {
1580 XGetWMNormalHints(dpy, c->win, &size, &msize);
1581 if(size.flags & PBaseSize) {
1582 c->basew = size.base_width;
1583 c->baseh = size.base_height;
1585 else if(size.flags & PMinSize) {
1586 c->basew = size.min_width;
1587 c->baseh = size.min_height;
1590 c->basew = c->baseh = 0;
1591 if(size.flags & PResizeInc) {
1592 c->incw = size.width_inc;
1593 c->inch = size.height_inc;
1596 c->incw = c->inch = 0;
1597 if(size.flags & PMaxSize) {
1598 c->maxw = size.max_width;
1599 c->maxh = size.max_height;
1602 c->maxw = c->maxh = 0;
1603 if(size.flags & PMinSize) {
1604 c->minw = size.min_width;
1605 c->minh = size.min_height;
1607 else if(size.flags & PBaseSize) {
1608 c->minw = size.base_width;
1609 c->minh = size.base_height;
1612 c->minw = c->minh = 0;
1613 if(size.flags & PAspect) {
1614 c->mina = (float)size.min_aspect.y / (float)size.min_aspect.x;
1615 c->maxa = (float)size.max_aspect.x / (float)size.max_aspect.y;
1618 c->maxa = c->mina = 0.0;
1619 c->isfixed = (c->maxw && c->minw && c->maxh && c->minh
1620 && c->maxw == c->minw && c->maxh == c->minh);
1624 updatetitle(Client *c) {
1625 if(!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
1626 gettextprop(c->win, wmatom[WMName], c->name, sizeof c->name);
1630 updatewmhints(Client *c) {
1633 if((wmh = XGetWMHints(dpy, c->win))) {
1635 sel->isurgent = False;
1637 c->isurgent = (wmh->flags & XUrgencyHint) ? True : False;
1643 view(const Arg *arg) {
1644 seltags ^= 1; /* toggle sel tagset */
1645 if(arg && (arg->ui & TAGMASK))
1646 tagset[seltags] = arg->i & TAGMASK;
1650 /* There's no way to check accesses to destroyed windows, thus those cases are
1651 * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
1652 * default error handler, which may call exit. */
1654 xerror(Display *dpy, XErrorEvent *ee) {
1655 if(ee->error_code == BadWindow
1656 || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1657 || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1658 || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1659 || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1660 || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1661 || (ee->request_code == X_GrabButton && ee->error_code == BadAccess)
1662 || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1663 || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1665 fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1666 ee->request_code, ee->error_code);
1667 return xerrorxlib(dpy, ee); /* may call exit */
1671 xerrordummy(Display *dpy, XErrorEvent *ee) {
1675 /* Startup Error handler to check if another window manager
1676 * is already running. */
1678 xerrorstart(Display *dpy, XErrorEvent *ee) {
1684 zoom(const Arg *arg) {
1687 if(ismax || !lt->arrange || (sel && sel->isfloating))
1689 if(c == nexttiled(clients))
1690 if(!c || !(c = nexttiled(c->next)))
1699 main(int argc, char *argv[]) {
1700 if(argc == 2 && !strcmp("-v", argv[1]))
1701 eprint("dwm-"VERSION", © 2006-2008 dwm engineers, see LICENSE for details\n");
1703 eprint("usage: dwm [-v]\n");
1705 setlocale(LC_CTYPE, "");
1706 if(!(dpy = XOpenDisplay(0)))
1707 eprint("dwm: cannot open display\n");