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 */
64 typedef unsigned int uint;
65 typedef unsigned long ulong;
66 typedef struct Client Client;
70 int basew, baseh, incw, inch, maxw, maxh, minw, minh;
73 Bool isbanned, isfixed, isfloating, ismoved, isurgent;
93 } DC; /* draw context */
105 void (*func)(const Arg *);
111 void (*arrange)(void);
116 const char *instance;
122 /* function declarations */
123 static void applyrules(Client *c);
124 static void arrange(void);
125 static void attach(Client *c);
126 static void attachstack(Client *c);
127 static void buttonpress(XEvent *e);
128 static void checkotherwm(void);
129 static void cleanup(void);
130 static void configure(Client *c);
131 static void configurenotify(XEvent *e);
132 static void configurerequest(XEvent *e);
133 static void destroynotify(XEvent *e);
134 static void detach(Client *c);
135 static void detachstack(Client *c);
136 static void drawbar(void);
137 static void drawsquare(Bool filled, Bool empty, Bool invert, ulong col[ColLast]);
138 static void drawtext(const char *text, ulong col[ColLast], Bool invert);
139 static void enternotify(XEvent *e);
140 static void eprint(const char *errstr, ...);
141 static void expose(XEvent *e);
142 static void focus(Client *c);
143 static void focusin(XEvent *e);
144 static void focusstack(const Arg *arg);
145 static Client *getclient(Window w);
146 static ulong getcolor(const char *colstr);
147 static long getstate(Window w);
148 static Bool gettextprop(Window w, Atom atom, char *text, uint size);
149 static void grabbuttons(Client *c, Bool focused);
150 static void grabkeys(void);
151 static void initfont(const char *fontstr);
152 static Bool isoccupied(uint t);
153 static Bool isprotodel(Client *c);
154 static Bool isurgent(uint t);
155 static void keypress(XEvent *e);
156 static void killclient(const Arg *arg);
157 static void manage(Window w, XWindowAttributes *wa);
158 static void mappingnotify(XEvent *e);
159 static void maprequest(XEvent *e);
160 static void movemouse(Client *c);
161 static Client *nexttiled(Client *c);
162 static void propertynotify(XEvent *e);
163 static void quit(const Arg *arg);
164 static void resize(Client *c, int x, int y, int w, int h, Bool sizehints);
165 static void resizemouse(Client *c);
166 static void restack(void);
167 static void run(void);
168 static void scan(void);
169 static void setclientstate(Client *c, long state);
170 static void setmfact(const Arg *arg);
171 static void setup(void);
172 static void spawn(const Arg *arg);
173 static void tag(const Arg *arg);
174 static int textnw(const char *text, uint len);
175 static void tile(void);
176 static void togglebar(const Arg *arg);
177 static void togglefloating(const Arg *arg);
178 static void togglelayout(const Arg *arg);
179 static void togglemax(const Arg *arg);
180 static void toggletag(const Arg *arg);
181 static void toggleview(const Arg *arg);
182 static void unmanage(Client *c);
183 static void unmapnotify(XEvent *e);
184 static void updatebar(void);
185 static void updategeom(void);
186 static void updatesizehints(Client *c);
187 static void updatetitle(Client *c);
188 static void updatewmhints(Client *c);
189 static void view(const Arg *arg);
190 static int xerror(Display *dpy, XErrorEvent *ee);
191 static int xerrordummy(Display *dpy, XErrorEvent *ee);
192 static int xerrorstart(Display *dpy, XErrorEvent *ee);
193 static void zoom(const Arg *arg);
196 static char stext[256];
197 static int screen, sx, sy, sw, sh;
198 static int by, bh, blw, wx, wy, ww, wh;
199 static uint seltags = 0;
200 static int (*xerrorxlib)(Display *, XErrorEvent *);
201 static uint numlockmask = 0;
202 static void (*handler[LASTEvent]) (XEvent *) = {
203 [ButtonPress] = buttonpress,
204 [ConfigureRequest] = configurerequest,
205 [ConfigureNotify] = configurenotify,
206 [DestroyNotify] = destroynotify,
207 [EnterNotify] = enternotify,
210 [KeyPress] = keypress,
211 [MappingNotify] = mappingnotify,
212 [MapRequest] = maprequest,
213 [PropertyNotify] = propertynotify,
214 [UnmapNotify] = unmapnotify
216 static Atom wmatom[WMLast], netatom[NetLast];
217 static Bool ismax = False;
218 static Bool otherwm, readin;
219 static Bool running = True;
220 static uint tagset[] = {1, 1}; /* after start, first tag is selected */
221 static Client *clients = NULL;
222 static Client *sel = NULL;
223 static Client *stack = NULL;
224 static Cursor cursor[CurLast];
227 static Layout *lt = NULL;
228 static Window root, barwin;
229 /* configuration, allows nested code to access above variables */
232 /* compile-time check if all tags fit into an uint bit array. */
233 struct NumTags { char limitexceeded[sizeof(uint) * 8 < LENGTH(tags) ? -1 : 1]; };
235 /* function implementations */
237 applyrules(Client *c) {
240 XClassHint ch = { 0 };
243 XGetClassHint(dpy, c->win, &ch);
244 for(i = 0; i < LENGTH(rules); i++) {
246 if((!r->title || strstr(c->name, r->title))
247 && (!r->class || (ch.res_class && strstr(ch.res_class, r->class)))
248 && (!r->instance || (ch.res_name && strstr(ch.res_name, r->instance)))) {
249 c->isfloating = r->isfloating;
250 c->tags |= r->tags & TAGMASK;
258 c->tags = tagset[seltags];
265 for(c = clients; c; c = c->next)
266 if(c->tags & tagset[seltags]) { /* is visible */
267 if(ismax && !c->isfixed) {
268 XMoveResizeWindow(dpy, c->win, wx, wy, ww - 2 * c->bw, wh - 2 * c->bw);
271 else if(!lt->arrange || c->isfloating)
272 resize(c, c->x, c->y, c->w, c->h, True);
275 else if(!c->isbanned) {
276 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
277 c->isbanned = c->ismoved = True;
281 if(lt->arrange && !ismax)
293 attachstack(Client *c) {
299 buttonpress(XEvent *e) {
303 XButtonPressedEvent *ev = &e->xbutton;
305 if(ev->window == barwin) {
307 for(i = 0; i < LENGTH(tags); i++) {
311 if(ev->button == Button1) {
312 if(ev->state & MODKEY)
317 else if(ev->button == Button3) {
318 if(ev->state & MODKEY)
319 toggletag((Arg*)&mask);
321 toggleview((Arg*)&mask);
326 if(ev->x < x + blw) {
327 if(ev->button == Button1)
329 else if(ev->button == Button3)
333 else if((c = getclient(ev->window))) {
335 if(CLEANMASK(ev->state) != MODKEY || (ismax && !c->isfixed))
337 if(ev->button == Button1)
339 else if(ev->button == Button2)
340 togglefloating(NULL);
341 else if(ev->button == Button3 && !c->isfixed)
349 XSetErrorHandler(xerrorstart);
351 /* this causes an error if some other window manager is running */
352 XSelectInput(dpy, DefaultRootWindow(dpy), SubstructureRedirectMask);
355 eprint("dwm: another window manager is already running\n");
356 XSetErrorHandler(NULL);
357 xerrorxlib = XSetErrorHandler(xerror);
364 Layout foo = { "", NULL };
372 XFreeFontSet(dpy, dc.font.set);
374 XFreeFont(dpy, dc.font.xfont);
375 XUngrabKey(dpy, AnyKey, AnyModifier, root);
376 XFreePixmap(dpy, dc.drawable);
378 XFreeCursor(dpy, cursor[CurNormal]);
379 XFreeCursor(dpy, cursor[CurResize]);
380 XFreeCursor(dpy, cursor[CurMove]);
381 XDestroyWindow(dpy, barwin);
383 XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime);
387 configure(Client *c) {
390 ce.type = ConfigureNotify;
398 ce.border_width = c->bw;
400 ce.override_redirect = False;
401 XSendEvent(dpy, c->win, False, StructureNotifyMask, (XEvent *)&ce);
405 configurenotify(XEvent *e) {
406 XConfigureEvent *ev = &e->xconfigure;
408 if(ev->window == root && (ev->width != sw || ev->height != sh)) {
418 configurerequest(XEvent *e) {
420 XConfigureRequestEvent *ev = &e->xconfigurerequest;
423 if((c = getclient(ev->window))) {
424 if(ev->value_mask & CWBorderWidth)
425 c->bw = ev->border_width;
426 if(ismax && !c->isbanned && !c->isfixed)
427 XMoveResizeWindow(dpy, c->win, wx, wy, ww - 2 * c->bw, wh + 2 * c->bw);
428 else if(c->isfloating || !lt->arrange) {
429 if(ev->value_mask & CWX)
431 if(ev->value_mask & CWY)
433 if(ev->value_mask & CWWidth)
435 if(ev->value_mask & CWHeight)
437 if((c->x - sx + c->w) > sw && c->isfloating)
438 c->x = sx + (sw / 2 - c->w / 2); /* center in x direction */
439 if((c->y - sy + c->h) > sh && c->isfloating)
440 c->y = sy + (sh / 2 - c->h / 2); /* center in y direction */
441 if((ev->value_mask & (CWX|CWY))
442 && !(ev->value_mask & (CWWidth|CWHeight)))
445 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h);
453 wc.width = ev->width;
454 wc.height = ev->height;
455 wc.border_width = ev->border_width;
456 wc.sibling = ev->above;
457 wc.stack_mode = ev->detail;
458 XConfigureWindow(dpy, ev->window, ev->value_mask, &wc);
464 destroynotify(XEvent *e) {
466 XDestroyWindowEvent *ev = &e->xdestroywindow;
468 if((c = getclient(ev->window)))
477 for(i = clients; i->next != c; i = i->next);
487 detachstack(Client *c) {
490 for(tc = &stack; *tc && *tc != c; tc = &(*tc)->snext);
500 for(c = stack; c && c->isbanned; c = c->snext);
501 for(i = 0; i < LENGTH(tags); i++) {
502 dc.w = TEXTW(tags[i]);
503 if(tagset[seltags] & 1 << i) {
504 drawtext(tags[i], dc.sel, isurgent(i));
505 drawsquare(c && c->tags & 1 << i, isoccupied(i), isurgent(i), dc.sel);
508 drawtext(tags[i], dc.norm, isurgent(i));
509 drawsquare(c && c->tags & 1 << i, isoccupied(i), isurgent(i), dc.norm);
515 drawtext(lt->symbol, dc.norm, ismax);
526 drawtext(stext, dc.norm, False);
527 if((dc.w = dc.x - x) > bh) {
530 drawtext(c->name, dc.sel, False);
531 drawsquare(c->isfixed, c->isfloating, False, dc.sel);
534 drawtext(NULL, dc.norm, False);
536 XCopyArea(dpy, dc.drawable, barwin, dc.gc, 0, 0, ww, bh, 0, 0);
541 drawsquare(Bool filled, Bool empty, Bool invert, ulong col[ColLast]) {
544 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
546 gcv.foreground = col[invert ? ColBG : ColFG];
547 XChangeGC(dpy, dc.gc, GCForeground, &gcv);
548 x = (dc.font.ascent + dc.font.descent + 2) / 4;
552 r.width = r.height = x + 1;
553 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
556 r.width = r.height = x;
557 XDrawRectangles(dpy, dc.drawable, dc.gc, &r, 1);
562 drawtext(const char *text, ulong col[ColLast], Bool invert) {
563 int i, x, y, h, len, olen;
564 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
567 XSetForeground(dpy, dc.gc, col[invert ? ColFG : ColBG]);
568 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
572 len = MIN(olen, sizeof buf);
573 memcpy(buf, text, len);
574 h = dc.font.ascent + dc.font.descent;
575 y = dc.y + (dc.h / 2) - (h / 2) + dc.font.ascent;
577 /* shorten text if necessary */
578 for(; len && (i = textnw(buf, len)) > dc.w - h; len--);
582 for(i = len; i && i > len - 3; buf[--i] = '.');
583 XSetForeground(dpy, dc.gc, col[invert ? ColBG : ColFG]);
585 XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
587 XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
591 enternotify(XEvent *e) {
593 XCrossingEvent *ev = &e->xcrossing;
595 if((ev->mode != NotifyNormal || ev->detail == NotifyInferior) && ev->window != root)
597 if((c = getclient(ev->window)))
604 eprint(const char *errstr, ...) {
607 va_start(ap, errstr);
608 vfprintf(stderr, errstr, ap);
615 XExposeEvent *ev = &e->xexpose;
617 if(ev->count == 0 && (ev->window == barwin))
623 if(!c || c->isbanned)
624 for(c = stack; c && c->isbanned; c = c->snext);
625 if(sel && sel != c) {
626 grabbuttons(sel, False);
627 XSetWindowBorder(dpy, sel->win, dc.norm[ColBorder]);
632 grabbuttons(c, True);
633 XSetWindowBorder(dpy, c->win, dc.sel[ColBorder]);
634 XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
637 XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
643 focusin(XEvent *e) { /* there are some broken focus acquiring clients */
644 XFocusChangeEvent *ev = &e->xfocus;
646 if(sel && ev->window != sel->win)
647 XSetInputFocus(dpy, sel->win, RevertToPointerRoot, CurrentTime);
651 focusstack(const Arg *arg) {
652 Client *c = NULL, *i;
657 for(c = sel->next; c && c->isbanned; c = c->next);
659 for(c = clients; c && c->isbanned; c = c->next);
662 for(i = clients; i != sel; i = i->next)
666 for(; i; i = i->next)
677 getclient(Window w) {
680 for(c = clients; c && c->win != w; c = c->next);
685 getcolor(const char *colstr) {
686 Colormap cmap = DefaultColormap(dpy, screen);
689 if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
690 eprint("error, cannot allocate color '%s'\n", colstr);
698 unsigned char *p = NULL;
702 status = XGetWindowProperty(dpy, w, wmatom[WMState], 0L, 2L, False, wmatom[WMState],
703 &real, &format, &n, &extra, (unsigned char **)&p);
704 if(status != Success)
713 gettextprop(Window w, Atom atom, char *text, uint size) {
718 if(!text || size == 0)
721 XGetTextProperty(dpy, w, &name, atom);
724 if(name.encoding == XA_STRING)
725 strncpy(text, (char *)name.value, size - 1);
727 if(XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success
729 strncpy(text, *list, size - 1);
730 XFreeStringList(list);
733 text[size - 1] = '\0';
739 grabbuttons(Client *c, Bool focused) {
741 uint buttons[] = { Button1, Button2, Button3 };
742 uint modifiers[] = { MODKEY, MODKEY|LockMask, MODKEY|numlockmask, MODKEY|numlockmask|LockMask };
744 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
746 for(i = 0; i < LENGTH(buttons); i++)
747 for(j = 0; j < LENGTH(modifiers); j++)
748 XGrabButton(dpy, buttons[i], modifiers[j], c->win, False,
749 BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
751 XGrabButton(dpy, AnyButton, AnyModifier, c->win, False,
752 BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
759 XModifierKeymap *modmap;
761 /* init modifier map */
762 modmap = XGetModifierMapping(dpy);
763 for(i = 0; i < 8; i++)
764 for(j = 0; j < modmap->max_keypermod; j++) {
765 if(modmap->modifiermap[i * modmap->max_keypermod + j] == XKeysymToKeycode(dpy, XK_Num_Lock))
766 numlockmask = (1 << i);
768 XFreeModifiermap(modmap);
770 XUngrabKey(dpy, AnyKey, AnyModifier, root);
771 for(i = 0; i < LENGTH(keys); i++) {
772 code = XKeysymToKeycode(dpy, keys[i].keysym);
773 XGrabKey(dpy, code, keys[i].mod, root, True,
774 GrabModeAsync, GrabModeAsync);
775 XGrabKey(dpy, code, keys[i].mod|LockMask, root, True,
776 GrabModeAsync, GrabModeAsync);
777 XGrabKey(dpy, code, keys[i].mod|numlockmask, root, True,
778 GrabModeAsync, GrabModeAsync);
779 XGrabKey(dpy, code, keys[i].mod|numlockmask|LockMask, root, True,
780 GrabModeAsync, GrabModeAsync);
785 initfont(const char *fontstr) {
786 char *def, **missing;
791 XFreeFontSet(dpy, dc.font.set);
792 dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
795 fprintf(stderr, "dwm: missing fontset: %s\n", missing[n]);
796 XFreeStringList(missing);
799 XFontSetExtents *font_extents;
800 XFontStruct **xfonts;
802 dc.font.ascent = dc.font.descent = 0;
803 font_extents = XExtentsOfFontSet(dc.font.set);
804 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
805 for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
806 dc.font.ascent = MAX(dc.font.ascent, (*xfonts)->ascent);
807 dc.font.descent = MAX(dc.font.descent,(*xfonts)->descent);
813 XFreeFont(dpy, dc.font.xfont);
814 dc.font.xfont = NULL;
815 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr))
816 && !(dc.font.xfont = XLoadQueryFont(dpy, "fixed")))
817 eprint("error, cannot load font: '%s'\n", fontstr);
818 dc.font.ascent = dc.font.xfont->ascent;
819 dc.font.descent = dc.font.xfont->descent;
821 dc.font.height = dc.font.ascent + dc.font.descent;
828 for(c = clients; c; c = c->next)
835 isprotodel(Client *c) {
840 if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
841 for(i = 0; !ret && i < n; i++)
842 if(protocols[i] == wmatom[WMDelete])
853 for(c = clients; c; c = c->next)
854 if(c->isurgent && c->tags & 1 << t)
860 keypress(XEvent *e) {
866 keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
867 for(i = 0; i < LENGTH(keys); i++)
868 if(keysym == keys[i].keysym
869 && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state)
871 keys[i].func(&(keys[i].arg));
875 killclient(const Arg *arg) {
880 if(isprotodel(sel)) {
881 ev.type = ClientMessage;
882 ev.xclient.window = sel->win;
883 ev.xclient.message_type = wmatom[WMProtocols];
884 ev.xclient.format = 32;
885 ev.xclient.data.l[0] = wmatom[WMDelete];
886 ev.xclient.data.l[1] = CurrentTime;
887 XSendEvent(dpy, sel->win, False, NoEventMask, &ev);
890 XKillClient(dpy, sel->win);
894 manage(Window w, XWindowAttributes *wa) {
895 Client *c, *t = NULL;
900 if(!(c = calloc(1, sizeof(Client))))
901 eprint("fatal: could not calloc() %u bytes\n", sizeof(Client));
909 c->oldbw = wa->border_width;
910 if(c->w == sw && c->h == sh) {
913 c->bw = wa->border_width;
916 if(c->x + c->w + 2 * c->bw > sx + sw)
917 c->x = sx + sw - c->w - 2 * c->bw;
918 if(c->y + c->h + 2 * c->bw > sy + sh)
919 c->y = sy + sh - c->h - 2 * c->bw;
920 c->x = MAX(c->x, sx);
921 c->y = MAX(c->y, by == 0 ? bh : sy);
925 wc.border_width = c->bw;
926 XConfigureWindow(dpy, w, CWBorderWidth, &wc);
927 XSetWindowBorder(dpy, w, dc.norm[ColBorder]);
928 configure(c); /* propagates border_width, if size doesn't change */
930 XSelectInput(dpy, w, EnterWindowMask|FocusChangeMask|PropertyChangeMask|StructureNotifyMask);
931 grabbuttons(c, False);
933 if((rettrans = XGetTransientForHint(dpy, w, &trans) == Success))
934 for(t = clients; t && t->win != trans; t = t->next);
940 c->isfloating = (rettrans == Success) || c->isfixed;
942 XRaiseWindow(dpy, c->win);
945 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h); /* some windows require this */
946 XMapWindow(dpy, c->win);
947 setclientstate(c, NormalState);
952 mappingnotify(XEvent *e) {
953 XMappingEvent *ev = &e->xmapping;
955 XRefreshKeyboardMapping(ev);
956 if(ev->request == MappingKeyboard)
961 maprequest(XEvent *e) {
962 static XWindowAttributes wa;
963 XMapRequestEvent *ev = &e->xmaprequest;
965 if(!XGetWindowAttributes(dpy, ev->window, &wa))
967 if(wa.override_redirect)
969 if(!getclient(ev->window))
970 manage(ev->window, &wa);
974 movemouse(Client *c) {
975 int x1, y1, ocx, ocy, di, nx, ny;
983 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
984 None, cursor[CurMove], CurrentTime) != GrabSuccess)
986 XQueryPointer(dpy, root, &dummy, &dummy, &x1, &y1, &di, &di, &dui);
988 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
991 XUngrabPointer(dpy, CurrentTime);
993 case ConfigureRequest:
996 handler[ev.type](&ev);
1000 nx = ocx + (ev.xmotion.x - x1);
1001 ny = ocy + (ev.xmotion.y - y1);
1002 if(snap && nx >= wx && nx <= wx + ww
1003 && ny >= wy && ny <= wy + wh) {
1004 if(abs(wx - nx) < snap)
1006 else if(abs((wx + ww) - (nx + c->w + 2 * c->bw)) < snap)
1007 nx = wx + ww - c->w - 2 * c->bw;
1008 if(abs(wy - ny) < snap)
1010 else if(abs((wy + wh) - (ny + c->h + 2 * c->bw)) < snap)
1011 ny = wy + wh - c->h - 2 * c->bw;
1012 if(!c->isfloating && lt->arrange && (abs(nx - c->x) > snap || abs(ny - c->y) > snap))
1013 togglefloating(NULL);
1015 if(!lt->arrange || c->isfloating)
1016 resize(c, nx, ny, c->w, c->h, False);
1023 nexttiled(Client *c) {
1024 for(; c && (c->isfloating || c->isbanned); c = c->next);
1029 propertynotify(XEvent *e) {
1032 XPropertyEvent *ev = &e->xproperty;
1034 if(ev->state == PropertyDelete)
1035 return; /* ignore */
1036 if((c = getclient(ev->window))) {
1039 case XA_WM_TRANSIENT_FOR:
1040 XGetTransientForHint(dpy, c->win, &trans);
1041 if(!c->isfloating && (c->isfloating = (getclient(trans) != NULL)))
1044 case XA_WM_NORMAL_HINTS:
1052 if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
1061 quit(const Arg *arg) {
1062 readin = running = False;
1066 resize(Client *c, int x, int y, int w, int h, Bool sizehints) {
1070 /* set minimum possible */
1074 /* temporarily remove base dimensions */
1078 /* adjust for aspect limits */
1079 if(c->mina > 0 && c->maxa > 0) {
1080 if(c->maxa < (float) w/h)
1082 else if(c->mina > (float) h/w)
1086 /* adjust for increment value */
1092 /* restore base dimensions */
1096 w = MAX(w, c->minw);
1097 h = MAX(h, c->minh);
1100 w = MIN(w, c->maxw);
1103 h = MIN(h, c->maxh);
1105 if(w <= 0 || h <= 0)
1108 x = sw - w - 2 * c->bw;
1110 y = sh - h - 2 * c->bw;
1111 if(x + w + 2 * c->bw < sx)
1113 if(y + h + 2 * c->bw < sy)
1119 if(c->x != x || c->y != y || c->w != w || c->h != h || c->ismoved) {
1123 c->w = wc.width = w;
1124 c->h = wc.height = h;
1125 wc.border_width = c->bw;
1126 XConfigureWindow(dpy, c->win,
1127 CWX|CWY|CWWidth|CWHeight|CWBorderWidth, &wc);
1134 resizemouse(Client *c) {
1142 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1143 None, cursor[CurResize], CurrentTime) != GrabSuccess)
1145 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->bw - 1, c->h + c->bw - 1);
1147 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask , &ev);
1150 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0,
1151 c->w + c->bw - 1, c->h + c->bw - 1);
1152 XUngrabPointer(dpy, CurrentTime);
1153 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1155 case ConfigureRequest:
1158 handler[ev.type](&ev);
1162 nw = MAX(ev.xmotion.x - ocx - 2 * c->bw + 1, 1);
1163 nh = MAX(ev.xmotion.y - ocy - 2 * c->bw + 1, 1);
1165 if(snap && nw >= wx && nw <= wx + ww
1166 && nh >= wy && nh <= wy + wh) {
1167 if(!c->isfloating && lt->arrange
1168 && (abs(nw - c->w) > snap || abs(nh - c->h) > snap))
1169 togglefloating(NULL);
1171 if(!lt->arrange || c->isfloating)
1172 resize(c, c->x, c->y, nw, nh, True);
1187 if(ismax || sel->isfloating || !lt->arrange)
1188 XRaiseWindow(dpy, sel->win);
1189 if(!ismax && lt->arrange) {
1190 wc.stack_mode = Below;
1191 wc.sibling = barwin;
1192 for(c = stack; c; c = c->snext)
1193 if(!c->isfloating && !c->isbanned) {
1194 XConfigureWindow(dpy, c->win, CWSibling|CWStackMode, &wc);
1195 wc.sibling = c->win;
1199 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1205 char sbuf[sizeof stext];
1211 /* main event loop, also reads status text from stdin */
1213 xfd = ConnectionNumber(dpy);
1216 len = sizeof stext - 1;
1217 sbuf[len] = stext[len] = '\0'; /* 0-terminator is never touched */
1221 FD_SET(STDIN_FILENO, &rd);
1223 if(select(xfd + 1, &rd, NULL, NULL, NULL) == -1) {
1226 eprint("select failed\n");
1228 if(FD_ISSET(STDIN_FILENO, &rd)) {
1229 switch((r = read(STDIN_FILENO, sbuf + offset, len - offset))) {
1231 strncpy(stext, strerror(errno), len);
1235 strncpy(stext, "EOF", 4);
1239 for(p = sbuf + offset; r > 0; p++, r--, offset++)
1240 if(*p == '\n' || *p == '\0') {
1242 strncpy(stext, sbuf, len);
1243 p += r - 1; /* p is sbuf + offset + r - 1 */
1244 for(r = 0; *(p - r) && *(p - r) != '\n'; r++);
1247 memmove(sbuf, p - r + 1, r);
1254 while(XPending(dpy)) {
1255 XNextEvent(dpy, &ev);
1256 if(handler[ev.type])
1257 (handler[ev.type])(&ev); /* call handler */
1265 Window *wins, d1, d2;
1266 XWindowAttributes wa;
1269 if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1270 for(i = 0; i < num; i++) {
1271 if(!XGetWindowAttributes(dpy, wins[i], &wa)
1272 || wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1274 if(wa.map_state == IsViewable || getstate(wins[i]) == IconicState)
1275 manage(wins[i], &wa);
1277 for(i = 0; i < num; i++) { /* now the transients */
1278 if(!XGetWindowAttributes(dpy, wins[i], &wa))
1280 if(XGetTransientForHint(dpy, wins[i], &d1)
1281 && (wa.map_state == IsViewable || getstate(wins[i]) == IconicState))
1282 manage(wins[i], &wa);
1290 setclientstate(Client *c, long state) {
1291 long data[] = {state, None};
1293 XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1294 PropModeReplace, (unsigned char *)data, 2);
1297 /* arg > 1.0 will set mfact absolutly */
1299 setmfact(const Arg *arg) {
1302 if(!arg || !lt->arrange)
1304 f = arg->f < 1.0 ? arg->f + mfact : arg->f - 1.0;
1305 if(f < 0.1 || f > 0.9)
1315 XSetWindowAttributes wa;
1318 screen = DefaultScreen(dpy);
1319 root = RootWindow(dpy, screen);
1323 sw = DisplayWidth(dpy, screen);
1324 sh = DisplayHeight(dpy, screen);
1325 bh = dc.font.height + 2;
1330 wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1331 wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1332 wmatom[WMName] = XInternAtom(dpy, "WM_NAME", False);
1333 wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1334 netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1335 netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1338 wa.cursor = cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1339 cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1340 cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1342 /* init appearance */
1343 dc.norm[ColBorder] = getcolor(NORMBORDERCOLOR);
1344 dc.norm[ColBG] = getcolor(NORMBGCOLOR);
1345 dc.norm[ColFG] = getcolor(NORMFGCOLOR);
1346 dc.sel[ColBorder] = getcolor(SELBORDERCOLOR);
1347 dc.sel[ColBG] = getcolor(SELBGCOLOR);
1348 dc.sel[ColFG] = getcolor(SELFGCOLOR);
1351 dc.drawable = XCreatePixmap(dpy, root, DisplayWidth(dpy, screen), bh, DefaultDepth(dpy, screen));
1352 dc.gc = XCreateGC(dpy, root, 0, 0);
1353 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
1355 XSetFont(dpy, dc.gc, dc.font.xfont->fid);
1358 for(blw = i = 0; LENGTH(layouts) > 1 && i < LENGTH(layouts); i++) {
1359 w = TEXTW(layouts[i].symbol);
1363 wa.override_redirect = 1;
1364 wa.background_pixmap = ParentRelative;
1365 wa.event_mask = ButtonPressMask|ExposureMask;
1367 barwin = XCreateWindow(dpy, root, wx, by, ww, bh, 0, DefaultDepth(dpy, screen),
1368 CopyFromParent, DefaultVisual(dpy, screen),
1369 CWOverrideRedirect|CWBackPixmap|CWEventMask, &wa);
1370 XDefineCursor(dpy, barwin, cursor[CurNormal]);
1371 XMapRaised(dpy, barwin);
1372 strcpy(stext, "dwm-"VERSION);
1375 /* EWMH support per view */
1376 XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1377 PropModeReplace, (unsigned char *) netatom, NetLast);
1379 /* select for events */
1380 wa.event_mask = SubstructureRedirectMask|SubstructureNotifyMask
1381 |EnterWindowMask|LeaveWindowMask|StructureNotifyMask;
1382 XChangeWindowAttributes(dpy, root, CWEventMask|CWCursor, &wa);
1383 XSelectInput(dpy, root, wa.event_mask);
1391 spawn(const Arg *arg) {
1392 /* The double-fork construct avoids zombie processes and keeps the code
1393 * clean from stupid signal handlers. */
1397 close(ConnectionNumber(dpy));
1399 execvp(((char **)arg->v)[0], (char **)arg->v);
1400 fprintf(stderr, "dwm: execvp %s", ((char **)arg->v)[0]);
1409 tag(const Arg *arg) {
1410 if(sel && arg->ui & TAGMASK) {
1411 sel->tags = arg->ui & TAGMASK;
1417 textnw(const char *text, uint len) {
1421 XmbTextExtents(dc.font.set, text, len, NULL, &r);
1424 return XTextWidth(dc.font.xfont, text, len);
1433 for(n = 0, c = nexttiled(clients); c; c = nexttiled(c->next), n++);
1438 c = nexttiled(clients);
1440 resize(c, wx, wy, (n == 1 ? ww : mw) - 2 * c->bw, wh - 2 * c->bw, resizehints);
1446 x = (wx + mw > c->x + c->w) ? c->x + c->w + 2 * c->bw : wx + mw;
1448 w = (wx + mw > c->x + c->w) ? wx + ww - x : ww - mw;
1453 for(i = 0, c = nexttiled(c->next); c; c = nexttiled(c->next), i++) {
1454 resize(c, x, y, w - 2 * c->bw, /* remainder */ ((i + 1 == n)
1455 ? (wy + wh) - y : h) - 2 * c->bw, resizehints);
1457 y = c->y + c->h + 2 * c->bw;
1462 togglebar(const Arg *arg) {
1470 togglefloating(const Arg *arg) {
1473 sel->isfloating = !sel->isfloating || sel->isfixed;
1475 resize(sel, sel->x, sel->y, sel->w, sel->h, True);
1480 togglelayout(const Arg *arg) {
1482 lt = (Layout *)arg->v;
1483 else if(++lt == &layouts[LENGTH(layouts)])
1492 togglemax(const Arg *arg) {
1498 toggletag(const Arg *arg) {
1499 if(sel && (sel->tags ^= (arg->ui & TAGMASK)))
1504 toggleview(const Arg *arg) {
1505 if((tagset[seltags] ^= (arg->ui & TAGMASK)))
1510 unmanage(Client *c) {
1513 wc.border_width = c->oldbw;
1514 /* The server grab construct avoids race conditions. */
1516 XSetErrorHandler(xerrordummy);
1517 XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
1522 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1523 setclientstate(c, WithdrawnState);
1526 XSetErrorHandler(xerror);
1532 unmapnotify(XEvent *e) {
1534 XUnmapEvent *ev = &e->xunmap;
1536 if((c = getclient(ev->window)))
1542 if(dc.drawable != 0)
1543 XFreePixmap(dpy, dc.drawable);
1544 dc.drawable = XCreatePixmap(dpy, root, ww, bh, DefaultDepth(dpy, screen));
1545 XMoveResizeWindow(dpy, barwin, wx, by, ww, bh);
1552 XineramaScreenInfo *info = NULL;
1554 /* window area geometry */
1555 if(XineramaIsActive(dpy)) {
1556 info = XineramaQueryScreens(dpy, &i);
1558 wy = showbar && topbar ? info[0].y_org + bh : info[0].y_org;
1560 wh = showbar ? info[0].height - bh : info[0].height;
1567 wy = showbar && topbar ? sy + bh : sy;
1569 wh = showbar ? sh - bh : sh;
1573 by = showbar ? (topbar ? wy - bh : wy + wh) : -bh;
1577 updatesizehints(Client *c) {
1581 XGetWMNormalHints(dpy, c->win, &size, &msize);
1582 if(size.flags & PBaseSize) {
1583 c->basew = size.base_width;
1584 c->baseh = size.base_height;
1586 else if(size.flags & PMinSize) {
1587 c->basew = size.min_width;
1588 c->baseh = size.min_height;
1591 c->basew = c->baseh = 0;
1592 if(size.flags & PResizeInc) {
1593 c->incw = size.width_inc;
1594 c->inch = size.height_inc;
1597 c->incw = c->inch = 0;
1598 if(size.flags & PMaxSize) {
1599 c->maxw = size.max_width;
1600 c->maxh = size.max_height;
1603 c->maxw = c->maxh = 0;
1604 if(size.flags & PMinSize) {
1605 c->minw = size.min_width;
1606 c->minh = size.min_height;
1608 else if(size.flags & PBaseSize) {
1609 c->minw = size.base_width;
1610 c->minh = size.base_height;
1613 c->minw = c->minh = 0;
1614 if(size.flags & PAspect) {
1615 c->mina = (float)size.min_aspect.y / (float)size.min_aspect.x;
1616 c->maxa = (float)size.max_aspect.x / (float)size.max_aspect.y;
1619 c->maxa = c->mina = 0.0;
1620 c->isfixed = (c->maxw && c->minw && c->maxh && c->minh
1621 && c->maxw == c->minw && c->maxh == c->minh);
1625 updatetitle(Client *c) {
1626 if(!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
1627 gettextprop(c->win, wmatom[WMName], c->name, sizeof c->name);
1631 updatewmhints(Client *c) {
1634 if((wmh = XGetWMHints(dpy, c->win))) {
1636 sel->isurgent = False;
1638 c->isurgent = (wmh->flags & XUrgencyHint) ? True : False;
1644 view(const Arg *arg) {
1645 seltags ^= 1; /* toggle sel tagset */
1646 if(arg && (arg->ui & TAGMASK))
1647 tagset[seltags] = arg->i & TAGMASK;
1651 /* There's no way to check accesses to destroyed windows, thus those cases are
1652 * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
1653 * default error handler, which may call exit. */
1655 xerror(Display *dpy, XErrorEvent *ee) {
1656 if(ee->error_code == BadWindow
1657 || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1658 || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1659 || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1660 || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1661 || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1662 || (ee->request_code == X_GrabButton && ee->error_code == BadAccess)
1663 || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1664 || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1666 fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1667 ee->request_code, ee->error_code);
1668 return xerrorxlib(dpy, ee); /* may call exit */
1672 xerrordummy(Display *dpy, XErrorEvent *ee) {
1676 /* Startup Error handler to check if another window manager
1677 * is already running. */
1679 xerrorstart(Display *dpy, XErrorEvent *ee) {
1685 zoom(const Arg *arg) {
1688 if(ismax || !lt->arrange || (sel && sel->isfloating))
1690 if(c == nexttiled(clients))
1691 if(!c || !(c = nexttiled(c->next)))
1700 main(int argc, char *argv[]) {
1701 if(argc == 2 && !strcmp("-v", argv[1]))
1702 eprint("dwm-"VERSION", © 2006-2008 dwm engineers, see LICENSE for details\n");
1704 eprint("usage: dwm [-v]\n");
1706 setlocale(LC_CTYPE, "");
1707 if(!(dpy = XOpenDisplay(0)))
1708 eprint("dwm: cannot open display\n");