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 an array of Bools of the same size as the
20 * global tags array to indicate the tags of a client.
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)
56 #define VISIBLE(x) ((x)->tags & tagset[seltags])
59 enum { CurNormal, CurResize, CurMove, CurLast }; /* cursor */
60 enum { ColBorder, ColFG, ColBG, ColLast }; /* color */
61 enum { NetSupported, NetWMName, NetLast }; /* EWMH atoms */
62 enum { WMProtocols, WMDelete, WMName, WMState, WMLast };/* default atoms */
65 typedef unsigned int uint;
66 typedef unsigned long ulong;
67 typedef struct Client Client;
71 int basew, baseh, incw, inch, maxw, maxh, minw, minh;
72 int minax, maxax, minay, maxay;
75 Bool isbanned, isfixed, isfloating, ismax, isurgent;
96 } DC; /* draw context */
101 void (*func)(const void *arg);
107 void (*arrange)(void);
112 const char *instance;
118 /* function declarations */
119 void applyrules(Client *c);
121 void attach(Client *c);
122 void attachstack(Client *c);
123 void buttonpress(XEvent *e);
124 void checkotherwm(void);
126 void configure(Client *c);
127 void configurenotify(XEvent *e);
128 void configurerequest(XEvent *e);
129 void destroynotify(XEvent *e);
130 void detach(Client *c);
131 void detachstack(Client *c);
133 void drawsquare(Bool filled, Bool empty, Bool invert, ulong col[ColLast]);
134 void drawtext(const char *text, ulong col[ColLast], Bool invert);
135 void enternotify(XEvent *e);
136 void eprint(const char *errstr, ...);
137 void expose(XEvent *e);
138 void focus(Client *c);
139 void focusin(XEvent *e);
140 void focusnext(const void *arg);
141 void focusprev(const void *arg);
142 Client *getclient(Window w);
143 ulong getcolor(const char *colstr);
144 long getstate(Window w);
145 Bool gettextprop(Window w, Atom atom, char *text, uint size);
146 void grabbuttons(Client *c, Bool focused);
148 void initfont(const char *fontstr);
149 Bool isoccupied(uint t);
150 Bool isprotodel(Client *c);
151 Bool isurgent(uint t);
152 void keypress(XEvent *e);
153 void killclient(const void *arg);
154 void manage(Window w, XWindowAttributes *wa);
155 void mappingnotify(XEvent *e);
156 void maprequest(XEvent *e);
157 void movemouse(Client *c);
158 Client *nexttiled(Client *c);
159 void propertynotify(XEvent *e);
160 void quit(const void *arg);
161 void resize(Client *c, int x, int y, int w, int h, Bool sizehints);
162 void resizemouse(Client *c);
166 void setclientstate(Client *c, long state);
167 void setmfact(const void *arg);
169 void spawn(const void *arg);
170 void tag(const void *arg);
171 uint textnw(const char *text, uint len);
173 void tileresize(Client *c, int x, int y, int w, int h);
174 void togglebar(const void *arg);
175 void togglefloating(const void *arg);
176 void togglelayout(const void *arg);
177 void togglemax(const void *arg);
178 void toggletag(const void *arg);
179 void toggleview(const void *arg);
180 void unmanage(Client *c);
181 void unmapnotify(XEvent *e);
182 void updatebar(void);
183 void updategeom(void);
184 void updatesizehints(Client *c);
185 void updatetitle(Client *c);
186 void updatewmhints(Client *c);
187 void view(const void *arg);
188 void viewprevtag(const void *arg);
189 int xerror(Display *dpy, XErrorEvent *ee);
190 int xerrordummy(Display *dpy, XErrorEvent *ee);
191 int xerrorstart(Display *dpy, XErrorEvent *ee);
192 void zoom(const void *arg);
196 int screen, sx, sy, sw, sh;
197 int bx, by, bw, bh, blw, wx, wy, ww, wh;
199 int (*xerrorxlib)(Display *, XErrorEvent *);
200 uint numlockmask = 0;
201 void (*handler[LASTEvent]) (XEvent *) = {
202 [ButtonPress] = buttonpress,
203 [ConfigureRequest] = configurerequest,
204 [ConfigureNotify] = configurenotify,
205 [DestroyNotify] = destroynotify,
206 [EnterNotify] = enternotify,
209 [KeyPress] = keypress,
210 [MappingNotify] = mappingnotify,
211 [MapRequest] = maprequest,
212 [PropertyNotify] = propertynotify,
213 [UnmapNotify] = unmapnotify
215 Atom wmatom[WMLast], netatom[NetLast];
217 Bool otherwm, readin;
219 uint tagset[] = {1, 1}; /* after start, first tag is selected */
220 Client *clients = NULL;
222 Client *stack = NULL;
223 Cursor cursor[CurLast];
227 Layout *lt = layouts;
230 /* configuration, allows nested code to access above variables */
233 /* compile-time check if all tags fit into an uint bit array. */
234 struct NumTags { char limitexceeded[sizeof(uint) * 8 < LENGTH(tags) ? -1 : 1]; };
236 /* function implementations */
238 applyrules(Client *c) {
241 XClassHint ch = { 0 };
244 XGetClassHint(dpy, c->win, &ch);
245 for(i = 0; i < LENGTH(rules); i++) {
247 if((!r->title || strstr(c->name, r->title))
248 && (!r->class || (ch.res_class && strstr(ch.res_class, r->class)))
249 && (!r->instance || (ch.res_name && strstr(ch.res_name, r->instance)))) {
250 c->isfloating = r->isfloating;
251 c->tags |= r->tags & TAGMASK;
259 c->tags = tagset[seltags];
266 for(c = clients; c; c = c->next)
268 if(!lt->arrange || c->isfloating)
269 resize(c, c->x, c->y, c->w, c->h, True);
271 else if(!c->isbanned) {
272 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
277 if(lt->arrange && !domax)
291 attachstack(Client *c) {
297 buttonpress(XEvent *e) {
300 XButtonPressedEvent *ev = &e->xbutton;
302 if(ev->window == barwin) {
304 for(i = 0; i < LENGTH(tags); i++) {
308 if(ev->button == Button1) {
309 if(ev->state & MODKEY)
314 else if(ev->button == Button3) {
315 if(ev->state & MODKEY)
323 if(ev->x < x + blw) {
324 if(ev->button == Button1)
326 else if(ev->button == Button3)
330 else if((c = getclient(ev->window))) {
332 if(CLEANMASK(ev->state) != MODKEY || domax)
334 if(ev->button == Button1)
336 else if(ev->button == Button2)
337 togglefloating(NULL);
338 else if(ev->button == Button3 && !c->isfixed)
346 XSetErrorHandler(xerrorstart);
348 /* this causes an error if some other window manager is running */
349 XSelectInput(dpy, DefaultRootWindow(dpy), SubstructureRedirectMask);
352 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(c->isfixed || c->isfloating || !lt->arrange) {
421 if(ev->value_mask & CWX)
423 if(ev->value_mask & CWY)
425 if(ev->value_mask & CWWidth)
427 if(ev->value_mask & CWHeight)
429 if((c->x - sx + c->w) > sw && c->isfloating)
430 c->x = sx + (sw / 2 - c->w / 2); /* center in x direction */
431 if((c->y - sy + c->h) > sh && c->isfloating)
432 c->y = sy + (sh / 2 - c->h / 2); /* center in y direction */
433 if((ev->value_mask & (CWX|CWY))
434 && !(ev->value_mask & (CWWidth|CWHeight)))
437 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h);
445 wc.width = ev->width;
446 wc.height = ev->height;
447 wc.border_width = ev->border_width;
448 wc.sibling = ev->above;
449 wc.stack_mode = ev->detail;
450 XConfigureWindow(dpy, ev->window, ev->value_mask, &wc);
456 destroynotify(XEvent *e) {
458 XDestroyWindowEvent *ev = &e->xdestroywindow;
460 if((c = getclient(ev->window)))
467 c->prev->next = c->next;
469 c->next->prev = c->prev;
472 c->next = c->prev = NULL;
476 detachstack(Client *c) {
479 for(tc = &stack; *tc && *tc != c; tc = &(*tc)->snext);
489 for(c = stack; c && !VISIBLE(c); c = c->snext);
490 for(i = 0; i < LENGTH(tags); i++) {
491 dc.w = TEXTW(tags[i]);
492 if(tagset[seltags] & 1 << i) {
493 drawtext(tags[i], dc.sel, isurgent(i));
494 drawsquare(c && c->tags & 1 << i, isoccupied(i), isurgent(i), dc.sel);
497 drawtext(tags[i], dc.norm, isurgent(i));
498 drawsquare(c && c->tags & 1 << i, isoccupied(i), isurgent(i), dc.norm);
504 drawtext(lt->symbol, dc.norm, domax);
515 drawtext(stext, dc.norm, False);
516 if((dc.w = dc.x - x) > bh) {
519 drawtext(c->name, dc.sel, False);
520 drawsquare(False, c->isfloating, False, dc.sel);
523 drawtext(NULL, dc.norm, False);
525 XCopyArea(dpy, dc.drawable, barwin, dc.gc, 0, 0, bw, bh, 0, 0);
530 drawsquare(Bool filled, Bool empty, Bool invert, ulong col[ColLast]) {
533 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
535 gcv.foreground = col[invert ? ColBG : ColFG];
536 XChangeGC(dpy, dc.gc, GCForeground, &gcv);
537 x = (dc.font.ascent + dc.font.descent + 2) / 4;
541 r.width = r.height = x + 1;
542 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
545 r.width = r.height = x;
546 XDrawRectangles(dpy, dc.drawable, dc.gc, &r, 1);
551 drawtext(const char *text, ulong col[ColLast], Bool invert) {
554 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
557 XSetForeground(dpy, dc.gc, col[invert ? ColFG : ColBG]);
558 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
562 len = MIN(olen, sizeof buf);
563 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 && (w = textnw(buf, len)) > dc.w - h; len--);
580 XSetForeground(dpy, dc.gc, col[invert ? ColBG : ColFG]);
582 XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
584 XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
588 enternotify(XEvent *e) {
590 XCrossingEvent *ev = &e->xcrossing;
592 if((ev->mode != NotifyNormal || ev->detail == NotifyInferior) && ev->window != root)
594 if((c = getclient(ev->window)))
601 eprint(const char *errstr, ...) {
604 va_start(ap, errstr);
605 vfprintf(stderr, errstr, ap);
612 XExposeEvent *ev = &e->xexpose;
614 if(ev->count == 0 && (ev->window == barwin))
620 if(!c || (c && !VISIBLE(c)))
621 for(c = stack; c && !VISIBLE(c); c = c->snext);
622 if(sel && sel != c) {
623 grabbuttons(sel, False);
624 XSetWindowBorder(dpy, sel->win, dc.norm[ColBorder]);
629 grabbuttons(c, True);
634 XMoveResizeWindow(dpy, c->win, wx, wy, ww - 2 * c->bw, wh - 2 * c->bw);
637 XSetWindowBorder(dpy, c->win, dc.sel[ColBorder]);
638 XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
641 XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
646 focusin(XEvent *e) { /* there are some broken focus acquiring clients */
647 XFocusChangeEvent *ev = &e->xfocus;
649 if(sel && ev->window != sel->win)
650 XSetInputFocus(dpy, sel->win, RevertToPointerRoot, CurrentTime);
654 focusnext(const void *arg) {
659 for(c = sel->next; c && !VISIBLE(c); c = c->next);
661 for(c = clients; c && !VISIBLE(c); c = c->next);
669 focusprev(const void *arg) {
674 for(c = sel->prev; c && !VISIBLE(c); c = c->prev);
676 for(c = clients; c && c->next; c = c->next);
677 for(; c && !VISIBLE(c); c = c->prev);
686 getclient(Window w) {
689 for(c = clients; c && c->win != w; c = c->next);
694 getcolor(const char *colstr) {
695 Colormap cmap = DefaultColormap(dpy, screen);
698 if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
699 eprint("error, cannot allocate color '%s'\n", colstr);
707 unsigned char *p = NULL;
711 status = XGetWindowProperty(dpy, w, wmatom[WMState], 0L, 2L, False, wmatom[WMState],
712 &real, &format, &n, &extra, (unsigned char **)&p);
713 if(status != Success)
722 gettextprop(Window w, Atom atom, char *text, uint size) {
727 if(!text || size == 0)
730 XGetTextProperty(dpy, w, &name, atom);
733 if(name.encoding == XA_STRING)
734 strncpy(text, (char *)name.value, size - 1);
736 if(XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success
738 strncpy(text, *list, size - 1);
739 XFreeStringList(list);
742 text[size - 1] = '\0';
748 grabbuttons(Client *c, Bool focused) {
750 uint buttons[] = { Button1, Button2, Button3 };
751 uint modifiers[] = { MODKEY, MODKEY|LockMask, MODKEY|numlockmask,
752 MODKEY|numlockmask|LockMask} ;
754 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
756 for(i = 0; i < LENGTH(buttons); i++)
757 for(j = 0; j < LENGTH(modifiers); j++)
758 XGrabButton(dpy, buttons[i], modifiers[j], c->win, False,
759 BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
761 XGrabButton(dpy, AnyButton, AnyModifier, c->win, False,
762 BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
769 XModifierKeymap *modmap;
771 /* init modifier map */
772 modmap = XGetModifierMapping(dpy);
773 for(i = 0; i < 8; i++)
774 for(j = 0; j < modmap->max_keypermod; j++) {
775 if(modmap->modifiermap[i * modmap->max_keypermod + j] == XKeysymToKeycode(dpy, XK_Num_Lock))
776 numlockmask = (1 << i);
778 XFreeModifiermap(modmap);
780 XUngrabKey(dpy, AnyKey, AnyModifier, root);
781 for(i = 0; i < LENGTH(keys); i++) {
782 code = XKeysymToKeycode(dpy, keys[i].keysym);
783 XGrabKey(dpy, code, keys[i].mod, root, True,
784 GrabModeAsync, GrabModeAsync);
785 XGrabKey(dpy, code, keys[i].mod|LockMask, root, True,
786 GrabModeAsync, GrabModeAsync);
787 XGrabKey(dpy, code, keys[i].mod|numlockmask, root, True,
788 GrabModeAsync, GrabModeAsync);
789 XGrabKey(dpy, code, keys[i].mod|numlockmask|LockMask, root, True,
790 GrabModeAsync, GrabModeAsync);
795 initfont(const char *fontstr) {
796 char *def, **missing;
801 XFreeFontSet(dpy, dc.font.set);
802 dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
805 fprintf(stderr, "dwm: missing fontset: %s\n", missing[n]);
806 XFreeStringList(missing);
809 XFontSetExtents *font_extents;
810 XFontStruct **xfonts;
812 dc.font.ascent = dc.font.descent = 0;
813 font_extents = XExtentsOfFontSet(dc.font.set);
814 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
815 for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
816 dc.font.ascent = MAX(dc.font.ascent, (*xfonts)->ascent);
817 dc.font.descent = MAX(dc.font.descent,(*xfonts)->descent);
823 XFreeFont(dpy, dc.font.xfont);
824 dc.font.xfont = NULL;
825 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr))
826 && !(dc.font.xfont = XLoadQueryFont(dpy, "fixed")))
827 eprint("error, cannot load font: '%s'\n", fontstr);
828 dc.font.ascent = dc.font.xfont->ascent;
829 dc.font.descent = dc.font.xfont->descent;
831 dc.font.height = dc.font.ascent + dc.font.descent;
838 for(c = clients; c; c = c->next)
845 isprotodel(Client *c) {
850 if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
851 for(i = 0; !ret && i < n; i++)
852 if(protocols[i] == wmatom[WMDelete])
863 for(c = clients; c; c = c->next)
864 if(c->isurgent && c->tags & 1 << t)
870 keypress(XEvent *e) {
876 keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
877 for(i = 0; i < LENGTH(keys); i++)
878 if(keysym == keys[i].keysym
879 && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state))
882 keys[i].func(keys[i].arg);
887 killclient(const void *arg) {
892 if(isprotodel(sel)) {
893 ev.type = ClientMessage;
894 ev.xclient.window = sel->win;
895 ev.xclient.message_type = wmatom[WMProtocols];
896 ev.xclient.format = 32;
897 ev.xclient.data.l[0] = wmatom[WMDelete];
898 ev.xclient.data.l[1] = CurrentTime;
899 XSendEvent(dpy, sel->win, False, NoEventMask, &ev);
902 XKillClient(dpy, sel->win);
906 manage(Window w, XWindowAttributes *wa) {
907 Client *c, *t = NULL;
912 if(!(c = calloc(1, sizeof(Client))))
913 eprint("fatal: could not calloc() %u bytes\n", sizeof(Client));
921 c->oldbw = wa->border_width;
922 if(c->w == sw && c->h == sh) {
925 c->bw = wa->border_width;
928 if(c->x + c->w + 2 * c->bw > sx + sw)
929 c->x = sx + sw - c->w - 2 * c->bw;
930 if(c->y + c->h + 2 * c->bw > sy + sh)
931 c->y = sy + sh - c->h - 2 * c->bw;
932 c->x = MAX(c->x, sx);
933 c->y = MAX(c->y, by == 0 ? bh : sy);
937 wc.border_width = c->bw;
938 XConfigureWindow(dpy, w, CWBorderWidth, &wc);
939 XSetWindowBorder(dpy, w, dc.norm[ColBorder]);
940 configure(c); /* propagates border_width, if size doesn't change */
942 XSelectInput(dpy, w, EnterWindowMask|FocusChangeMask|PropertyChangeMask|StructureNotifyMask);
943 grabbuttons(c, False);
945 if((rettrans = XGetTransientForHint(dpy, w, &trans) == Success))
946 for(t = clients; t && t->win != trans; t = t->next);
952 c->isfloating = (rettrans == Success) || c->isfixed;
955 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h); /* some windows require this */
956 XMapWindow(dpy, c->win);
957 setclientstate(c, NormalState);
962 mappingnotify(XEvent *e) {
963 XMappingEvent *ev = &e->xmapping;
965 XRefreshKeyboardMapping(ev);
966 if(ev->request == MappingKeyboard)
971 maprequest(XEvent *e) {
972 static XWindowAttributes wa;
973 XMapRequestEvent *ev = &e->xmaprequest;
975 if(!XGetWindowAttributes(dpy, ev->window, &wa))
977 if(wa.override_redirect)
979 if(!getclient(ev->window))
980 manage(ev->window, &wa);
984 movemouse(Client *c) {
985 int x1, y1, ocx, ocy, di, nx, ny;
993 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
994 None, cursor[CurMove], CurrentTime) != GrabSuccess)
996 XQueryPointer(dpy, root, &dummy, &dummy, &x1, &y1, &di, &di, &dui);
998 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
1001 XUngrabPointer(dpy, CurrentTime);
1003 case ConfigureRequest:
1006 handler[ev.type](&ev);
1010 nx = ocx + (ev.xmotion.x - x1);
1011 ny = ocy + (ev.xmotion.y - y1);
1012 if(snap && nx >= wx && nx <= wx + ww
1013 && ny >= wy && ny <= wy + wh) {
1014 if(abs(wx - nx) < snap)
1016 else if(abs((wx + ww) - (nx + c->w + 2 * c->bw)) < snap)
1017 nx = wx + ww - c->w - 2 * c->bw;
1018 if(abs(wy - ny) < snap)
1020 else if(abs((wy + wh) - (ny + c->h + 2 * c->bw)) < snap)
1021 ny = wy + wh - c->h - 2 * c->bw;
1022 if(!c->isfloating && lt->arrange && (abs(nx - c->x) > snap || abs(ny - c->y) > snap))
1023 togglefloating(NULL);
1025 if(!lt->arrange || c->isfloating)
1026 resize(c, nx, ny, c->w, c->h, False);
1033 nexttiled(Client *c) {
1034 for(; c && (c->isfloating || !VISIBLE(c)); c = c->next);
1039 propertynotify(XEvent *e) {
1042 XPropertyEvent *ev = &e->xproperty;
1044 if(ev->state == PropertyDelete)
1045 return; /* ignore */
1046 if((c = getclient(ev->window))) {
1049 case XA_WM_TRANSIENT_FOR:
1050 XGetTransientForHint(dpy, c->win, &trans);
1051 if(!c->isfloating && (c->isfloating = (getclient(trans) != NULL)))
1054 case XA_WM_NORMAL_HINTS:
1062 if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
1071 quit(const void *arg) {
1072 readin = running = False;
1076 resize(Client *c, int x, int y, int w, int h, Bool sizehints) {
1080 /* set minimum possible */
1084 /* temporarily remove base dimensions */
1088 /* adjust for aspect limits */
1089 if(c->minax != c->maxax && c->minay != c->maxay
1090 && c->minax > 0 && c->maxax > 0 && c->minay > 0 && c->maxay > 0) {
1091 if(w * c->maxay > h * c->maxax)
1092 w = h * c->maxax / c->maxay;
1093 else if(w * c->minay < h * c->minax)
1094 h = w * c->minay / c->minax;
1097 /* adjust for increment value */
1103 /* restore base dimensions */
1107 w = MAX(w, c->minw);
1108 h = MAX(h, c->minh);
1111 w = MIN(w, c->maxw);
1114 h = MIN(h, c->maxh);
1116 if(w <= 0 || h <= 0)
1119 x = sw - w - 2 * c->bw;
1121 y = sh - h - 2 * c->bw;
1122 if(x + w + 2 * c->bw < sx)
1124 if(y + h + 2 * c->bw < sy)
1126 if(c->x != x || c->y != y || c->w != w || c->h != h || c->isbanned || c->ismax) {
1127 c->isbanned = c->ismax = False;
1130 c->w = wc.width = w;
1131 c->h = wc.height = h;
1132 wc.border_width = c->bw;
1133 XConfigureWindow(dpy, c->win,
1134 CWX|CWY|CWWidth|CWHeight|CWBorderWidth, &wc);
1141 resizemouse(Client *c) {
1149 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1150 None, cursor[CurResize], CurrentTime) != GrabSuccess)
1152 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->bw - 1, c->h + c->bw - 1);
1154 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask , &ev);
1157 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0,
1158 c->w + c->bw - 1, c->h + c->bw - 1);
1159 XUngrabPointer(dpy, CurrentTime);
1160 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1162 case ConfigureRequest:
1165 handler[ev.type](&ev);
1169 nw = MAX(ev.xmotion.x - ocx - 2 * c->bw + 1, 1);
1170 nh = MAX(ev.xmotion.y - ocy - 2 * c->bw + 1, 1);
1172 if(snap && nw >= wx && nw <= wx + ww
1173 && nh >= wy && nh <= wy + wh) {
1174 if(!c->isfloating && lt->arrange
1175 && (abs(nw - c->w) > snap || abs(nh - c->h) > snap))
1176 togglefloating(NULL);
1178 if(!lt->arrange || c->isfloating)
1179 resize(c, c->x, c->y, nw, nh, True);
1194 if(domax || sel->isfloating || !lt->arrange)
1195 XRaiseWindow(dpy, sel->win);
1196 if(!domax && lt->arrange) {
1197 wc.stack_mode = Below;
1198 wc.sibling = barwin;
1199 for(c = stack; c; c = c->snext)
1200 if(!c->isfloating && VISIBLE(c)) {
1201 XConfigureWindow(dpy, c->win, CWSibling|CWStackMode, &wc);
1202 wc.sibling = c->win;
1206 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1212 char sbuf[sizeof stext];
1218 /* main event loop, also reads status text from stdin */
1220 xfd = ConnectionNumber(dpy);
1223 len = sizeof stext - 1;
1224 sbuf[len] = stext[len] = '\0'; /* 0-terminator is never touched */
1228 FD_SET(STDIN_FILENO, &rd);
1230 if(select(xfd + 1, &rd, NULL, NULL, NULL) == -1) {
1233 eprint("select failed\n");
1235 if(FD_ISSET(STDIN_FILENO, &rd)) {
1236 switch((r = read(STDIN_FILENO, sbuf + offset, len - offset))) {
1238 strncpy(stext, strerror(errno), len);
1242 strncpy(stext, "EOF", 4);
1246 for(p = sbuf + offset; r > 0; p++, r--, offset++)
1247 if(*p == '\n' || *p == '\0') {
1249 strncpy(stext, sbuf, len);
1250 p += r - 1; /* p is sbuf + offset + r - 1 */
1251 for(r = 0; *(p - r) && *(p - r) != '\n'; r++);
1254 memmove(sbuf, p - r + 1, r);
1261 while(XPending(dpy)) {
1262 XNextEvent(dpy, &ev);
1263 if(handler[ev.type])
1264 (handler[ev.type])(&ev); /* call handler */
1272 Window *wins, d1, d2;
1273 XWindowAttributes wa;
1276 if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1277 for(i = 0; i < num; i++) {
1278 if(!XGetWindowAttributes(dpy, wins[i], &wa)
1279 || wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1281 if(wa.map_state == IsViewable || getstate(wins[i]) == IconicState)
1282 manage(wins[i], &wa);
1284 for(i = 0; i < num; i++) { /* now the transients */
1285 if(!XGetWindowAttributes(dpy, wins[i], &wa))
1287 if(XGetTransientForHint(dpy, wins[i], &d1)
1288 && (wa.map_state == IsViewable || getstate(wins[i]) == IconicState))
1289 manage(wins[i], &wa);
1297 setclientstate(Client *c, long state) {
1298 long data[] = {state, None};
1300 XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1301 PropModeReplace, (unsigned char *)data, 2);
1304 /* arg > 1.0 will set mfact absolutly */
1306 setmfact(const void *arg) {
1307 double d = *((double*) arg);
1309 if(!d || lt->arrange != tile)
1311 d = d < 1.0 ? d + mfact : d - 1.0;
1312 if(d < 0.1 || d > 0.9)
1321 XSetWindowAttributes wa;
1324 screen = DefaultScreen(dpy);
1325 root = RootWindow(dpy, screen);
1329 sw = DisplayWidth(dpy, screen);
1330 sh = DisplayHeight(dpy, screen);
1331 bh = dc.font.height + 2;
1335 wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1336 wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1337 wmatom[WMName] = XInternAtom(dpy, "WM_NAME", False);
1338 wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1339 netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1340 netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1343 wa.cursor = cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1344 cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1345 cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1347 /* init appearance */
1348 dc.norm[ColBorder] = getcolor(NORMBORDERCOLOR);
1349 dc.norm[ColBG] = getcolor(NORMBGCOLOR);
1350 dc.norm[ColFG] = getcolor(NORMFGCOLOR);
1351 dc.sel[ColBorder] = getcolor(SELBORDERCOLOR);
1352 dc.sel[ColBG] = getcolor(SELBGCOLOR);
1353 dc.sel[ColFG] = getcolor(SELFGCOLOR);
1356 dc.drawable = XCreatePixmap(dpy, root, DisplayWidth(dpy, screen), bh, DefaultDepth(dpy, screen));
1357 dc.gc = XCreateGC(dpy, root, 0, 0);
1358 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
1360 XSetFont(dpy, dc.gc, dc.font.xfont->fid);
1363 for(blw = i = 0; LENGTH(layouts) > 1 && i < LENGTH(layouts); i++) {
1364 w = TEXTW(layouts[i].symbol);
1368 wa.override_redirect = 1;
1369 wa.background_pixmap = ParentRelative;
1370 wa.event_mask = ButtonPressMask|ExposureMask;
1372 barwin = XCreateWindow(dpy, root, bx, by, bw, bh, 0, DefaultDepth(dpy, screen),
1373 CopyFromParent, DefaultVisual(dpy, screen),
1374 CWOverrideRedirect|CWBackPixmap|CWEventMask, &wa);
1375 XDefineCursor(dpy, barwin, cursor[CurNormal]);
1376 XMapRaised(dpy, barwin);
1377 strcpy(stext, "dwm-"VERSION);
1380 /* EWMH support per view */
1381 XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1382 PropModeReplace, (unsigned char *) netatom, NetLast);
1384 /* select for events */
1385 wa.event_mask = SubstructureRedirectMask|SubstructureNotifyMask
1386 |EnterWindowMask|LeaveWindowMask|StructureNotifyMask;
1387 XChangeWindowAttributes(dpy, root, CWEventMask|CWCursor, &wa);
1388 XSelectInput(dpy, root, wa.event_mask);
1396 spawn(const void *arg) {
1397 static char *shell = NULL;
1399 if(!shell && !(shell = getenv("SHELL")))
1401 /* The double-fork construct avoids zombie processes and keeps the code
1402 * clean from stupid signal handlers. */
1406 close(ConnectionNumber(dpy));
1408 execl(shell, shell, "-c", (char *)arg, (char *)NULL);
1409 fprintf(stderr, "dwm: execl '%s -c %s'", shell, (char *)arg);
1418 tag(const void *arg) {
1419 if(sel && *(int *)arg & TAGMASK) {
1420 sel->tags = *(int *)arg & TAGMASK;
1426 textnw(const char *text, uint len) {
1430 XmbTextExtents(dc.font.set, text, len, NULL, &r);
1433 return XTextWidth(dc.font.xfont, text, len);
1438 int x, y, h, w, mx, my, mw, mh, tx, ty, tw, th;
1442 for(n = 0, c = nexttiled(clients); c; c = nexttiled(c->next), n++);
1446 /* master area geometry */
1452 /* tile area geometry */
1459 c = nexttiled(clients);
1462 tileresize(c, wx, wy, ww - 2 * c->bw, wh - 2 * c->bw);
1464 tileresize(c, mx, my, mw - 2 * c->bw, mh - 2 * c->bw);
1470 x = (tx > c->x + c->w) ? c->x + c->w + 2 * c->bw : tw;
1472 w = (tx > c->x + c->w) ? wx + ww - x : tw;
1477 for(i = 0, c = nexttiled(c->next); c; c = nexttiled(c->next), i++) {
1478 if(i + 1 == n) /* remainder */
1479 tileresize(c, x, y, w - 2 * c->bw, (ty + th) - y - 2 * c->bw);
1481 tileresize(c, x, y, w - 2 * c->bw, h - 2 * c->bw);
1483 y = c->y + c->h + 2 * c->bw;
1488 tileresize(Client *c, int x, int y, int w, int h) {
1489 resize(c, x, y, w, h, resizehints);
1490 if(resizehints && ((c->h < bh) || (c->h > h) || (c->w < bh) || (c->w > w)))
1491 /* client doesn't accept size constraints */
1492 resize(c, x, y, w, h, False);
1496 togglebar(const void *arg) {
1504 togglefloating(const void *arg) {
1507 sel->isfloating = !sel->isfloating;
1509 resize(sel, sel->x, sel->y, sel->w, sel->h, True);
1514 togglelayout(const void *arg) {
1518 if(++lt == &layouts[LENGTH(layouts)])
1522 for(i = 0; i < LENGTH(layouts); i++)
1523 if(!strcmp((char *)arg, layouts[i].symbol))
1525 if(i == LENGTH(layouts))
1536 togglemax(const void *arg) {
1542 toggletag(const void *arg) {
1543 if(sel && (sel->tags ^ ((*(int *)arg) & TAGMASK))) {
1544 sel->tags ^= (*(int *)arg) & TAGMASK;
1550 toggleview(const void *arg) {
1551 if((tagset[seltags] ^ ((*(int *)arg) & TAGMASK))) {
1552 tagset[seltags] ^= (*(int *)arg) & TAGMASK;
1558 unmanage(Client *c) {
1561 wc.border_width = c->oldbw;
1562 /* The server grab construct avoids race conditions. */
1564 XSetErrorHandler(xerrordummy);
1565 XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
1570 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1571 setclientstate(c, WithdrawnState);
1574 XSetErrorHandler(xerror);
1580 unmapnotify(XEvent *e) {
1582 XUnmapEvent *ev = &e->xunmap;
1584 if((c = getclient(ev->window)))
1590 if(dc.drawable != 0)
1591 XFreePixmap(dpy, dc.drawable);
1592 dc.drawable = XCreatePixmap(dpy, root, bw, bh, DefaultDepth(dpy, screen));
1593 XMoveResizeWindow(dpy, barwin, bx, by, bw, bh);
1600 XineramaScreenInfo *info = NULL;
1602 /* window area geometry */
1603 if(XineramaIsActive(dpy)) {
1604 info = XineramaQueryScreens(dpy, &i);
1606 wy = showbar && topbar ? info[0].y_org + bh : info[0].y_org;
1608 wh = showbar ? info[0].height - bh : info[0].height;
1615 wy = showbar && topbar ? sy + bh : sy;
1617 wh = showbar ? sh - bh : sh;
1622 by = showbar ? (topbar ? wy - bh : wy + wh) : -bh;
1627 updatesizehints(Client *c) {
1631 if(!XGetWMNormalHints(dpy, c->win, &size, &msize) || !size.flags)
1633 c->flags = size.flags;
1634 if(c->flags & PBaseSize) {
1635 c->basew = size.base_width;
1636 c->baseh = size.base_height;
1638 else if(c->flags & PMinSize) {
1639 c->basew = size.min_width;
1640 c->baseh = size.min_height;
1643 c->basew = c->baseh = 0;
1644 if(c->flags & PResizeInc) {
1645 c->incw = size.width_inc;
1646 c->inch = size.height_inc;
1649 c->incw = c->inch = 0;
1650 if(c->flags & PMaxSize) {
1651 c->maxw = size.max_width;
1652 c->maxh = size.max_height;
1655 c->maxw = c->maxh = 0;
1656 if(c->flags & PMinSize) {
1657 c->minw = size.min_width;
1658 c->minh = size.min_height;
1660 else if(c->flags & PBaseSize) {
1661 c->minw = size.base_width;
1662 c->minh = size.base_height;
1665 c->minw = c->minh = 0;
1666 if(c->flags & PAspect) {
1667 c->minax = size.min_aspect.x;
1668 c->maxax = size.max_aspect.x;
1669 c->minay = size.min_aspect.y;
1670 c->maxay = size.max_aspect.y;
1673 c->minax = c->maxax = c->minay = c->maxay = 0;
1674 c->isfixed = (c->maxw && c->minw && c->maxh && c->minh
1675 && c->maxw == c->minw && c->maxh == c->minh);
1679 updatetitle(Client *c) {
1680 if(!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
1681 gettextprop(c->win, wmatom[WMName], c->name, sizeof c->name);
1685 updatewmhints(Client *c) {
1688 if((wmh = XGetWMHints(dpy, c->win))) {
1690 sel->isurgent = False;
1692 c->isurgent = (wmh->flags & XUrgencyHint) ? True : False;
1698 view(const void *arg) {
1699 if(*(int *)arg & TAGMASK) {
1700 seltags ^= 1; /* toggle sel tagset */
1701 tagset[seltags] = *(int *)arg & TAGMASK;
1707 viewprevtag(const void *arg) {
1708 seltags ^= 1; /* toggle sel tagset */
1712 /* There's no way to check accesses to destroyed windows, thus those cases are
1713 * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
1714 * default error handler, which may call exit. */
1716 xerror(Display *dpy, XErrorEvent *ee) {
1717 if(ee->error_code == BadWindow
1718 || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1719 || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1720 || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1721 || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1722 || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1723 || (ee->request_code == X_GrabButton && ee->error_code == BadAccess)
1724 || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1725 || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1727 fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1728 ee->request_code, ee->error_code);
1729 return xerrorxlib(dpy, ee); /* may call exit */
1733 xerrordummy(Display *dpy, XErrorEvent *ee) {
1737 /* Startup Error handler to check if another window manager
1738 * is already running. */
1740 xerrorstart(Display *dpy, XErrorEvent *ee) {
1746 zoom(const void *arg) {
1749 if(!lt->arrange || sel->isfloating)
1751 if(c == nexttiled(clients))
1752 if(!c || !(c = nexttiled(c->next)))
1761 main(int argc, char *argv[]) {
1762 if(argc == 2 && !strcmp("-v", argv[1]))
1763 eprint("dwm-"VERSION", © 2006-2008 dwm engineers, see LICENSE for details\n");
1765 eprint("usage: dwm [-v]\n");
1767 setlocale(LC_CTYPE, "");
1768 if(!(dpy = XOpenDisplay(0)))
1769 eprint("dwm: cannot open display\n");