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,
740 MODKEY|numlockmask|LockMask} ;
742 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
744 for(i = 0; i < LENGTH(buttons); i++)
745 for(j = 0; j < LENGTH(modifiers); j++)
746 XGrabButton(dpy, buttons[i], modifiers[j], c->win, False,
747 BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
749 XGrabButton(dpy, AnyButton, AnyModifier, c->win, False,
750 BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
757 XModifierKeymap *modmap;
759 /* init modifier map */
760 modmap = XGetModifierMapping(dpy);
761 for(i = 0; i < 8; i++)
762 for(j = 0; j < modmap->max_keypermod; j++) {
763 if(modmap->modifiermap[i * modmap->max_keypermod + j] == XKeysymToKeycode(dpy, XK_Num_Lock))
764 numlockmask = (1 << i);
766 XFreeModifiermap(modmap);
768 XUngrabKey(dpy, AnyKey, AnyModifier, root);
769 for(i = 0; i < LENGTH(keys); i++) {
770 code = XKeysymToKeycode(dpy, keys[i].keysym);
771 XGrabKey(dpy, code, keys[i].mod, root, True,
772 GrabModeAsync, GrabModeAsync);
773 XGrabKey(dpy, code, keys[i].mod|LockMask, root, True,
774 GrabModeAsync, GrabModeAsync);
775 XGrabKey(dpy, code, keys[i].mod|numlockmask, root, True,
776 GrabModeAsync, GrabModeAsync);
777 XGrabKey(dpy, code, keys[i].mod|numlockmask|LockMask, root, True,
778 GrabModeAsync, GrabModeAsync);
783 initfont(const char *fontstr) {
784 char *def, **missing;
789 XFreeFontSet(dpy, dc.font.set);
790 dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
793 fprintf(stderr, "dwm: missing fontset: %s\n", missing[n]);
794 XFreeStringList(missing);
797 XFontSetExtents *font_extents;
798 XFontStruct **xfonts;
800 dc.font.ascent = dc.font.descent = 0;
801 font_extents = XExtentsOfFontSet(dc.font.set);
802 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
803 for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
804 dc.font.ascent = MAX(dc.font.ascent, (*xfonts)->ascent);
805 dc.font.descent = MAX(dc.font.descent,(*xfonts)->descent);
811 XFreeFont(dpy, dc.font.xfont);
812 dc.font.xfont = NULL;
813 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr))
814 && !(dc.font.xfont = XLoadQueryFont(dpy, "fixed")))
815 eprint("error, cannot load font: '%s'\n", fontstr);
816 dc.font.ascent = dc.font.xfont->ascent;
817 dc.font.descent = dc.font.xfont->descent;
819 dc.font.height = dc.font.ascent + dc.font.descent;
826 for(c = clients; c; c = c->next)
833 isprotodel(Client *c) {
838 if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
839 for(i = 0; !ret && i < n; i++)
840 if(protocols[i] == wmatom[WMDelete])
851 for(c = clients; c; c = c->next)
852 if(c->isurgent && c->tags & 1 << t)
858 keypress(XEvent *e) {
864 keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
865 for(i = 0; i < LENGTH(keys); i++)
866 if(keysym == keys[i].keysym
867 && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state)
869 keys[i].func(keys[i].arg);
873 killclient(const void *arg) {
878 if(isprotodel(sel)) {
879 ev.type = ClientMessage;
880 ev.xclient.window = sel->win;
881 ev.xclient.message_type = wmatom[WMProtocols];
882 ev.xclient.format = 32;
883 ev.xclient.data.l[0] = wmatom[WMDelete];
884 ev.xclient.data.l[1] = CurrentTime;
885 XSendEvent(dpy, sel->win, False, NoEventMask, &ev);
888 XKillClient(dpy, sel->win);
892 manage(Window w, XWindowAttributes *wa) {
893 Client *c, *t = NULL;
898 if(!(c = calloc(1, sizeof(Client))))
899 eprint("fatal: could not calloc() %u bytes\n", sizeof(Client));
907 c->oldbw = wa->border_width;
908 if(c->w == sw && c->h == sh) {
911 c->bw = wa->border_width;
914 if(c->x + c->w + 2 * c->bw > sx + sw)
915 c->x = sx + sw - c->w - 2 * c->bw;
916 if(c->y + c->h + 2 * c->bw > sy + sh)
917 c->y = sy + sh - c->h - 2 * c->bw;
918 c->x = MAX(c->x, sx);
919 c->y = MAX(c->y, by == 0 ? bh : sy);
923 wc.border_width = c->bw;
924 XConfigureWindow(dpy, w, CWBorderWidth, &wc);
925 XSetWindowBorder(dpy, w, dc.norm[ColBorder]);
926 configure(c); /* propagates border_width, if size doesn't change */
928 XSelectInput(dpy, w, EnterWindowMask|FocusChangeMask|PropertyChangeMask|StructureNotifyMask);
929 grabbuttons(c, False);
931 if((rettrans = XGetTransientForHint(dpy, w, &trans) == Success))
932 for(t = clients; t && t->win != trans; t = t->next);
938 c->isfloating = (rettrans == Success) || c->isfixed;
940 XRaiseWindow(dpy, c->win);
943 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h); /* some windows require this */
944 XMapWindow(dpy, c->win);
945 setclientstate(c, NormalState);
950 mappingnotify(XEvent *e) {
951 XMappingEvent *ev = &e->xmapping;
953 XRefreshKeyboardMapping(ev);
954 if(ev->request == MappingKeyboard)
959 maprequest(XEvent *e) {
960 static XWindowAttributes wa;
961 XMapRequestEvent *ev = &e->xmaprequest;
963 if(!XGetWindowAttributes(dpy, ev->window, &wa))
965 if(wa.override_redirect)
967 if(!getclient(ev->window))
968 manage(ev->window, &wa);
972 movemouse(Client *c) {
973 int x1, y1, ocx, ocy, di, nx, ny;
981 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
982 None, cursor[CurMove], CurrentTime) != GrabSuccess)
984 XQueryPointer(dpy, root, &dummy, &dummy, &x1, &y1, &di, &di, &dui);
986 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
989 XUngrabPointer(dpy, CurrentTime);
991 case ConfigureRequest:
994 handler[ev.type](&ev);
998 nx = ocx + (ev.xmotion.x - x1);
999 ny = ocy + (ev.xmotion.y - y1);
1000 if(snap && nx >= wx && nx <= wx + ww
1001 && ny >= wy && ny <= wy + wh) {
1002 if(abs(wx - nx) < snap)
1004 else if(abs((wx + ww) - (nx + c->w + 2 * c->bw)) < snap)
1005 nx = wx + ww - c->w - 2 * c->bw;
1006 if(abs(wy - ny) < snap)
1008 else if(abs((wy + wh) - (ny + c->h + 2 * c->bw)) < snap)
1009 ny = wy + wh - c->h - 2 * c->bw;
1010 if(!c->isfloating && lt->arrange && (abs(nx - c->x) > snap || abs(ny - c->y) > snap))
1011 togglefloating(NULL);
1013 if(!lt->arrange || c->isfloating)
1014 resize(c, nx, ny, c->w, c->h, False);
1021 nexttiled(Client *c) {
1022 for(; c && (c->isfloating || c->isbanned); c = c->next);
1027 propertynotify(XEvent *e) {
1030 XPropertyEvent *ev = &e->xproperty;
1032 if(ev->state == PropertyDelete)
1033 return; /* ignore */
1034 if((c = getclient(ev->window))) {
1037 case XA_WM_TRANSIENT_FOR:
1038 XGetTransientForHint(dpy, c->win, &trans);
1039 if(!c->isfloating && (c->isfloating = (getclient(trans) != NULL)))
1042 case XA_WM_NORMAL_HINTS:
1050 if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
1059 quit(const void *arg) {
1060 readin = running = False;
1064 resize(Client *c, int x, int y, int w, int h, Bool sizehints) {
1068 /* set minimum possible */
1072 /* temporarily remove base dimensions */
1076 /* adjust for aspect limits */
1077 if(c->minax != c->maxax && c->minay != c->maxay
1078 && c->minax > 0 && c->maxax > 0 && c->minay > 0 && c->maxay > 0) {
1079 if(w * c->maxay > h * c->maxax)
1080 w = h * c->maxax / c->maxay;
1081 else if(w * c->minay < h * c->minax)
1082 h = w * c->minay / c->minax;
1085 /* adjust for increment value */
1091 /* restore base dimensions */
1095 w = MAX(w, c->minw);
1096 h = MAX(h, c->minh);
1099 w = MIN(w, c->maxw);
1102 h = MIN(h, c->maxh);
1104 if(w <= 0 || h <= 0)
1107 x = sw - w - 2 * c->bw;
1109 y = sh - h - 2 * c->bw;
1110 if(x + w + 2 * c->bw < sx)
1112 if(y + h + 2 * c->bw < sy)
1118 if(c->x != x || c->y != y || c->w != w || c->h != h || c->ismoved) {
1122 c->w = wc.width = w;
1123 c->h = wc.height = h;
1124 wc.border_width = c->bw;
1125 XConfigureWindow(dpy, c->win,
1126 CWX|CWY|CWWidth|CWHeight|CWBorderWidth, &wc);
1133 resizemouse(Client *c) {
1141 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1142 None, cursor[CurResize], CurrentTime) != GrabSuccess)
1144 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->bw - 1, c->h + c->bw - 1);
1146 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask , &ev);
1149 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0,
1150 c->w + c->bw - 1, c->h + c->bw - 1);
1151 XUngrabPointer(dpy, CurrentTime);
1152 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1154 case ConfigureRequest:
1157 handler[ev.type](&ev);
1161 nw = MAX(ev.xmotion.x - ocx - 2 * c->bw + 1, 1);
1162 nh = MAX(ev.xmotion.y - ocy - 2 * c->bw + 1, 1);
1164 if(snap && nw >= wx && nw <= wx + ww
1165 && nh >= wy && nh <= wy + wh) {
1166 if(!c->isfloating && lt->arrange
1167 && (abs(nw - c->w) > snap || abs(nh - c->h) > snap))
1168 togglefloating(NULL);
1170 if(!lt->arrange || c->isfloating)
1171 resize(c, c->x, c->y, nw, nh, True);
1186 if(ismax || sel->isfloating || !lt->arrange)
1187 XRaiseWindow(dpy, sel->win);
1188 if(!ismax && lt->arrange) {
1189 wc.stack_mode = Below;
1190 wc.sibling = barwin;
1191 for(c = stack; c; c = c->snext)
1192 if(!c->isfloating && !c->isbanned) {
1193 XConfigureWindow(dpy, c->win, CWSibling|CWStackMode, &wc);
1194 wc.sibling = c->win;
1198 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1204 char sbuf[sizeof stext];
1210 /* main event loop, also reads status text from stdin */
1212 xfd = ConnectionNumber(dpy);
1215 len = sizeof stext - 1;
1216 sbuf[len] = stext[len] = '\0'; /* 0-terminator is never touched */
1220 FD_SET(STDIN_FILENO, &rd);
1222 if(select(xfd + 1, &rd, NULL, NULL, NULL) == -1) {
1225 eprint("select failed\n");
1227 if(FD_ISSET(STDIN_FILENO, &rd)) {
1228 switch((r = read(STDIN_FILENO, sbuf + offset, len - offset))) {
1230 strncpy(stext, strerror(errno), len);
1234 strncpy(stext, "EOF", 4);
1238 for(p = sbuf + offset; r > 0; p++, r--, offset++)
1239 if(*p == '\n' || *p == '\0') {
1241 strncpy(stext, sbuf, len);
1242 p += r - 1; /* p is sbuf + offset + r - 1 */
1243 for(r = 0; *(p - r) && *(p - r) != '\n'; r++);
1246 memmove(sbuf, p - r + 1, r);
1253 while(XPending(dpy)) {
1254 XNextEvent(dpy, &ev);
1255 if(handler[ev.type])
1256 (handler[ev.type])(&ev); /* call handler */
1264 Window *wins, d1, d2;
1265 XWindowAttributes wa;
1268 if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1269 for(i = 0; i < num; i++) {
1270 if(!XGetWindowAttributes(dpy, wins[i], &wa)
1271 || wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1273 if(wa.map_state == IsViewable || getstate(wins[i]) == IconicState)
1274 manage(wins[i], &wa);
1276 for(i = 0; i < num; i++) { /* now the transients */
1277 if(!XGetWindowAttributes(dpy, wins[i], &wa))
1279 if(XGetTransientForHint(dpy, wins[i], &d1)
1280 && (wa.map_state == IsViewable || getstate(wins[i]) == IconicState))
1281 manage(wins[i], &wa);
1289 setclientstate(Client *c, long state) {
1290 long data[] = {state, None};
1292 XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1293 PropModeReplace, (unsigned char *)data, 2);
1296 /* arg > 1.0 will set mfact absolutly */
1298 setmfact(const void *arg) {
1299 double d = *((double*) arg);
1301 if(!d || !lt->arrange)
1303 d = d < 1.0 ? d + mfact : d - 1.0;
1304 if(d < 0.1 || d > 0.9)
1313 XSetWindowAttributes wa;
1316 screen = DefaultScreen(dpy);
1317 root = RootWindow(dpy, screen);
1321 sw = DisplayWidth(dpy, screen);
1322 sh = DisplayHeight(dpy, screen);
1323 bh = dc.font.height + 2;
1327 wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1328 wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1329 wmatom[WMName] = XInternAtom(dpy, "WM_NAME", False);
1330 wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1331 netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1332 netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1335 wa.cursor = cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1336 cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1337 cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1339 /* init appearance */
1340 dc.norm[ColBorder] = getcolor(NORMBORDERCOLOR);
1341 dc.norm[ColBG] = getcolor(NORMBGCOLOR);
1342 dc.norm[ColFG] = getcolor(NORMFGCOLOR);
1343 dc.sel[ColBorder] = getcolor(SELBORDERCOLOR);
1344 dc.sel[ColBG] = getcolor(SELBGCOLOR);
1345 dc.sel[ColFG] = getcolor(SELFGCOLOR);
1348 dc.drawable = XCreatePixmap(dpy, root, DisplayWidth(dpy, screen), bh, DefaultDepth(dpy, screen));
1349 dc.gc = XCreateGC(dpy, root, 0, 0);
1350 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
1352 XSetFont(dpy, dc.gc, dc.font.xfont->fid);
1355 for(blw = i = 0; LENGTH(layouts) > 1 && i < LENGTH(layouts); i++) {
1356 w = TEXTW(layouts[i].symbol);
1360 wa.override_redirect = 1;
1361 wa.background_pixmap = ParentRelative;
1362 wa.event_mask = ButtonPressMask|ExposureMask;
1364 barwin = XCreateWindow(dpy, root, wx, by, ww, bh, 0, DefaultDepth(dpy, screen),
1365 CopyFromParent, DefaultVisual(dpy, screen),
1366 CWOverrideRedirect|CWBackPixmap|CWEventMask, &wa);
1367 XDefineCursor(dpy, barwin, cursor[CurNormal]);
1368 XMapRaised(dpy, barwin);
1369 strcpy(stext, "dwm-"VERSION);
1372 /* EWMH support per view */
1373 XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1374 PropModeReplace, (unsigned char *) netatom, NetLast);
1376 /* select for events */
1377 wa.event_mask = SubstructureRedirectMask|SubstructureNotifyMask
1378 |EnterWindowMask|LeaveWindowMask|StructureNotifyMask;
1379 XChangeWindowAttributes(dpy, root, CWEventMask|CWCursor, &wa);
1380 XSelectInput(dpy, root, wa.event_mask);
1388 spawn(const void *arg) {
1389 static char *shell = NULL;
1391 if(!shell && !(shell = getenv("SHELL")))
1393 /* The double-fork construct avoids zombie processes and keeps the code
1394 * clean from stupid signal handlers. */
1398 close(ConnectionNumber(dpy));
1400 execl(shell, shell, "-c", (char *)arg, (char *)NULL);
1401 fprintf(stderr, "dwm: execl '%s -c %s'", shell, (char *)arg);
1410 tag(const void *arg) {
1411 if(sel && *(int *)arg & TAGMASK) {
1412 sel->tags = *(int *)arg & 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 void *arg) {
1471 togglefloating(const void *arg) {
1474 sel->isfloating = !sel->isfloating || sel->isfixed;
1476 resize(sel, sel->x, sel->y, sel->w, sel->h, True);
1481 togglelayout(const void *arg) {
1485 if(++lt == &layouts[LENGTH(layouts)])
1489 for(i = 0; i < LENGTH(layouts); i++)
1490 if(!strcmp((char *)arg, layouts[i].symbol))
1492 if(i == LENGTH(layouts))
1503 togglemax(const void *arg) {
1509 toggletag(const void *arg) {
1510 if(sel && (sel->tags ^ ((*(int *)arg) & TAGMASK))) {
1511 sel->tags ^= (*(int *)arg) & TAGMASK;
1517 toggleview(const void *arg) {
1518 if((tagset[seltags] ^ ((*(int *)arg) & TAGMASK))) {
1519 tagset[seltags] ^= (*(int *)arg) & TAGMASK;
1525 unmanage(Client *c) {
1528 wc.border_width = c->oldbw;
1529 /* The server grab construct avoids race conditions. */
1531 XSetErrorHandler(xerrordummy);
1532 XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
1537 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1538 setclientstate(c, WithdrawnState);
1541 XSetErrorHandler(xerror);
1547 unmapnotify(XEvent *e) {
1549 XUnmapEvent *ev = &e->xunmap;
1551 if((c = getclient(ev->window)))
1557 if(dc.drawable != 0)
1558 XFreePixmap(dpy, dc.drawable);
1559 dc.drawable = XCreatePixmap(dpy, root, ww, bh, DefaultDepth(dpy, screen));
1560 XMoveResizeWindow(dpy, barwin, wx, by, ww, bh);
1567 XineramaScreenInfo *info = NULL;
1569 /* window area geometry */
1570 if(XineramaIsActive(dpy)) {
1571 info = XineramaQueryScreens(dpy, &i);
1573 wy = showbar && topbar ? info[0].y_org + bh : info[0].y_org;
1575 wh = showbar ? info[0].height - bh : info[0].height;
1582 wy = showbar && topbar ? sy + bh : sy;
1584 wh = showbar ? sh - bh : sh;
1588 by = showbar ? (topbar ? wy - bh : wy + wh) : -bh;
1592 updatesizehints(Client *c) {
1596 XGetWMNormalHints(dpy, c->win, &size, &msize);
1597 if(size.flags & PBaseSize) {
1598 c->basew = size.base_width;
1599 c->baseh = size.base_height;
1601 else if(size.flags & PMinSize) {
1602 c->basew = size.min_width;
1603 c->baseh = size.min_height;
1606 c->basew = c->baseh = 0;
1607 if(size.flags & PResizeInc) {
1608 c->incw = size.width_inc;
1609 c->inch = size.height_inc;
1612 c->incw = c->inch = 0;
1613 if(size.flags & PMaxSize) {
1614 c->maxw = size.max_width;
1615 c->maxh = size.max_height;
1618 c->maxw = c->maxh = 0;
1619 if(size.flags & PMinSize) {
1620 c->minw = size.min_width;
1621 c->minh = size.min_height;
1623 else if(size.flags & PBaseSize) {
1624 c->minw = size.base_width;
1625 c->minh = size.base_height;
1628 c->minw = c->minh = 0;
1629 if(size.flags & PAspect) {
1630 c->minax = size.min_aspect.x;
1631 c->maxax = size.max_aspect.x;
1632 c->minay = size.min_aspect.y;
1633 c->maxay = size.max_aspect.y;
1636 c->minax = c->maxax = c->minay = c->maxay = 0;
1637 c->isfixed = (c->maxw && c->minw && c->maxh && c->minh
1638 && c->maxw == c->minw && c->maxh == c->minh);
1642 updatetitle(Client *c) {
1643 if(!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
1644 gettextprop(c->win, wmatom[WMName], c->name, sizeof c->name);
1648 updatewmhints(Client *c) {
1651 if((wmh = XGetWMHints(dpy, c->win))) {
1653 sel->isurgent = False;
1655 c->isurgent = (wmh->flags & XUrgencyHint) ? True : False;
1661 view(const void *arg) {
1662 seltags ^= 1; /* toggle sel tagset */
1663 if(arg && (*(int *)arg & TAGMASK))
1664 tagset[seltags] = *(int *)arg & TAGMASK;
1668 /* There's no way to check accesses to destroyed windows, thus those cases are
1669 * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
1670 * default error handler, which may call exit. */
1672 xerror(Display *dpy, XErrorEvent *ee) {
1673 if(ee->error_code == BadWindow
1674 || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1675 || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1676 || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1677 || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1678 || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1679 || (ee->request_code == X_GrabButton && ee->error_code == BadAccess)
1680 || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1681 || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1683 fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1684 ee->request_code, ee->error_code);
1685 return xerrorxlib(dpy, ee); /* may call exit */
1689 xerrordummy(Display *dpy, XErrorEvent *ee) {
1693 /* Startup Error handler to check if another window manager
1694 * is already running. */
1696 xerrorstart(Display *dpy, XErrorEvent *ee) {
1702 zoom(const void *arg) {
1705 if(ismax || !lt->arrange || (sel && sel->isfloating))
1707 if(c == nexttiled(clients))
1708 if(!c || !(c = nexttiled(c->next)))
1717 main(int argc, char *argv[]) {
1718 if(argc == 2 && !strcmp("-v", argv[1]))
1719 eprint("dwm-"VERSION", © 2006-2008 dwm engineers, see LICENSE for details\n");
1721 eprint("usage: dwm [-v]\n");
1723 setlocale(LC_CTYPE, "");
1724 if(!(dpy = XOpenDisplay(0)))
1725 eprint("dwm: cannot open display\n");