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;
71 int minax, maxax, minay, maxay;
73 Bool isbanned, isfixed, isfloating, ismoved, isurgent;
94 } DC; /* draw context */
99 void (*func)(const void *arg);
105 void (*arrange)(void);
110 const char *instance;
116 /* function declarations */
117 void applyrules(Client *c);
119 void attach(Client *c);
120 void attachstack(Client *c);
121 void buttonpress(XEvent *e);
122 void checkotherwm(void);
124 void configure(Client *c);
125 void configurenotify(XEvent *e);
126 void configurerequest(XEvent *e);
127 void destroynotify(XEvent *e);
128 void detach(Client *c);
129 void detachstack(Client *c);
131 void drawsquare(Bool filled, Bool empty, Bool invert, ulong col[ColLast]);
132 void drawtext(const char *text, ulong col[ColLast], Bool invert);
133 void enternotify(XEvent *e);
134 void eprint(const char *errstr, ...);
135 void expose(XEvent *e);
136 void focus(Client *c);
137 void focusin(XEvent *e);
138 void focusnext(const void *arg);
139 void focusprev(const void *arg);
140 Client *getclient(Window w);
141 ulong getcolor(const char *colstr);
142 long getstate(Window w);
143 Bool gettextprop(Window w, Atom atom, char *text, uint size);
144 void grabbuttons(Client *c, Bool focused);
146 void initfont(const char *fontstr);
147 Bool isoccupied(uint t);
148 Bool isprotodel(Client *c);
149 Bool isurgent(uint t);
150 void keypress(XEvent *e);
151 void killclient(const void *arg);
152 void manage(Window w, XWindowAttributes *wa);
153 void mappingnotify(XEvent *e);
154 void maprequest(XEvent *e);
155 void movemouse(Client *c);
156 Client *nexttiled(Client *c);
157 void propertynotify(XEvent *e);
158 void quit(const void *arg);
159 void resize(Client *c, int x, int y, int w, int h, Bool sizehints);
160 void resizemouse(Client *c);
164 void setclientstate(Client *c, long state);
165 void setmfact(const void *arg);
167 void spawn(const void *arg);
168 void tag(const void *arg);
169 uint textnw(const char *text, uint len);
171 void togglebar(const void *arg);
172 void togglefloating(const void *arg);
173 void togglelayout(const void *arg);
174 void togglemax(const void *arg);
175 void toggletag(const void *arg);
176 void toggleview(const void *arg);
177 void unmanage(Client *c);
178 void unmapnotify(XEvent *e);
179 void updatebar(void);
180 void updategeom(void);
181 void updatesizehints(Client *c);
182 void updatetitle(Client *c);
183 void updatewmhints(Client *c);
184 void view(const void *arg);
185 int xerror(Display *dpy, XErrorEvent *ee);
186 int xerrordummy(Display *dpy, XErrorEvent *ee);
187 int xerrorstart(Display *dpy, XErrorEvent *ee);
188 void zoom(const void *arg);
192 int screen, sx, sy, sw, sh;
193 int by, bh, blw, wx, wy, ww, wh;
195 int (*xerrorxlib)(Display *, XErrorEvent *);
196 uint numlockmask = 0;
197 void (*handler[LASTEvent]) (XEvent *) = {
198 [ButtonPress] = buttonpress,
199 [ConfigureRequest] = configurerequest,
200 [ConfigureNotify] = configurenotify,
201 [DestroyNotify] = destroynotify,
202 [EnterNotify] = enternotify,
205 [KeyPress] = keypress,
206 [MappingNotify] = mappingnotify,
207 [MapRequest] = maprequest,
208 [PropertyNotify] = propertynotify,
209 [UnmapNotify] = unmapnotify
211 Atom wmatom[WMLast], netatom[NetLast];
213 Bool otherwm, readin;
215 uint tagset[] = {1, 1}; /* after start, first tag is selected */
216 Client *clients = NULL;
218 Client *stack = NULL;
219 Cursor cursor[CurLast];
223 Layout *lt = layouts;
226 /* configuration, allows nested code to access above variables */
229 /* compile-time check if all tags fit into an uint bit array. */
230 struct NumTags { char limitexceeded[sizeof(uint) * 8 < LENGTH(tags) ? -1 : 1]; };
232 /* function implementations */
234 applyrules(Client *c) {
237 XClassHint ch = { 0 };
240 XGetClassHint(dpy, c->win, &ch);
241 for(i = 0; i < LENGTH(rules); i++) {
243 if((!r->title || strstr(c->name, r->title))
244 && (!r->class || (ch.res_class && strstr(ch.res_class, r->class)))
245 && (!r->instance || (ch.res_name && strstr(ch.res_name, r->instance)))) {
246 c->isfloating = r->isfloating;
247 c->tags |= r->tags & TAGMASK;
255 c->tags = tagset[seltags];
262 for(c = clients; c; c = c->next)
263 if(c->tags & tagset[seltags]) { /* is visible */
264 if(ismax && !c->isfixed) {
265 XMoveResizeWindow(dpy, c->win, wx, wy, ww - 2 * c->bw, wh - 2 * c->bw);
268 else if(!lt->arrange || c->isfloating)
269 resize(c, c->x, c->y, c->w, c->h, True);
272 else if(!c->isbanned) {
273 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
274 c->isbanned = c->ismoved = True;
278 if(lt->arrange && !ismax)
292 attachstack(Client *c) {
298 buttonpress(XEvent *e) {
301 XButtonPressedEvent *ev = &e->xbutton;
303 if(ev->window == barwin) {
305 for(i = 0; i < LENGTH(tags); i++) {
309 if(ev->button == Button1) {
310 if(ev->state & MODKEY)
315 else if(ev->button == Button3) {
316 if(ev->state & MODKEY)
324 if(ev->x < x + blw) {
325 if(ev->button == Button1)
327 else if(ev->button == Button3)
331 else if((c = getclient(ev->window))) {
333 if(CLEANMASK(ev->state) != MODKEY || (ismax && !c->isfixed))
335 if(ev->button == Button1)
337 else if(ev->button == Button2)
338 togglefloating(NULL);
339 else if(ev->button == Button3 && !c->isfixed)
347 XSetErrorHandler(xerrorstart);
349 /* this causes an error if some other window manager is running */
350 XSelectInput(dpy, DefaultRootWindow(dpy), SubstructureRedirectMask);
353 eprint("dwm: another window manager is already running\n");
354 XSetErrorHandler(NULL);
355 xerrorxlib = XSetErrorHandler(xerror);
366 XFreeFontSet(dpy, dc.font.set);
368 XFreeFont(dpy, dc.font.xfont);
369 XUngrabKey(dpy, AnyKey, AnyModifier, root);
370 XFreePixmap(dpy, dc.drawable);
372 XFreeCursor(dpy, cursor[CurNormal]);
373 XFreeCursor(dpy, cursor[CurResize]);
374 XFreeCursor(dpy, cursor[CurMove]);
375 XDestroyWindow(dpy, barwin);
377 XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime);
381 configure(Client *c) {
384 ce.type = ConfigureNotify;
392 ce.border_width = c->bw;
394 ce.override_redirect = False;
395 XSendEvent(dpy, c->win, False, StructureNotifyMask, (XEvent *)&ce);
399 configurenotify(XEvent *e) {
400 XConfigureEvent *ev = &e->xconfigure;
402 if(ev->window == root && (ev->width != sw || ev->height != sh)) {
412 configurerequest(XEvent *e) {
414 XConfigureRequestEvent *ev = &e->xconfigurerequest;
417 if((c = getclient(ev->window))) {
418 if(ev->value_mask & CWBorderWidth)
419 c->bw = ev->border_width;
420 if(ismax && !c->isbanned && !c->isfixed)
421 XMoveResizeWindow(dpy, c->win, wx, wy, ww - 2 * c->bw, wh + 2 * c->bw);
422 else if(c->isfloating || !lt->arrange) {
423 if(ev->value_mask & CWX)
425 if(ev->value_mask & CWY)
427 if(ev->value_mask & CWWidth)
429 if(ev->value_mask & CWHeight)
431 if((c->x - sx + c->w) > sw && c->isfloating)
432 c->x = sx + (sw / 2 - c->w / 2); /* center in x direction */
433 if((c->y - sy + c->h) > sh && c->isfloating)
434 c->y = sy + (sh / 2 - c->h / 2); /* center in y direction */
435 if((ev->value_mask & (CWX|CWY))
436 && !(ev->value_mask & (CWWidth|CWHeight)))
439 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h);
447 wc.width = ev->width;
448 wc.height = ev->height;
449 wc.border_width = ev->border_width;
450 wc.sibling = ev->above;
451 wc.stack_mode = ev->detail;
452 XConfigureWindow(dpy, ev->window, ev->value_mask, &wc);
458 destroynotify(XEvent *e) {
460 XDestroyWindowEvent *ev = &e->xdestroywindow;
462 if((c = getclient(ev->window)))
469 c->prev->next = c->next;
471 c->next->prev = c->prev;
474 c->next = c->prev = NULL;
478 detachstack(Client *c) {
481 for(tc = &stack; *tc && *tc != c; tc = &(*tc)->snext);
491 for(c = stack; c && c->isbanned; c = c->snext);
492 for(i = 0; i < LENGTH(tags); i++) {
493 dc.w = TEXTW(tags[i]);
494 if(tagset[seltags] & 1 << i) {
495 drawtext(tags[i], dc.sel, isurgent(i));
496 drawsquare(c && c->tags & 1 << i, isoccupied(i), isurgent(i), dc.sel);
499 drawtext(tags[i], dc.norm, isurgent(i));
500 drawsquare(c && c->tags & 1 << i, isoccupied(i), isurgent(i), dc.norm);
506 drawtext(lt->symbol, dc.norm, ismax);
517 drawtext(stext, dc.norm, False);
518 if((dc.w = dc.x - x) > bh) {
521 drawtext(c->name, dc.sel, False);
522 drawsquare(c->isfixed, c->isfloating, False, dc.sel);
525 drawtext(NULL, dc.norm, False);
527 XCopyArea(dpy, dc.drawable, barwin, dc.gc, 0, 0, ww, bh, 0, 0);
532 drawsquare(Bool filled, Bool empty, Bool invert, ulong col[ColLast]) {
535 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
537 gcv.foreground = col[invert ? ColBG : ColFG];
538 XChangeGC(dpy, dc.gc, GCForeground, &gcv);
539 x = (dc.font.ascent + dc.font.descent + 2) / 4;
543 r.width = r.height = x + 1;
544 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
547 r.width = r.height = x;
548 XDrawRectangles(dpy, dc.drawable, dc.gc, &r, 1);
553 drawtext(const char *text, ulong col[ColLast], Bool invert) {
554 int i, x, y, h, len, olen;
555 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
558 XSetForeground(dpy, dc.gc, col[invert ? ColFG : ColBG]);
559 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
563 len = MIN(olen, sizeof buf);
564 memcpy(buf, text, len);
565 h = dc.font.ascent + dc.font.descent;
566 y = dc.y + (dc.h / 2) - (h / 2) + dc.font.ascent;
568 /* shorten text if necessary */
569 for(; len && (i = textnw(buf, len)) > dc.w - h; len--);
573 for(i = len; i >= MAX(0, len - 3); buf[i--] = '.');
574 XSetForeground(dpy, dc.gc, col[invert ? ColBG : ColFG]);
576 XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
578 XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
582 enternotify(XEvent *e) {
584 XCrossingEvent *ev = &e->xcrossing;
586 if((ev->mode != NotifyNormal || ev->detail == NotifyInferior) && ev->window != root)
588 if((c = getclient(ev->window)))
595 eprint(const char *errstr, ...) {
598 va_start(ap, errstr);
599 vfprintf(stderr, errstr, ap);
606 XExposeEvent *ev = &e->xexpose;
608 if(ev->count == 0 && (ev->window == barwin))
614 if(!c || c->isbanned)
615 for(c = stack; c && c->isbanned; c = c->snext);
616 if(sel && sel != c) {
617 grabbuttons(sel, False);
618 XSetWindowBorder(dpy, sel->win, dc.norm[ColBorder]);
623 grabbuttons(c, True);
624 XSetWindowBorder(dpy, c->win, dc.sel[ColBorder]);
625 XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
628 XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
634 focusin(XEvent *e) { /* there are some broken focus acquiring clients */
635 XFocusChangeEvent *ev = &e->xfocus;
637 if(sel && ev->window != sel->win)
638 XSetInputFocus(dpy, sel->win, RevertToPointerRoot, CurrentTime);
642 focusnext(const void *arg) {
647 for(c = sel->next; c && c->isbanned; c = c->next);
649 for(c = clients; c && c->isbanned; c = c->next);
657 focusprev(const void *arg) {
662 for(c = sel->prev; c && c->isbanned; c = c->prev);
664 for(c = clients; c && c->next; c = c->next);
665 for(; c && c->isbanned; c = c->prev);
674 getclient(Window w) {
677 for(c = clients; c && c->win != w; c = c->next);
682 getcolor(const char *colstr) {
683 Colormap cmap = DefaultColormap(dpy, screen);
686 if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
687 eprint("error, cannot allocate color '%s'\n", colstr);
695 unsigned char *p = NULL;
699 status = XGetWindowProperty(dpy, w, wmatom[WMState], 0L, 2L, False, wmatom[WMState],
700 &real, &format, &n, &extra, (unsigned char **)&p);
701 if(status != Success)
710 gettextprop(Window w, Atom atom, char *text, uint size) {
715 if(!text || size == 0)
718 XGetTextProperty(dpy, w, &name, atom);
721 if(name.encoding == XA_STRING)
722 strncpy(text, (char *)name.value, size - 1);
724 if(XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success
726 strncpy(text, *list, size - 1);
727 XFreeStringList(list);
730 text[size - 1] = '\0';
736 grabbuttons(Client *c, Bool focused) {
738 uint buttons[] = { Button1, Button2, Button3 };
739 uint modifiers[] = { MODKEY, MODKEY|LockMask, MODKEY|numlockmask, MODKEY|numlockmask|LockMask };
741 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
743 for(i = 0; i < LENGTH(buttons); i++)
744 for(j = 0; j < LENGTH(modifiers); j++)
745 XGrabButton(dpy, buttons[i], modifiers[j], c->win, False,
746 BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
748 XGrabButton(dpy, AnyButton, AnyModifier, c->win, False,
749 BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
756 XModifierKeymap *modmap;
758 /* init modifier map */
759 modmap = XGetModifierMapping(dpy);
760 for(i = 0; i < 8; i++)
761 for(j = 0; j < modmap->max_keypermod; j++) {
762 if(modmap->modifiermap[i * modmap->max_keypermod + j] == XKeysymToKeycode(dpy, XK_Num_Lock))
763 numlockmask = (1 << i);
765 XFreeModifiermap(modmap);
767 XUngrabKey(dpy, AnyKey, AnyModifier, root);
768 for(i = 0; i < LENGTH(keys); i++) {
769 code = XKeysymToKeycode(dpy, keys[i].keysym);
770 XGrabKey(dpy, code, keys[i].mod, root, True,
771 GrabModeAsync, GrabModeAsync);
772 XGrabKey(dpy, code, keys[i].mod|LockMask, root, True,
773 GrabModeAsync, GrabModeAsync);
774 XGrabKey(dpy, code, keys[i].mod|numlockmask, root, True,
775 GrabModeAsync, GrabModeAsync);
776 XGrabKey(dpy, code, keys[i].mod|numlockmask|LockMask, root, True,
777 GrabModeAsync, GrabModeAsync);
782 initfont(const char *fontstr) {
783 char *def, **missing;
788 XFreeFontSet(dpy, dc.font.set);
789 dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
792 fprintf(stderr, "dwm: missing fontset: %s\n", missing[n]);
793 XFreeStringList(missing);
796 XFontSetExtents *font_extents;
797 XFontStruct **xfonts;
799 dc.font.ascent = dc.font.descent = 0;
800 font_extents = XExtentsOfFontSet(dc.font.set);
801 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
802 for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
803 dc.font.ascent = MAX(dc.font.ascent, (*xfonts)->ascent);
804 dc.font.descent = MAX(dc.font.descent,(*xfonts)->descent);
810 XFreeFont(dpy, dc.font.xfont);
811 dc.font.xfont = NULL;
812 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr))
813 && !(dc.font.xfont = XLoadQueryFont(dpy, "fixed")))
814 eprint("error, cannot load font: '%s'\n", fontstr);
815 dc.font.ascent = dc.font.xfont->ascent;
816 dc.font.descent = dc.font.xfont->descent;
818 dc.font.height = dc.font.ascent + dc.font.descent;
825 for(c = clients; c; c = c->next)
832 isprotodel(Client *c) {
837 if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
838 for(i = 0; !ret && i < n; i++)
839 if(protocols[i] == wmatom[WMDelete])
850 for(c = clients; c; c = c->next)
851 if(c->isurgent && c->tags & 1 << t)
857 keypress(XEvent *e) {
863 keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
864 for(i = 0; i < LENGTH(keys); i++)
865 if(keysym == keys[i].keysym
866 && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state)
868 keys[i].func(keys[i].arg);
872 killclient(const void *arg) {
877 if(isprotodel(sel)) {
878 ev.type = ClientMessage;
879 ev.xclient.window = sel->win;
880 ev.xclient.message_type = wmatom[WMProtocols];
881 ev.xclient.format = 32;
882 ev.xclient.data.l[0] = wmatom[WMDelete];
883 ev.xclient.data.l[1] = CurrentTime;
884 XSendEvent(dpy, sel->win, False, NoEventMask, &ev);
887 XKillClient(dpy, sel->win);
891 manage(Window w, XWindowAttributes *wa) {
892 Client *c, *t = NULL;
897 if(!(c = calloc(1, sizeof(Client))))
898 eprint("fatal: could not calloc() %u bytes\n", sizeof(Client));
906 c->oldbw = wa->border_width;
907 if(c->w == sw && c->h == sh) {
910 c->bw = wa->border_width;
913 if(c->x + c->w + 2 * c->bw > sx + sw)
914 c->x = sx + sw - c->w - 2 * c->bw;
915 if(c->y + c->h + 2 * c->bw > sy + sh)
916 c->y = sy + sh - c->h - 2 * c->bw;
917 c->x = MAX(c->x, sx);
918 c->y = MAX(c->y, by == 0 ? bh : sy);
922 wc.border_width = c->bw;
923 XConfigureWindow(dpy, w, CWBorderWidth, &wc);
924 XSetWindowBorder(dpy, w, dc.norm[ColBorder]);
925 configure(c); /* propagates border_width, if size doesn't change */
927 XSelectInput(dpy, w, EnterWindowMask|FocusChangeMask|PropertyChangeMask|StructureNotifyMask);
928 grabbuttons(c, False);
930 if((rettrans = XGetTransientForHint(dpy, w, &trans) == Success))
931 for(t = clients; t && t->win != trans; t = t->next);
937 c->isfloating = (rettrans == Success) || c->isfixed;
939 XRaiseWindow(dpy, c->win);
942 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h); /* some windows require this */
943 XMapWindow(dpy, c->win);
944 setclientstate(c, NormalState);
949 mappingnotify(XEvent *e) {
950 XMappingEvent *ev = &e->xmapping;
952 XRefreshKeyboardMapping(ev);
953 if(ev->request == MappingKeyboard)
958 maprequest(XEvent *e) {
959 static XWindowAttributes wa;
960 XMapRequestEvent *ev = &e->xmaprequest;
962 if(!XGetWindowAttributes(dpy, ev->window, &wa))
964 if(wa.override_redirect)
966 if(!getclient(ev->window))
967 manage(ev->window, &wa);
971 movemouse(Client *c) {
972 int x1, y1, ocx, ocy, di, nx, ny;
980 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
981 None, cursor[CurMove], CurrentTime) != GrabSuccess)
983 XQueryPointer(dpy, root, &dummy, &dummy, &x1, &y1, &di, &di, &dui);
985 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
988 XUngrabPointer(dpy, CurrentTime);
990 case ConfigureRequest:
993 handler[ev.type](&ev);
997 nx = ocx + (ev.xmotion.x - x1);
998 ny = ocy + (ev.xmotion.y - y1);
999 if(snap && nx >= wx && nx <= wx + ww
1000 && ny >= wy && ny <= wy + wh) {
1001 if(abs(wx - nx) < snap)
1003 else if(abs((wx + ww) - (nx + c->w + 2 * c->bw)) < snap)
1004 nx = wx + ww - c->w - 2 * c->bw;
1005 if(abs(wy - ny) < snap)
1007 else if(abs((wy + wh) - (ny + c->h + 2 * c->bw)) < snap)
1008 ny = wy + wh - c->h - 2 * c->bw;
1009 if(!c->isfloating && lt->arrange && (abs(nx - c->x) > snap || abs(ny - c->y) > snap))
1010 togglefloating(NULL);
1012 if(!lt->arrange || c->isfloating)
1013 resize(c, nx, ny, c->w, c->h, False);
1020 nexttiled(Client *c) {
1021 for(; c && (c->isfloating || c->isbanned); c = c->next);
1026 propertynotify(XEvent *e) {
1029 XPropertyEvent *ev = &e->xproperty;
1031 if(ev->state == PropertyDelete)
1032 return; /* ignore */
1033 if((c = getclient(ev->window))) {
1036 case XA_WM_TRANSIENT_FOR:
1037 XGetTransientForHint(dpy, c->win, &trans);
1038 if(!c->isfloating && (c->isfloating = (getclient(trans) != NULL)))
1041 case XA_WM_NORMAL_HINTS:
1049 if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
1058 quit(const void *arg) {
1059 readin = running = False;
1063 resize(Client *c, int x, int y, int w, int h, Bool sizehints) {
1067 /* set minimum possible */
1071 /* temporarily remove base dimensions */
1075 /* adjust for aspect limits */
1076 if(c->minax != c->maxax && c->minay != c->maxay
1077 && c->minax > 0 && c->maxax > 0 && c->minay > 0 && c->maxay > 0) {
1078 if(w * c->maxay > h * c->maxax)
1079 w = h * c->maxax / c->maxay;
1080 else if(w * c->minay < h * c->minax)
1081 h = w * c->minay / c->minax;
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(Client *c) {
1140 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1141 None, cursor[CurResize], CurrentTime) != GrabSuccess)
1143 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->bw - 1, c->h + c->bw - 1);
1145 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask , &ev);
1148 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0,
1149 c->w + c->bw - 1, c->h + c->bw - 1);
1150 XUngrabPointer(dpy, CurrentTime);
1151 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1153 case ConfigureRequest:
1156 handler[ev.type](&ev);
1160 nw = MAX(ev.xmotion.x - ocx - 2 * c->bw + 1, 1);
1161 nh = MAX(ev.xmotion.y - ocy - 2 * c->bw + 1, 1);
1163 if(snap && nw >= wx && nw <= wx + ww
1164 && nh >= wy && nh <= wy + wh) {
1165 if(!c->isfloating && lt->arrange
1166 && (abs(nw - c->w) > snap || abs(nh - c->h) > snap))
1167 togglefloating(NULL);
1169 if(!lt->arrange || c->isfloating)
1170 resize(c, c->x, c->y, nw, nh, True);
1185 if(ismax || sel->isfloating || !lt->arrange)
1186 XRaiseWindow(dpy, sel->win);
1187 if(!ismax && lt->arrange) {
1188 wc.stack_mode = Below;
1189 wc.sibling = barwin;
1190 for(c = stack; c; c = c->snext)
1191 if(!c->isfloating && !c->isbanned) {
1192 XConfigureWindow(dpy, c->win, CWSibling|CWStackMode, &wc);
1193 wc.sibling = c->win;
1197 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1203 char sbuf[sizeof stext];
1209 /* main event loop, also reads status text from stdin */
1211 xfd = ConnectionNumber(dpy);
1214 len = sizeof stext - 1;
1215 sbuf[len] = stext[len] = '\0'; /* 0-terminator is never touched */
1219 FD_SET(STDIN_FILENO, &rd);
1221 if(select(xfd + 1, &rd, NULL, NULL, NULL) == -1) {
1224 eprint("select failed\n");
1226 if(FD_ISSET(STDIN_FILENO, &rd)) {
1227 switch((r = read(STDIN_FILENO, sbuf + offset, len - offset))) {
1229 strncpy(stext, strerror(errno), len);
1233 strncpy(stext, "EOF", 4);
1237 for(p = sbuf + offset; r > 0; p++, r--, offset++)
1238 if(*p == '\n' || *p == '\0') {
1240 strncpy(stext, sbuf, len);
1241 p += r - 1; /* p is sbuf + offset + r - 1 */
1242 for(r = 0; *(p - r) && *(p - r) != '\n'; r++);
1245 memmove(sbuf, p - r + 1, r);
1252 while(XPending(dpy)) {
1253 XNextEvent(dpy, &ev);
1254 if(handler[ev.type])
1255 (handler[ev.type])(&ev); /* call handler */
1263 Window *wins, d1, d2;
1264 XWindowAttributes wa;
1267 if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1268 for(i = 0; i < num; i++) {
1269 if(!XGetWindowAttributes(dpy, wins[i], &wa)
1270 || wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1272 if(wa.map_state == IsViewable || getstate(wins[i]) == IconicState)
1273 manage(wins[i], &wa);
1275 for(i = 0; i < num; i++) { /* now the transients */
1276 if(!XGetWindowAttributes(dpy, wins[i], &wa))
1278 if(XGetTransientForHint(dpy, wins[i], &d1)
1279 && (wa.map_state == IsViewable || getstate(wins[i]) == IconicState))
1280 manage(wins[i], &wa);
1288 setclientstate(Client *c, long state) {
1289 long data[] = {state, None};
1291 XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1292 PropModeReplace, (unsigned char *)data, 2);
1295 /* arg > 1.0 will set mfact absolutly */
1297 setmfact(const void *arg) {
1298 double d = *((double*) arg);
1300 if(!d || !lt->arrange)
1302 d = d < 1.0 ? d + mfact : d - 1.0;
1303 if(d < 0.1 || d > 0.9)
1312 XSetWindowAttributes wa;
1315 screen = DefaultScreen(dpy);
1316 root = RootWindow(dpy, screen);
1320 sw = DisplayWidth(dpy, screen);
1321 sh = DisplayHeight(dpy, screen);
1322 bh = dc.font.height + 2;
1326 wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1327 wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1328 wmatom[WMName] = XInternAtom(dpy, "WM_NAME", False);
1329 wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1330 netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1331 netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1334 wa.cursor = cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1335 cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1336 cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1338 /* init appearance */
1339 dc.norm[ColBorder] = getcolor(NORMBORDERCOLOR);
1340 dc.norm[ColBG] = getcolor(NORMBGCOLOR);
1341 dc.norm[ColFG] = getcolor(NORMFGCOLOR);
1342 dc.sel[ColBorder] = getcolor(SELBORDERCOLOR);
1343 dc.sel[ColBG] = getcolor(SELBGCOLOR);
1344 dc.sel[ColFG] = getcolor(SELFGCOLOR);
1347 dc.drawable = XCreatePixmap(dpy, root, DisplayWidth(dpy, screen), bh, DefaultDepth(dpy, screen));
1348 dc.gc = XCreateGC(dpy, root, 0, 0);
1349 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
1351 XSetFont(dpy, dc.gc, dc.font.xfont->fid);
1354 for(blw = i = 0; LENGTH(layouts) > 1 && i < LENGTH(layouts); i++) {
1355 w = TEXTW(layouts[i].symbol);
1359 wa.override_redirect = 1;
1360 wa.background_pixmap = ParentRelative;
1361 wa.event_mask = ButtonPressMask|ExposureMask;
1363 barwin = XCreateWindow(dpy, root, wx, by, ww, bh, 0, DefaultDepth(dpy, screen),
1364 CopyFromParent, DefaultVisual(dpy, screen),
1365 CWOverrideRedirect|CWBackPixmap|CWEventMask, &wa);
1366 XDefineCursor(dpy, barwin, cursor[CurNormal]);
1367 XMapRaised(dpy, barwin);
1368 strcpy(stext, "dwm-"VERSION);
1371 /* EWMH support per view */
1372 XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1373 PropModeReplace, (unsigned char *) netatom, NetLast);
1375 /* select for events */
1376 wa.event_mask = SubstructureRedirectMask|SubstructureNotifyMask
1377 |EnterWindowMask|LeaveWindowMask|StructureNotifyMask;
1378 XChangeWindowAttributes(dpy, root, CWEventMask|CWCursor, &wa);
1379 XSelectInput(dpy, root, wa.event_mask);
1387 spawn(const void *arg) {
1388 static char *shell = NULL;
1390 if(!shell && !(shell = getenv("SHELL")))
1392 /* The double-fork construct avoids zombie processes and keeps the code
1393 * clean from stupid signal handlers. */
1397 close(ConnectionNumber(dpy));
1399 execl(shell, shell, "-c", (char *)arg, (char *)NULL);
1400 fprintf(stderr, "dwm: execl '%s -c %s'", shell, (char *)arg);
1409 tag(const void *arg) {
1410 if(sel && *(int *)arg & TAGMASK) {
1411 sel->tags = *(int *)arg & 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 void *arg) {
1470 togglefloating(const void *arg) {
1473 sel->isfloating = !sel->isfloating || sel->isfixed;
1475 resize(sel, sel->x, sel->y, sel->w, sel->h, True);
1480 togglelayout(const void *arg) {
1484 if(++lt == &layouts[LENGTH(layouts)])
1488 for(i = 0; i < LENGTH(layouts); i++)
1489 if(!strcmp((char *)arg, layouts[i].symbol))
1491 if(i == LENGTH(layouts))
1502 togglemax(const void *arg) {
1508 toggletag(const void *arg) {
1509 if(sel && (sel->tags ^ ((*(int *)arg) & TAGMASK))) {
1510 sel->tags ^= (*(int *)arg) & TAGMASK;
1516 toggleview(const void *arg) {
1517 if((tagset[seltags] ^ ((*(int *)arg) & TAGMASK))) {
1518 tagset[seltags] ^= (*(int *)arg) & TAGMASK;
1524 unmanage(Client *c) {
1527 wc.border_width = c->oldbw;
1528 /* The server grab construct avoids race conditions. */
1530 XSetErrorHandler(xerrordummy);
1531 XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
1536 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1537 setclientstate(c, WithdrawnState);
1540 XSetErrorHandler(xerror);
1546 unmapnotify(XEvent *e) {
1548 XUnmapEvent *ev = &e->xunmap;
1550 if((c = getclient(ev->window)))
1556 if(dc.drawable != 0)
1557 XFreePixmap(dpy, dc.drawable);
1558 dc.drawable = XCreatePixmap(dpy, root, ww, bh, DefaultDepth(dpy, screen));
1559 XMoveResizeWindow(dpy, barwin, wx, by, ww, bh);
1566 XineramaScreenInfo *info = NULL;
1568 /* window area geometry */
1569 if(XineramaIsActive(dpy)) {
1570 info = XineramaQueryScreens(dpy, &i);
1572 wy = showbar && topbar ? info[0].y_org + bh : info[0].y_org;
1574 wh = showbar ? info[0].height - bh : info[0].height;
1581 wy = showbar && topbar ? sy + bh : sy;
1583 wh = showbar ? sh - bh : sh;
1587 by = showbar ? (topbar ? wy - bh : wy + wh) : -bh;
1591 updatesizehints(Client *c) {
1595 XGetWMNormalHints(dpy, c->win, &size, &msize);
1596 if(size.flags & PBaseSize) {
1597 c->basew = size.base_width;
1598 c->baseh = size.base_height;
1600 else if(size.flags & PMinSize) {
1601 c->basew = size.min_width;
1602 c->baseh = size.min_height;
1605 c->basew = c->baseh = 0;
1606 if(size.flags & PResizeInc) {
1607 c->incw = size.width_inc;
1608 c->inch = size.height_inc;
1611 c->incw = c->inch = 0;
1612 if(size.flags & PMaxSize) {
1613 c->maxw = size.max_width;
1614 c->maxh = size.max_height;
1617 c->maxw = c->maxh = 0;
1618 if(size.flags & PMinSize) {
1619 c->minw = size.min_width;
1620 c->minh = size.min_height;
1622 else if(size.flags & PBaseSize) {
1623 c->minw = size.base_width;
1624 c->minh = size.base_height;
1627 c->minw = c->minh = 0;
1628 if(size.flags & PAspect) {
1629 c->minax = size.min_aspect.x;
1630 c->maxax = size.max_aspect.x;
1631 c->minay = size.min_aspect.y;
1632 c->maxay = size.max_aspect.y;
1635 c->minax = c->maxax = c->minay = c->maxay = 0;
1636 c->isfixed = (c->maxw && c->minw && c->maxh && c->minh
1637 && c->maxw == c->minw && c->maxh == c->minh);
1641 updatetitle(Client *c) {
1642 if(!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
1643 gettextprop(c->win, wmatom[WMName], c->name, sizeof c->name);
1647 updatewmhints(Client *c) {
1650 if((wmh = XGetWMHints(dpy, c->win))) {
1652 sel->isurgent = False;
1654 c->isurgent = (wmh->flags & XUrgencyHint) ? True : False;
1660 view(const void *arg) {
1661 seltags ^= 1; /* toggle sel tagset */
1662 if(arg && (*(int *)arg & TAGMASK))
1663 tagset[seltags] = *(int *)arg & TAGMASK;
1667 /* There's no way to check accesses to destroyed windows, thus those cases are
1668 * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
1669 * default error handler, which may call exit. */
1671 xerror(Display *dpy, XErrorEvent *ee) {
1672 if(ee->error_code == BadWindow
1673 || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1674 || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1675 || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1676 || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1677 || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1678 || (ee->request_code == X_GrabButton && ee->error_code == BadAccess)
1679 || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1680 || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1682 fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1683 ee->request_code, ee->error_code);
1684 return xerrorxlib(dpy, ee); /* may call exit */
1688 xerrordummy(Display *dpy, XErrorEvent *ee) {
1692 /* Startup Error handler to check if another window manager
1693 * is already running. */
1695 xerrorstart(Display *dpy, XErrorEvent *ee) {
1701 zoom(const void *arg) {
1704 if(ismax || !lt->arrange || (sel && sel->isfloating))
1706 if(c == nexttiled(clients))
1707 if(!c || !(c = nexttiled(c->next)))
1716 main(int argc, char *argv[]) {
1717 if(argc == 2 && !strcmp("-v", argv[1]))
1718 eprint("dwm-"VERSION", © 2006-2008 dwm engineers, see LICENSE for details\n");
1720 eprint("usage: dwm [-v]\n");
1722 setlocale(LC_CTYPE, "");
1723 if(!(dpy = XOpenDisplay(0)))
1724 eprint("dwm: cannot open display\n");