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 Window root, barwin;
229 /* configuration, allows nested code to access above variables */
232 static Layout *lt = layouts;
234 /* compile-time check if all tags fit into an uint bit array. */
235 struct NumTags { char limitexceeded[sizeof(uint) * 8 < LENGTH(tags) ? -1 : 1]; };
237 /* function implementations */
239 applyrules(Client *c) {
242 XClassHint ch = { 0 };
245 XGetClassHint(dpy, c->win, &ch);
246 for(i = 0; i < LENGTH(rules); i++) {
248 if((!r->title || strstr(c->name, r->title))
249 && (!r->class || (ch.res_class && strstr(ch.res_class, r->class)))
250 && (!r->instance || (ch.res_name && strstr(ch.res_name, r->instance)))) {
251 c->isfloating = r->isfloating;
252 c->tags |= r->tags & TAGMASK;
260 c->tags = tagset[seltags];
267 for(c = clients; c; c = c->next)
268 if(c->tags & tagset[seltags]) { /* is visible */
269 if(ismax && !c->isfixed) {
270 XMoveResizeWindow(dpy, c->win, wx, wy, ww - 2 * c->bw, wh - 2 * c->bw);
273 else if(!lt->arrange || c->isfloating)
274 resize(c, c->x, c->y, c->w, c->h, True);
277 else if(!c->isbanned) {
278 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
279 c->isbanned = c->ismoved = True;
283 if(lt->arrange && !ismax)
295 attachstack(Client *c) {
301 buttonpress(XEvent *e) {
305 XButtonPressedEvent *ev = &e->xbutton;
307 if(ev->window == barwin) {
309 for(i = 0; i < LENGTH(tags); i++) {
313 if(ev->button == Button1) {
314 if(ev->state & MODKEY)
319 else if(ev->button == Button3) {
320 if(ev->state & MODKEY)
321 toggletag((Arg*)&mask);
323 toggleview((Arg*)&mask);
328 if(ev->x < x + blw) {
329 if(ev->button == Button1)
331 else if(ev->button == Button3)
335 else if((c = getclient(ev->window))) {
337 if(CLEANMASK(ev->state) != MODKEY || (ismax && !c->isfixed))
339 if(ev->button == Button1)
341 else if(ev->button == Button2)
342 togglefloating(NULL);
343 else if(ev->button == Button3 && !c->isfixed)
351 XSetErrorHandler(xerrorstart);
353 /* this causes an error if some other window manager is running */
354 XSelectInput(dpy, DefaultRootWindow(dpy), SubstructureRedirectMask);
357 eprint("dwm: another window manager is already running\n");
358 XSetErrorHandler(NULL);
359 xerrorxlib = XSetErrorHandler(xerror);
374 XFreeFontSet(dpy, dc.font.set);
376 XFreeFont(dpy, dc.font.xfont);
377 XUngrabKey(dpy, AnyKey, AnyModifier, root);
378 XFreePixmap(dpy, dc.drawable);
380 XFreeCursor(dpy, cursor[CurNormal]);
381 XFreeCursor(dpy, cursor[CurResize]);
382 XFreeCursor(dpy, cursor[CurMove]);
383 XDestroyWindow(dpy, barwin);
385 XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime);
389 configure(Client *c) {
392 ce.type = ConfigureNotify;
400 ce.border_width = c->bw;
402 ce.override_redirect = False;
403 XSendEvent(dpy, c->win, False, StructureNotifyMask, (XEvent *)&ce);
407 configurenotify(XEvent *e) {
408 XConfigureEvent *ev = &e->xconfigure;
410 if(ev->window == root && (ev->width != sw || ev->height != sh)) {
420 configurerequest(XEvent *e) {
422 XConfigureRequestEvent *ev = &e->xconfigurerequest;
425 if((c = getclient(ev->window))) {
426 if(ev->value_mask & CWBorderWidth)
427 c->bw = ev->border_width;
428 if(ismax && !c->isbanned && !c->isfixed)
429 XMoveResizeWindow(dpy, c->win, wx, wy, ww - 2 * c->bw, wh + 2 * c->bw);
430 else if(c->isfloating || !lt->arrange) {
431 if(ev->value_mask & CWX)
433 if(ev->value_mask & CWY)
435 if(ev->value_mask & CWWidth)
437 if(ev->value_mask & CWHeight)
439 if((c->x - sx + c->w) > sw && c->isfloating)
440 c->x = sx + (sw / 2 - c->w / 2); /* center in x direction */
441 if((c->y - sy + c->h) > sh && c->isfloating)
442 c->y = sy + (sh / 2 - c->h / 2); /* center in y direction */
443 if((ev->value_mask & (CWX|CWY))
444 && !(ev->value_mask & (CWWidth|CWHeight)))
447 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h);
455 wc.width = ev->width;
456 wc.height = ev->height;
457 wc.border_width = ev->border_width;
458 wc.sibling = ev->above;
459 wc.stack_mode = ev->detail;
460 XConfigureWindow(dpy, ev->window, ev->value_mask, &wc);
466 destroynotify(XEvent *e) {
468 XDestroyWindowEvent *ev = &e->xdestroywindow;
470 if((c = getclient(ev->window)))
479 for(i = clients; i->next != c; i = i->next);
489 detachstack(Client *c) {
492 for(tc = &stack; *tc && *tc != c; tc = &(*tc)->snext);
502 for(c = stack; c && c->isbanned; c = c->snext);
503 for(i = 0; i < LENGTH(tags); i++) {
504 dc.w = TEXTW(tags[i]);
505 if(tagset[seltags] & 1 << i) {
506 drawtext(tags[i], dc.sel, isurgent(i));
507 drawsquare(c && c->tags & 1 << i, isoccupied(i), isurgent(i), dc.sel);
510 drawtext(tags[i], dc.norm, isurgent(i));
511 drawsquare(c && c->tags & 1 << i, isoccupied(i), isurgent(i), dc.norm);
517 drawtext(lt->symbol, dc.norm, ismax);
528 drawtext(stext, dc.norm, False);
529 if((dc.w = dc.x - x) > bh) {
532 drawtext(c->name, dc.sel, False);
533 drawsquare(c->isfixed, c->isfloating, False, dc.sel);
536 drawtext(NULL, dc.norm, False);
538 XCopyArea(dpy, dc.drawable, barwin, dc.gc, 0, 0, ww, bh, 0, 0);
543 drawsquare(Bool filled, Bool empty, Bool invert, ulong col[ColLast]) {
546 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
548 gcv.foreground = col[invert ? ColBG : ColFG];
549 XChangeGC(dpy, dc.gc, GCForeground, &gcv);
550 x = (dc.font.ascent + dc.font.descent + 2) / 4;
554 r.width = r.height = x + 1;
555 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
558 r.width = r.height = x;
559 XDrawRectangles(dpy, dc.drawable, dc.gc, &r, 1);
564 drawtext(const char *text, ulong col[ColLast], Bool invert) {
565 int i, x, y, h, len, olen;
566 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
569 XSetForeground(dpy, dc.gc, col[invert ? ColFG : ColBG]);
570 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
574 len = MIN(olen, sizeof buf);
575 memcpy(buf, text, len);
576 h = dc.font.ascent + dc.font.descent;
577 y = dc.y + (dc.h / 2) - (h / 2) + dc.font.ascent;
579 /* shorten text if necessary */
580 for(; len && (i = textnw(buf, len)) > dc.w - h; len--);
584 for(i = len; i && i > len - 3; buf[--i] = '.');
585 XSetForeground(dpy, dc.gc, col[invert ? ColBG : ColFG]);
587 XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
589 XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
593 enternotify(XEvent *e) {
595 XCrossingEvent *ev = &e->xcrossing;
597 if((ev->mode != NotifyNormal || ev->detail == NotifyInferior) && ev->window != root)
599 if((c = getclient(ev->window)))
606 eprint(const char *errstr, ...) {
609 va_start(ap, errstr);
610 vfprintf(stderr, errstr, ap);
617 XExposeEvent *ev = &e->xexpose;
619 if(ev->count == 0 && (ev->window == barwin))
625 if(!c || c->isbanned)
626 for(c = stack; c && c->isbanned; c = c->snext);
627 if(sel && sel != c) {
628 grabbuttons(sel, False);
629 XSetWindowBorder(dpy, sel->win, dc.norm[ColBorder]);
634 grabbuttons(c, True);
635 XSetWindowBorder(dpy, c->win, dc.sel[ColBorder]);
636 XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
639 XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
645 focusin(XEvent *e) { /* there are some broken focus acquiring clients */
646 XFocusChangeEvent *ev = &e->xfocus;
648 if(sel && ev->window != sel->win)
649 XSetInputFocus(dpy, sel->win, RevertToPointerRoot, CurrentTime);
653 focusstack(const Arg *arg) {
654 Client *c = NULL, *i;
659 for(c = sel->next; c && c->isbanned; c = c->next);
661 for(c = clients; c && c->isbanned; c = c->next);
664 for(i = clients; i != sel; i = i->next)
668 for(; i; i = i->next)
679 getclient(Window w) {
682 for(c = clients; c && c->win != w; c = c->next);
687 getcolor(const char *colstr) {
688 Colormap cmap = DefaultColormap(dpy, screen);
691 if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
692 eprint("error, cannot allocate color '%s'\n", colstr);
700 unsigned char *p = NULL;
704 status = XGetWindowProperty(dpy, w, wmatom[WMState], 0L, 2L, False, wmatom[WMState],
705 &real, &format, &n, &extra, (unsigned char **)&p);
706 if(status != Success)
715 gettextprop(Window w, Atom atom, char *text, uint size) {
720 if(!text || size == 0)
723 XGetTextProperty(dpy, w, &name, atom);
726 if(name.encoding == XA_STRING)
727 strncpy(text, (char *)name.value, size - 1);
729 if(XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success
731 strncpy(text, *list, size - 1);
732 XFreeStringList(list);
735 text[size - 1] = '\0';
741 grabbuttons(Client *c, Bool focused) {
743 uint buttons[] = { Button1, Button2, Button3 };
744 uint modifiers[] = { MODKEY, MODKEY|LockMask, MODKEY|numlockmask, MODKEY|numlockmask|LockMask };
746 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
748 for(i = 0; i < LENGTH(buttons); i++)
749 for(j = 0; j < LENGTH(modifiers); j++)
750 XGrabButton(dpy, buttons[i], modifiers[j], c->win, False,
751 BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
753 XGrabButton(dpy, AnyButton, AnyModifier, c->win, False,
754 BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
761 XModifierKeymap *modmap;
763 /* init modifier map */
764 modmap = XGetModifierMapping(dpy);
765 for(i = 0; i < 8; i++)
766 for(j = 0; j < modmap->max_keypermod; j++) {
767 if(modmap->modifiermap[i * modmap->max_keypermod + j] == XKeysymToKeycode(dpy, XK_Num_Lock))
768 numlockmask = (1 << i);
770 XFreeModifiermap(modmap);
772 XUngrabKey(dpy, AnyKey, AnyModifier, root);
773 for(i = 0; i < LENGTH(keys); i++) {
774 code = XKeysymToKeycode(dpy, keys[i].keysym);
775 XGrabKey(dpy, code, keys[i].mod, root, True,
776 GrabModeAsync, GrabModeAsync);
777 XGrabKey(dpy, code, keys[i].mod|LockMask, root, True,
778 GrabModeAsync, GrabModeAsync);
779 XGrabKey(dpy, code, keys[i].mod|numlockmask, root, True,
780 GrabModeAsync, GrabModeAsync);
781 XGrabKey(dpy, code, keys[i].mod|numlockmask|LockMask, root, True,
782 GrabModeAsync, GrabModeAsync);
787 initfont(const char *fontstr) {
788 char *def, **missing;
793 XFreeFontSet(dpy, dc.font.set);
794 dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
797 fprintf(stderr, "dwm: missing fontset: %s\n", missing[n]);
798 XFreeStringList(missing);
801 XFontSetExtents *font_extents;
802 XFontStruct **xfonts;
804 dc.font.ascent = dc.font.descent = 0;
805 font_extents = XExtentsOfFontSet(dc.font.set);
806 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
807 for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
808 dc.font.ascent = MAX(dc.font.ascent, (*xfonts)->ascent);
809 dc.font.descent = MAX(dc.font.descent,(*xfonts)->descent);
815 XFreeFont(dpy, dc.font.xfont);
816 dc.font.xfont = NULL;
817 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr))
818 && !(dc.font.xfont = XLoadQueryFont(dpy, "fixed")))
819 eprint("error, cannot load font: '%s'\n", fontstr);
820 dc.font.ascent = dc.font.xfont->ascent;
821 dc.font.descent = dc.font.xfont->descent;
823 dc.font.height = dc.font.ascent + dc.font.descent;
830 for(c = clients; c; c = c->next)
837 isprotodel(Client *c) {
842 if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
843 for(i = 0; !ret && i < n; i++)
844 if(protocols[i] == wmatom[WMDelete])
855 for(c = clients; c; c = c->next)
856 if(c->isurgent && c->tags & 1 << t)
862 keypress(XEvent *e) {
868 keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
869 for(i = 0; i < LENGTH(keys); i++)
870 if(keysym == keys[i].keysym
871 && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state)
873 keys[i].func(&(keys[i].arg));
877 killclient(const Arg *arg) {
882 if(isprotodel(sel)) {
883 ev.type = ClientMessage;
884 ev.xclient.window = sel->win;
885 ev.xclient.message_type = wmatom[WMProtocols];
886 ev.xclient.format = 32;
887 ev.xclient.data.l[0] = wmatom[WMDelete];
888 ev.xclient.data.l[1] = CurrentTime;
889 XSendEvent(dpy, sel->win, False, NoEventMask, &ev);
892 XKillClient(dpy, sel->win);
896 manage(Window w, XWindowAttributes *wa) {
897 Client *c, *t = NULL;
902 if(!(c = calloc(1, sizeof(Client))))
903 eprint("fatal: could not calloc() %u bytes\n", sizeof(Client));
911 c->oldbw = wa->border_width;
912 if(c->w == sw && c->h == sh) {
915 c->bw = wa->border_width;
918 if(c->x + c->w + 2 * c->bw > sx + sw)
919 c->x = sx + sw - c->w - 2 * c->bw;
920 if(c->y + c->h + 2 * c->bw > sy + sh)
921 c->y = sy + sh - c->h - 2 * c->bw;
922 c->x = MAX(c->x, sx);
923 c->y = MAX(c->y, by == 0 ? bh : sy);
927 wc.border_width = c->bw;
928 XConfigureWindow(dpy, w, CWBorderWidth, &wc);
929 XSetWindowBorder(dpy, w, dc.norm[ColBorder]);
930 configure(c); /* propagates border_width, if size doesn't change */
932 XSelectInput(dpy, w, EnterWindowMask|FocusChangeMask|PropertyChangeMask|StructureNotifyMask);
933 grabbuttons(c, False);
935 if((rettrans = XGetTransientForHint(dpy, w, &trans) == Success))
936 for(t = clients; t && t->win != trans; t = t->next);
942 c->isfloating = (rettrans == Success) || c->isfixed;
944 XRaiseWindow(dpy, c->win);
947 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h); /* some windows require this */
948 XMapWindow(dpy, c->win);
949 setclientstate(c, NormalState);
954 mappingnotify(XEvent *e) {
955 XMappingEvent *ev = &e->xmapping;
957 XRefreshKeyboardMapping(ev);
958 if(ev->request == MappingKeyboard)
963 maprequest(XEvent *e) {
964 static XWindowAttributes wa;
965 XMapRequestEvent *ev = &e->xmaprequest;
967 if(!XGetWindowAttributes(dpy, ev->window, &wa))
969 if(wa.override_redirect)
971 if(!getclient(ev->window))
972 manage(ev->window, &wa);
976 movemouse(Client *c) {
977 int x1, y1, ocx, ocy, di, nx, ny;
985 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
986 None, cursor[CurMove], CurrentTime) != GrabSuccess)
988 XQueryPointer(dpy, root, &dummy, &dummy, &x1, &y1, &di, &di, &dui);
990 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
993 XUngrabPointer(dpy, CurrentTime);
995 case ConfigureRequest:
998 handler[ev.type](&ev);
1002 nx = ocx + (ev.xmotion.x - x1);
1003 ny = ocy + (ev.xmotion.y - y1);
1004 if(snap && nx >= wx && nx <= wx + ww
1005 && ny >= wy && ny <= wy + wh) {
1006 if(abs(wx - nx) < snap)
1008 else if(abs((wx + ww) - (nx + c->w + 2 * c->bw)) < snap)
1009 nx = wx + ww - c->w - 2 * c->bw;
1010 if(abs(wy - ny) < snap)
1012 else if(abs((wy + wh) - (ny + c->h + 2 * c->bw)) < snap)
1013 ny = wy + wh - c->h - 2 * c->bw;
1014 if(!c->isfloating && lt->arrange && (abs(nx - c->x) > snap || abs(ny - c->y) > snap))
1015 togglefloating(NULL);
1017 if(!lt->arrange || c->isfloating)
1018 resize(c, nx, ny, c->w, c->h, False);
1025 nexttiled(Client *c) {
1026 for(; c && (c->isfloating || c->isbanned); c = c->next);
1031 propertynotify(XEvent *e) {
1034 XPropertyEvent *ev = &e->xproperty;
1036 if(ev->state == PropertyDelete)
1037 return; /* ignore */
1038 if((c = getclient(ev->window))) {
1041 case XA_WM_TRANSIENT_FOR:
1042 XGetTransientForHint(dpy, c->win, &trans);
1043 if(!c->isfloating && (c->isfloating = (getclient(trans) != NULL)))
1046 case XA_WM_NORMAL_HINTS:
1054 if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
1063 quit(const Arg *arg) {
1064 readin = running = False;
1068 resize(Client *c, int x, int y, int w, int h, Bool sizehints) {
1072 /* set minimum possible */
1076 /* temporarily remove base dimensions */
1080 /* adjust for aspect limits */
1081 if(c->mina > 0 && c->maxa > 0) {
1082 if(c->maxa < (float) w/h)
1084 else if(c->mina > (float) h/w)
1088 /* adjust for increment value */
1094 /* restore base dimensions */
1098 w = MAX(w, c->minw);
1099 h = MAX(h, c->minh);
1102 w = MIN(w, c->maxw);
1105 h = MIN(h, c->maxh);
1107 if(w <= 0 || h <= 0)
1110 x = sw - w - 2 * c->bw;
1112 y = sh - h - 2 * c->bw;
1113 if(x + w + 2 * c->bw < sx)
1115 if(y + h + 2 * c->bw < sy)
1121 if(c->x != x || c->y != y || c->w != w || c->h != h || c->ismoved) {
1125 c->w = wc.width = w;
1126 c->h = wc.height = h;
1127 wc.border_width = c->bw;
1128 XConfigureWindow(dpy, c->win,
1129 CWX|CWY|CWWidth|CWHeight|CWBorderWidth, &wc);
1136 resizemouse(Client *c) {
1144 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1145 None, cursor[CurResize], CurrentTime) != GrabSuccess)
1147 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->bw - 1, c->h + c->bw - 1);
1149 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask , &ev);
1152 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0,
1153 c->w + c->bw - 1, c->h + c->bw - 1);
1154 XUngrabPointer(dpy, CurrentTime);
1155 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1157 case ConfigureRequest:
1160 handler[ev.type](&ev);
1164 nw = MAX(ev.xmotion.x - ocx - 2 * c->bw + 1, 1);
1165 nh = MAX(ev.xmotion.y - ocy - 2 * c->bw + 1, 1);
1167 if(snap && nw >= wx && nw <= wx + ww
1168 && nh >= wy && nh <= wy + wh) {
1169 if(!c->isfloating && lt->arrange
1170 && (abs(nw - c->w) > snap || abs(nh - c->h) > snap))
1171 togglefloating(NULL);
1173 if(!lt->arrange || c->isfloating)
1174 resize(c, c->x, c->y, nw, nh, True);
1189 if(ismax || sel->isfloating || !lt->arrange)
1190 XRaiseWindow(dpy, sel->win);
1191 if(!ismax && lt->arrange) {
1192 wc.stack_mode = Below;
1193 wc.sibling = barwin;
1194 for(c = stack; c; c = c->snext)
1195 if(!c->isfloating && !c->isbanned) {
1196 XConfigureWindow(dpy, c->win, CWSibling|CWStackMode, &wc);
1197 wc.sibling = c->win;
1201 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1207 char sbuf[sizeof stext];
1213 /* main event loop, also reads status text from stdin */
1215 xfd = ConnectionNumber(dpy);
1218 len = sizeof stext - 1;
1219 sbuf[len] = stext[len] = '\0'; /* 0-terminator is never touched */
1223 FD_SET(STDIN_FILENO, &rd);
1225 if(select(xfd + 1, &rd, NULL, NULL, NULL) == -1) {
1228 eprint("select failed\n");
1230 if(FD_ISSET(STDIN_FILENO, &rd)) {
1231 switch((r = read(STDIN_FILENO, sbuf + offset, len - offset))) {
1233 strncpy(stext, strerror(errno), len);
1237 strncpy(stext, "EOF", 4);
1241 for(p = sbuf + offset; r > 0; p++, r--, offset++)
1242 if(*p == '\n' || *p == '\0') {
1244 strncpy(stext, sbuf, len);
1245 p += r - 1; /* p is sbuf + offset + r - 1 */
1246 for(r = 0; *(p - r) && *(p - r) != '\n'; r++);
1249 memmove(sbuf, p - r + 1, r);
1256 while(XPending(dpy)) {
1257 XNextEvent(dpy, &ev);
1258 if(handler[ev.type])
1259 (handler[ev.type])(&ev); /* call handler */
1267 Window *wins, d1, d2;
1268 XWindowAttributes wa;
1271 if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1272 for(i = 0; i < num; i++) {
1273 if(!XGetWindowAttributes(dpy, wins[i], &wa)
1274 || wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1276 if(wa.map_state == IsViewable || getstate(wins[i]) == IconicState)
1277 manage(wins[i], &wa);
1279 for(i = 0; i < num; i++) { /* now the transients */
1280 if(!XGetWindowAttributes(dpy, wins[i], &wa))
1282 if(XGetTransientForHint(dpy, wins[i], &d1)
1283 && (wa.map_state == IsViewable || getstate(wins[i]) == IconicState))
1284 manage(wins[i], &wa);
1292 setclientstate(Client *c, long state) {
1293 long data[] = {state, None};
1295 XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1296 PropModeReplace, (unsigned char *)data, 2);
1299 /* arg > 1.0 will set mfact absolutly */
1301 setmfact(const Arg *arg) {
1304 if(!arg || !lt->arrange)
1306 f = arg->f < 1.0 ? arg->f + mfact : arg->f - 1.0;
1307 if(f < 0.1 || f > 0.9)
1317 XSetWindowAttributes wa;
1320 screen = DefaultScreen(dpy);
1321 root = RootWindow(dpy, screen);
1325 sw = DisplayWidth(dpy, screen);
1326 sh = DisplayHeight(dpy, screen);
1327 bh = 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);
1352 dc.drawable = XCreatePixmap(dpy, root, DisplayWidth(dpy, screen), bh, DefaultDepth(dpy, screen));
1353 dc.gc = XCreateGC(dpy, root, 0, 0);
1354 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
1356 XSetFont(dpy, dc.gc, dc.font.xfont->fid);
1359 for(blw = i = 0; LENGTH(layouts) > 1 && i < LENGTH(layouts); i++) {
1360 w = TEXTW(layouts[i].symbol);
1364 wa.override_redirect = 1;
1365 wa.background_pixmap = ParentRelative;
1366 wa.event_mask = ButtonPressMask|ExposureMask;
1368 barwin = XCreateWindow(dpy, root, wx, by, ww, bh, 0, DefaultDepth(dpy, screen),
1369 CopyFromParent, DefaultVisual(dpy, screen),
1370 CWOverrideRedirect|CWBackPixmap|CWEventMask, &wa);
1371 XDefineCursor(dpy, barwin, cursor[CurNormal]);
1372 XMapRaised(dpy, barwin);
1373 strcpy(stext, "dwm-"VERSION);
1376 /* EWMH support per view */
1377 XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1378 PropModeReplace, (unsigned char *) netatom, NetLast);
1380 /* select for events */
1381 wa.event_mask = SubstructureRedirectMask|SubstructureNotifyMask
1382 |EnterWindowMask|LeaveWindowMask|StructureNotifyMask;
1383 XChangeWindowAttributes(dpy, root, CWEventMask|CWCursor, &wa);
1384 XSelectInput(dpy, root, wa.event_mask);
1392 spawn(const Arg *arg) {
1393 /* The double-fork construct avoids zombie processes and keeps the code
1394 * clean from stupid signal handlers. */
1398 close(ConnectionNumber(dpy));
1400 execvp(((char **)arg->v)[0], (char **)arg->v);
1401 fprintf(stderr, "dwm: execvp %s", ((char **)arg->v)[0]);
1410 tag(const Arg *arg) {
1411 if(sel && arg->ui & TAGMASK) {
1412 sel->tags = arg->ui & TAGMASK;
1418 textnw(const char *text, uint len) {
1422 XmbTextExtents(dc.font.set, text, len, NULL, &r);
1425 return XTextWidth(dc.font.xfont, text, len);
1434 for(n = 0, c = nexttiled(clients); c; c = nexttiled(c->next), n++);
1439 c = nexttiled(clients);
1441 resize(c, wx, wy, (n == 1 ? ww : mw) - 2 * c->bw, wh - 2 * c->bw, resizehints);
1447 x = (wx + mw > c->x + c->w) ? c->x + c->w + 2 * c->bw : wx + mw;
1449 w = (wx + mw > c->x + c->w) ? wx + ww - x : ww - mw;
1454 for(i = 0, c = nexttiled(c->next); c; c = nexttiled(c->next), i++) {
1455 resize(c, x, y, w - 2 * c->bw, /* remainder */ ((i + 1 == n)
1456 ? (wy + wh) - y : h) - 2 * c->bw, resizehints);
1458 y = c->y + c->h + 2 * c->bw;
1463 togglebar(const Arg *arg) {
1471 togglefloating(const Arg *arg) {
1474 sel->isfloating = !sel->isfloating || sel->isfixed;
1476 resize(sel, sel->x, sel->y, sel->w, sel->h, True);
1481 togglelayout(const Arg *arg) {
1483 lt = (Layout *)arg->v;
1484 else if(++lt == &layouts[LENGTH(layouts)])
1493 togglemax(const Arg *arg) {
1499 toggletag(const Arg *arg) {
1500 if(sel && (sel->tags ^= (arg->ui & TAGMASK)))
1505 toggleview(const Arg *arg) {
1506 if((tagset[seltags] ^= (arg->ui & TAGMASK)))
1511 unmanage(Client *c) {
1514 wc.border_width = c->oldbw;
1515 /* The server grab construct avoids race conditions. */
1517 XSetErrorHandler(xerrordummy);
1518 XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
1523 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1524 setclientstate(c, WithdrawnState);
1527 XSetErrorHandler(xerror);
1533 unmapnotify(XEvent *e) {
1535 XUnmapEvent *ev = &e->xunmap;
1537 if((c = getclient(ev->window)))
1543 if(dc.drawable != 0)
1544 XFreePixmap(dpy, dc.drawable);
1545 dc.drawable = XCreatePixmap(dpy, root, ww, bh, DefaultDepth(dpy, screen));
1546 XMoveResizeWindow(dpy, barwin, wx, by, ww, bh);
1553 XineramaScreenInfo *info = NULL;
1555 /* window area geometry */
1556 if(XineramaIsActive(dpy)) {
1557 info = XineramaQueryScreens(dpy, &i);
1559 wy = showbar && topbar ? info[0].y_org + bh : info[0].y_org;
1561 wh = showbar ? info[0].height - bh : info[0].height;
1568 wy = showbar && topbar ? sy + bh : sy;
1570 wh = showbar ? sh - bh : sh;
1574 by = showbar ? (topbar ? wy - bh : wy + wh) : -bh;
1578 updatesizehints(Client *c) {
1582 XGetWMNormalHints(dpy, c->win, &size, &msize);
1583 if(size.flags & PBaseSize) {
1584 c->basew = size.base_width;
1585 c->baseh = size.base_height;
1587 else if(size.flags & PMinSize) {
1588 c->basew = size.min_width;
1589 c->baseh = size.min_height;
1592 c->basew = c->baseh = 0;
1593 if(size.flags & PResizeInc) {
1594 c->incw = size.width_inc;
1595 c->inch = size.height_inc;
1598 c->incw = c->inch = 0;
1599 if(size.flags & PMaxSize) {
1600 c->maxw = size.max_width;
1601 c->maxh = size.max_height;
1604 c->maxw = c->maxh = 0;
1605 if(size.flags & PMinSize) {
1606 c->minw = size.min_width;
1607 c->minh = size.min_height;
1609 else if(size.flags & PBaseSize) {
1610 c->minw = size.base_width;
1611 c->minh = size.base_height;
1614 c->minw = c->minh = 0;
1615 if(size.flags & PAspect) {
1616 c->mina = (float)size.min_aspect.y / (float)size.min_aspect.x;
1617 c->maxa = (float)size.max_aspect.x / (float)size.max_aspect.y;
1620 c->maxa = c->mina = 0.0;
1621 c->isfixed = (c->maxw && c->minw && c->maxh && c->minh
1622 && c->maxw == c->minw && c->maxh == c->minh);
1626 updatetitle(Client *c) {
1627 if(!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
1628 gettextprop(c->win, wmatom[WMName], c->name, sizeof c->name);
1632 updatewmhints(Client *c) {
1635 if((wmh = XGetWMHints(dpy, c->win))) {
1637 sel->isurgent = False;
1639 c->isurgent = (wmh->flags & XUrgencyHint) ? True : False;
1645 view(const Arg *arg) {
1646 seltags ^= 1; /* toggle sel tagset */
1647 if(arg && (arg->ui & TAGMASK))
1648 tagset[seltags] = arg->i & TAGMASK;
1652 /* There's no way to check accesses to destroyed windows, thus those cases are
1653 * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
1654 * default error handler, which may call exit. */
1656 xerror(Display *dpy, XErrorEvent *ee) {
1657 if(ee->error_code == BadWindow
1658 || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1659 || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1660 || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1661 || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1662 || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1663 || (ee->request_code == X_GrabButton && ee->error_code == BadAccess)
1664 || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1665 || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1667 fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1668 ee->request_code, ee->error_code);
1669 return xerrorxlib(dpy, ee); /* may call exit */
1673 xerrordummy(Display *dpy, XErrorEvent *ee) {
1677 /* Startup Error handler to check if another window manager
1678 * is already running. */
1680 xerrorstart(Display *dpy, XErrorEvent *ee) {
1686 zoom(const Arg *arg) {
1689 if(ismax || !lt->arrange || (sel && sel->isfloating))
1691 if(c == nexttiled(clients))
1692 if(!c || !(c = nexttiled(c->next)))
1701 main(int argc, char *argv[]) {
1702 if(argc == 2 && !strcmp("-v", argv[1]))
1703 eprint("dwm-"VERSION", © 2006-2008 dwm engineers, see LICENSE for details\n");
1705 eprint("usage: dwm [-v]\n");
1707 setlocale(LC_CTYPE, "");
1708 if(!(dpy = XOpenDisplay(0)))
1709 eprint("dwm: cannot open display\n");