3 * - treat monocle as floating layout, actually otherwise certain monocled windows don't get raised
4 * - use WX, WY, WW, WH for window snapping/resizing/mouse
5 * - MOX, MOY, MOW, MOH should only be used in the case of monocle layout and of n==1 in tiled
8 /* See LICENSE file for copyright and license details.
10 * dynamic window manager is designed like any other X client as well. It is
11 * driven through handling X events. In contrast to other X clients, a window
12 * manager selects for SubstructureRedirectMask on the root window, to receive
13 * events about window (dis-)appearance. Only one X connection at a time is
14 * allowed to select for this event mask.
16 * Calls to fetch an X event from the event queue are blocking. Due reading
17 * status text from standard input, a select()-driven main loop has been
18 * implemented which selects for reads on the X connection and STDIN_FILENO to
19 * handle all data smoothly. The event handlers of dwm are organized in an
20 * array which is accessed whenever a new event has been fetched. This allows
21 * event dispatching in O(1) time.
23 * Each child of the root window is called a client, except windows which have
24 * set the override_redirect flag. Clients are organized in a global
25 * doubly-linked client list, the focus history is remembered through a global
26 * stack list. Each client contains an array of Bools of the same size as the
27 * global tags array to indicate the tags of a client.
29 * Keys and tagging rules are organized as arrays and defined in config.h.
31 * To understand everything else, start reading main().
40 #include <sys/select.h>
41 #include <sys/types.h>
44 #include <X11/cursorfont.h>
45 #include <X11/keysym.h>
46 #include <X11/Xatom.h>
48 #include <X11/Xproto.h>
49 #include <X11/Xutil.h>
52 #define BUTTONMASK (ButtonPressMask|ButtonReleaseMask)
53 #define CLEANMASK(mask) (mask & ~(numlockmask|LockMask))
54 #define LENGTH(x) (sizeof x / sizeof x[0])
56 #define MOUSEMASK (BUTTONMASK|PointerMotionMask)
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 struct Client Client;
70 int basew, baseh, incw, inch, maxw, maxh, minw, minh;
71 int minax, maxax, minay, maxay;
73 unsigned int border, oldborder;
74 Bool isbanned, isfixed, isfloating, isurgent;
84 unsigned long norm[ColLast];
85 unsigned long sel[ColLast];
95 } DC; /* draw context */
100 void (*func)(const char *arg);
106 void (*arrange)(void);
115 /* function declarations */
116 void applyrules(Client *c);
118 void attach(Client *c);
119 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, unsigned long col[ColLast]);
132 void drawtext(const char *text, unsigned long col[ColLast], Bool invert);
133 void *emallocz(unsigned int size);
134 void enternotify(XEvent *e);
135 void eprint(const char *errstr, ...);
136 void expose(XEvent *e);
137 void floating(void); /* default floating layout */
138 void focus(Client *c);
139 void focusin(XEvent *e);
140 void focusnext(const char *arg);
141 void focusprev(const char *arg);
142 Client *getclient(Window w);
143 unsigned long getcolor(const char *colstr);
144 long getstate(Window w);
145 Bool gettextprop(Window w, Atom atom, char *text, unsigned int size);
146 void grabbuttons(Client *c, Bool focused);
148 unsigned int idxoftag(const char *t);
149 void initfont(const char *fontstr);
150 Bool isoccupied(unsigned int t);
151 Bool isprotodel(Client *c);
152 Bool isurgent(unsigned int t);
153 Bool isvisible(Client *c);
154 void keypress(XEvent *e);
155 void killclient(const char *arg);
156 void manage(Window w, XWindowAttributes *wa);
157 void mappingnotify(XEvent *e);
158 void maprequest(XEvent *e);
160 void movemouse(Client *c);
161 Client *nexttiled(Client *c);
162 void propertynotify(XEvent *e);
163 void quit(const char *arg);
164 void reapply(const char *arg);
165 void resize(Client *c, int x, int y, int w, int h, Bool sizehints);
166 void resizemouse(Client *c);
170 void setclientstate(Client *c, long state);
171 void setlayout(const char *arg);
173 void spawn(const char *arg);
174 void tag(const char *arg);
175 unsigned int textnw(const char *text, unsigned int len);
176 unsigned int textw(const char *text);
178 void togglefloating(const char *arg);
179 void toggletag(const char *arg);
180 void toggleview(const char *arg);
181 void unban(Client *c);
182 void unmanage(Client *c);
183 void unmapnotify(XEvent *e);
184 void updatesizehints(Client *c);
185 void updatetitle(Client *c);
186 void updatewmhints(Client *c);
187 void view(const char *arg);
188 void viewprevtag(const char *arg); /* views previous selected tags */
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 char *arg);
195 char stext[256], buf[256];
196 int screen, sx, sy, sw, sh;
197 int (*xerrorxlib)(Display *, XErrorEvent *);
198 unsigned int bh, blw = 0;
199 unsigned int numlockmask = 0;
200 void (*handler[LASTEvent]) (XEvent *) = {
201 [ButtonPress] = buttonpress,
202 [ConfigureRequest] = configurerequest,
203 [ConfigureNotify] = configurenotify,
204 [DestroyNotify] = destroynotify,
205 [EnterNotify] = enternotify,
208 [KeyPress] = keypress,
209 [MappingNotify] = mappingnotify,
210 [MapRequest] = maprequest,
211 [PropertyNotify] = propertynotify,
212 [UnmapNotify] = unmapnotify
214 Atom wmatom[WMLast], netatom[NetLast];
216 Bool otherwm, readin;
220 Client *clients = NULL;
222 Client *stack = NULL;
223 Cursor cursor[CurLast];
229 /* configuration, allows nested code to access above variables */
231 #define TAGSZ (LENGTH(tags) * sizeof(Bool))
232 static Bool tmp[LENGTH(tags)];
234 /* function implementations */
237 applyrules(Client *c) {
239 Bool matched = False;
241 XClassHint ch = { 0 };
244 XGetClassHint(dpy, c->win, &ch);
245 for(i = 0; i < LENGTH(rules); i++) {
247 if(strstr(c->name, r->prop)
248 || (ch.res_class && strstr(ch.res_class, r->prop))
249 || (ch.res_name && strstr(ch.res_name, r->prop)))
251 c->isfloating = r->isfloating;
253 c->tags[idxoftag(r->tag)] = True;
263 memcpy(c->tags, seltags, TAGSZ);
270 for(c = clients; c; c = c->next)
290 attachstack(Client *c) {
299 XMoveWindow(dpy, c->win, c->x + 3 * sw, c->y);
304 buttonpress(XEvent *e) {
307 XButtonPressedEvent *ev = &e->xbutton;
309 if(ev->window == barwin) {
311 for(i = 0; i < LENGTH(tags); i++) {
314 if(ev->button == Button1) {
315 if(ev->state & MODKEY)
320 else if(ev->button == Button3) {
321 if(ev->state & MODKEY)
330 else if((c = getclient(ev->window))) {
332 if(CLEANMASK(ev->state) != MODKEY)
334 if(ev->button == Button1) {
338 else if(ev->button == Button2) {
339 if((floating != lt->arrange) && c->isfloating)
340 togglefloating(NULL);
344 else if(ev->button == Button3 && !c->isfixed) {
354 XSetErrorHandler(xerrorstart);
356 /* this causes an error if some other window manager is running */
357 XSelectInput(dpy, DefaultRootWindow(dpy), SubstructureRedirectMask);
360 eprint("dwm: another window manager is already running\n");
362 XSetErrorHandler(NULL);
363 xerrorxlib = XSetErrorHandler(xerror);
375 XFreeFontSet(dpy, dc.font.set);
377 XFreeFont(dpy, dc.font.xfont);
378 XUngrabKey(dpy, AnyKey, AnyModifier, root);
379 XFreePixmap(dpy, dc.drawable);
381 XFreeCursor(dpy, cursor[CurNormal]);
382 XFreeCursor(dpy, cursor[CurResize]);
383 XFreeCursor(dpy, cursor[CurMove]);
384 XDestroyWindow(dpy, barwin);
386 XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime);
390 configure(Client *c) {
393 ce.type = ConfigureNotify;
401 ce.border_width = c->border;
403 ce.override_redirect = False;
404 XSendEvent(dpy, c->win, False, StructureNotifyMask, (XEvent *)&ce);
408 configurenotify(XEvent *e) {
409 XConfigureEvent *ev = &e->xconfigure;
411 if(ev->window == root && (ev->width != sw || ev->height != sh)) {
414 XFreePixmap(dpy, dc.drawable);
415 dc.drawable = XCreatePixmap(dpy, root, BW, bh, DefaultDepth(dpy, screen));
416 XMoveResizeWindow(dpy, barwin, BX, BY, BW, bh);
422 configurerequest(XEvent *e) {
424 XConfigureRequestEvent *ev = &e->xconfigurerequest;
427 if((c = getclient(ev->window))) {
428 if(ev->value_mask & CWBorderWidth)
429 c->border = ev->border_width;
430 if(c->isfixed || c->isfloating || (floating == lt->arrange)) {
431 if(ev->value_mask & CWX)
433 if(ev->value_mask & CWY)
435 if(ev->value_mask & CWWidth)
437 if(ev->value_mask & CWHeight)
439 if((c->x - sx + c->w) > sw && c->isfloating)
440 c->x = sx + (sw / 2 - c->w / 2); /* center in x direction */
441 if((c->y - sy + c->h) > sh && c->isfloating)
442 c->y = sy + (sh / 2 - c->h / 2); /* center in y direction */
443 if((ev->value_mask & (CWX|CWY))
444 && !(ev->value_mask & (CWWidth|CWHeight)))
447 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h);
455 wc.width = ev->width;
456 wc.height = ev->height;
457 wc.border_width = ev->border_width;
458 wc.sibling = ev->above;
459 wc.stack_mode = ev->detail;
460 XConfigureWindow(dpy, ev->window, ev->value_mask, &wc);
466 destroynotify(XEvent *e) {
468 XDestroyWindowEvent *ev = &e->xdestroywindow;
470 if((c = getclient(ev->window)))
477 c->prev->next = c->next;
479 c->next->prev = c->prev;
482 c->next = c->prev = NULL;
486 detachstack(Client *c) {
489 for(tc=&stack; *tc && *tc != c; tc=&(*tc)->snext);
499 for(c = stack; c && !isvisible(c); c = c->snext);
500 for(i = 0; i < LENGTH(tags); i++) {
501 dc.w = textw(tags[i]);
503 drawtext(tags[i], dc.sel, isurgent(i));
504 drawsquare(c && c->tags[i], isoccupied(i), isurgent(i), dc.sel);
507 drawtext(tags[i], dc.norm, isurgent(i));
508 drawsquare(c && c->tags[i], isoccupied(i), isurgent(i), dc.norm);
513 drawtext(lt->symbol, dc.norm, False);
521 drawtext(stext, dc.norm, False);
522 if((dc.w = dc.x - x) > bh) {
525 drawtext(c->name, dc.sel, False);
526 drawsquare(False, c->isfloating, False, dc.sel);
529 drawtext(NULL, dc.norm, False);
531 XCopyArea(dpy, dc.drawable, barwin, dc.gc, 0, 0, BW, bh, 0, 0);
536 drawsquare(Bool filled, Bool empty, Bool invert, unsigned long col[ColLast]) {
539 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
541 gcv.foreground = col[invert ? ColBG : ColFG];
542 XChangeGC(dpy, dc.gc, GCForeground, &gcv);
543 x = (dc.font.ascent + dc.font.descent + 2) / 4;
547 r.width = r.height = x + 1;
548 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
551 r.width = r.height = x;
552 XDrawRectangles(dpy, dc.drawable, dc.gc, &r, 1);
557 drawtext(const char *text, unsigned long col[ColLast], Bool invert) {
559 unsigned int len, olen;
560 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
562 XSetForeground(dpy, dc.gc, col[invert ? ColFG : ColBG]);
563 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
567 olen = len = strlen(text);
568 if(len >= sizeof buf)
569 len = sizeof buf - 1;
570 memcpy(buf, text, len);
572 h = dc.font.ascent + dc.font.descent;
573 y = dc.y + (dc.h / 2) - (h / 2) + dc.font.ascent;
575 /* shorten text if necessary */
576 while(len && (w = textnw(buf, len)) > dc.w - h)
587 return; /* too long */
588 XSetForeground(dpy, dc.gc, col[invert ? ColBG : ColFG]);
590 XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
592 XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
596 emallocz(unsigned int size) {
597 void *res = calloc(1, size);
600 eprint("fatal: could not malloc() %u bytes\n", size);
605 enternotify(XEvent *e) {
607 XCrossingEvent *ev = &e->xcrossing;
609 if((ev->mode != NotifyNormal || ev->detail == NotifyInferior) && ev->window != root)
611 if((c = getclient(ev->window)))
618 eprint(const char *errstr, ...) {
621 va_start(ap, errstr);
622 vfprintf(stderr, errstr, ap);
629 XExposeEvent *ev = &e->xexpose;
631 if(ev->count == 0 && (ev->window == barwin))
636 floating(void) { /* default floating layout */
640 for(c = clients; c; c = c->next)
642 resize(c, c->x, c->y, c->w, c->h, True);
647 if(!c || (c && !isvisible(c)))
648 for(c = stack; c && !isvisible(c); c = c->snext);
649 if(sel && sel != c) {
650 grabbuttons(sel, False);
651 XSetWindowBorder(dpy, sel->win, dc.norm[ColBorder]);
652 if(lt->arrange == monocle)
653 resize(sel, sel->rx, sel->ry, sel->rw, sel->rh, True);
658 grabbuttons(c, True);
659 if(lt->arrange == monocle) {
666 resize(c, MOX, MOY, MOW, MOH, RESIZEHINTS);
671 XSetWindowBorder(dpy, c->win, dc.sel[ColBorder]);
672 XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
675 XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
680 focusin(XEvent *e) { /* there are some broken focus acquiring clients */
681 XFocusChangeEvent *ev = &e->xfocus;
683 if(sel && ev->window != sel->win)
684 XSetInputFocus(dpy, sel->win, RevertToPointerRoot, CurrentTime);
688 focusnext(const char *arg) {
693 for(c = sel->next; c && !isvisible(c); c = c->next);
695 for(c = clients; c && !isvisible(c); c = c->next);
703 focusprev(const char *arg) {
708 for(c = sel->prev; c && !isvisible(c); c = c->prev);
710 for(c = clients; c && c->next; c = c->next);
711 for(; c && !isvisible(c); c = c->prev);
720 getclient(Window w) {
723 for(c = clients; c && c->win != w; c = c->next);
728 getcolor(const char *colstr) {
729 Colormap cmap = DefaultColormap(dpy, screen);
732 if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
733 eprint("error, cannot allocate color '%s'\n", colstr);
741 unsigned char *p = NULL;
742 unsigned long n, extra;
745 status = XGetWindowProperty(dpy, w, wmatom[WMState], 0L, 2L, False, wmatom[WMState],
746 &real, &format, &n, &extra, (unsigned char **)&p);
747 if(status != Success)
756 gettextprop(Window w, Atom atom, char *text, unsigned int size) {
761 if(!text || size == 0)
764 XGetTextProperty(dpy, w, &name, atom);
767 if(name.encoding == XA_STRING)
768 strncpy(text, (char *)name.value, size - 1);
770 if(XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success
772 strncpy(text, *list, size - 1);
773 XFreeStringList(list);
776 text[size - 1] = '\0';
782 grabbuttons(Client *c, Bool focused) {
783 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
786 XGrabButton(dpy, Button1, MODKEY, c->win, False, BUTTONMASK,
787 GrabModeAsync, GrabModeSync, None, None);
788 XGrabButton(dpy, Button1, MODKEY|LockMask, c->win, False, BUTTONMASK,
789 GrabModeAsync, GrabModeSync, None, None);
790 XGrabButton(dpy, Button1, MODKEY|numlockmask, c->win, False, BUTTONMASK,
791 GrabModeAsync, GrabModeSync, None, None);
792 XGrabButton(dpy, Button1, MODKEY|numlockmask|LockMask, c->win, False, BUTTONMASK,
793 GrabModeAsync, GrabModeSync, None, None);
795 XGrabButton(dpy, Button2, MODKEY, c->win, False, BUTTONMASK,
796 GrabModeAsync, GrabModeSync, None, None);
797 XGrabButton(dpy, Button2, MODKEY|LockMask, c->win, False, BUTTONMASK,
798 GrabModeAsync, GrabModeSync, None, None);
799 XGrabButton(dpy, Button2, MODKEY|numlockmask, c->win, False, BUTTONMASK,
800 GrabModeAsync, GrabModeSync, None, None);
801 XGrabButton(dpy, Button2, MODKEY|numlockmask|LockMask, c->win, False, BUTTONMASK,
802 GrabModeAsync, GrabModeSync, None, None);
804 XGrabButton(dpy, Button3, MODKEY, c->win, False, BUTTONMASK,
805 GrabModeAsync, GrabModeSync, None, None);
806 XGrabButton(dpy, Button3, MODKEY|LockMask, c->win, False, BUTTONMASK,
807 GrabModeAsync, GrabModeSync, None, None);
808 XGrabButton(dpy, Button3, MODKEY|numlockmask, c->win, False, BUTTONMASK,
809 GrabModeAsync, GrabModeSync, None, None);
810 XGrabButton(dpy, Button3, MODKEY|numlockmask|LockMask, c->win, False, BUTTONMASK,
811 GrabModeAsync, GrabModeSync, None, None);
814 XGrabButton(dpy, AnyButton, AnyModifier, c->win, False, BUTTONMASK,
815 GrabModeAsync, GrabModeSync, None, None);
822 XModifierKeymap *modmap;
824 /* init modifier map */
825 modmap = XGetModifierMapping(dpy);
826 for(i = 0; i < 8; i++)
827 for(j = 0; j < modmap->max_keypermod; j++) {
828 if(modmap->modifiermap[i * modmap->max_keypermod + j] == XKeysymToKeycode(dpy, XK_Num_Lock))
829 numlockmask = (1 << i);
831 XFreeModifiermap(modmap);
833 XUngrabKey(dpy, AnyKey, AnyModifier, root);
834 for(i = 0; i < LENGTH(keys); i++) {
835 code = XKeysymToKeycode(dpy, keys[i].keysym);
836 XGrabKey(dpy, code, keys[i].mod, root, True,
837 GrabModeAsync, GrabModeAsync);
838 XGrabKey(dpy, code, keys[i].mod|LockMask, root, True,
839 GrabModeAsync, GrabModeAsync);
840 XGrabKey(dpy, code, keys[i].mod|numlockmask, root, True,
841 GrabModeAsync, GrabModeAsync);
842 XGrabKey(dpy, code, keys[i].mod|numlockmask|LockMask, root, True,
843 GrabModeAsync, GrabModeAsync);
848 idxoftag(const char *t) {
851 for(i = 0; (i < LENGTH(tags)) && (tags[i] != t); i++);
852 return (i < LENGTH(tags)) ? i : 0;
856 initfont(const char *fontstr) {
857 char *def, **missing;
862 XFreeFontSet(dpy, dc.font.set);
863 dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
866 fprintf(stderr, "dwm: missing fontset: %s\n", missing[n]);
867 XFreeStringList(missing);
870 XFontSetExtents *font_extents;
871 XFontStruct **xfonts;
873 dc.font.ascent = dc.font.descent = 0;
874 font_extents = XExtentsOfFontSet(dc.font.set);
875 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
876 for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
877 if(dc.font.ascent < (*xfonts)->ascent)
878 dc.font.ascent = (*xfonts)->ascent;
879 if(dc.font.descent < (*xfonts)->descent)
880 dc.font.descent = (*xfonts)->descent;
886 XFreeFont(dpy, dc.font.xfont);
887 dc.font.xfont = NULL;
888 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr))
889 && !(dc.font.xfont = XLoadQueryFont(dpy, "fixed")))
890 eprint("error, cannot load font: '%s'\n", fontstr);
891 dc.font.ascent = dc.font.xfont->ascent;
892 dc.font.descent = dc.font.xfont->descent;
894 dc.font.height = dc.font.ascent + dc.font.descent;
898 isoccupied(unsigned int t) {
901 for(c = clients; c; c = c->next)
908 isprotodel(Client *c) {
913 if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
914 for(i = 0; !ret && i < n; i++)
915 if(protocols[i] == wmatom[WMDelete])
923 isurgent(unsigned int t) {
926 for(c = clients; c; c = c->next)
927 if(c->isurgent && c->tags[t])
933 isvisible(Client *c) {
936 for(i = 0; i < LENGTH(tags); i++)
937 if(c->tags[i] && seltags[i])
943 keypress(XEvent *e) {
949 keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
950 for(i = 0; i < LENGTH(keys); i++)
951 if(keysym == keys[i].keysym
952 && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state))
955 keys[i].func(keys[i].arg);
960 killclient(const char *arg) {
965 if(isprotodel(sel)) {
966 ev.type = ClientMessage;
967 ev.xclient.window = sel->win;
968 ev.xclient.message_type = wmatom[WMProtocols];
969 ev.xclient.format = 32;
970 ev.xclient.data.l[0] = wmatom[WMDelete];
971 ev.xclient.data.l[1] = CurrentTime;
972 XSendEvent(dpy, sel->win, False, NoEventMask, &ev);
975 XKillClient(dpy, sel->win);
979 manage(Window w, XWindowAttributes *wa) {
980 Client *c, *t = NULL;
985 c = emallocz(sizeof(Client));
986 c->tags = emallocz(TAGSZ);
989 c->x = c->rx = wa->x + sx;
990 c->y = c->ry = wa->y + sy;
991 c->w = c->rw = wa->width;
992 c->h = c->rh = wa->height;
993 c->oldborder = wa->border_width;
995 if(c->w == sw && c->h == sh) {
998 c->border = wa->border_width;
1001 if(c->x + c->w + 2 * c->border > sx + sw)
1002 c->x = sx + sw - c->w - 2 * c->border;
1003 if(c->y + c->h + 2 * c->border > sy + sh)
1004 c->y = sy + sh - c->h - 2 * c->border;
1009 c->border = BORDERPX;
1011 wc.border_width = c->border;
1012 XConfigureWindow(dpy, w, CWBorderWidth, &wc);
1013 XSetWindowBorder(dpy, w, dc.norm[ColBorder]);
1014 configure(c); /* propagates border_width, if size doesn't change */
1016 XSelectInput(dpy, w, EnterWindowMask|FocusChangeMask|PropertyChangeMask|StructureNotifyMask);
1017 grabbuttons(c, False);
1019 if((rettrans = XGetTransientForHint(dpy, w, &trans) == Success))
1020 for(t = clients; t && t->win != trans; t = t->next);
1022 memcpy(c->tags, t->tags, TAGSZ);
1026 c->isfloating = (rettrans == Success) || c->isfixed;
1029 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h); /* some windows require this */
1031 XMapWindow(dpy, c->win);
1032 setclientstate(c, NormalState);
1037 mappingnotify(XEvent *e) {
1038 XMappingEvent *ev = &e->xmapping;
1040 XRefreshKeyboardMapping(ev);
1041 if(ev->request == MappingKeyboard)
1046 maprequest(XEvent *e) {
1047 static XWindowAttributes wa;
1048 XMapRequestEvent *ev = &e->xmaprequest;
1050 if(!XGetWindowAttributes(dpy, ev->window, &wa))
1052 if(wa.override_redirect)
1054 if(!getclient(ev->window))
1055 manage(ev->window, &wa);
1064 movemouse(Client *c) {
1065 int x1, y1, ocx, ocy, di, nx, ny;
1072 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1073 None, cursor[CurMove], CurrentTime) != GrabSuccess)
1075 XQueryPointer(dpy, root, &dummy, &dummy, &x1, &y1, &di, &di, &dui);
1077 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
1080 XUngrabPointer(dpy, CurrentTime);
1082 case ConfigureRequest:
1085 handler[ev.type](&ev);
1089 nx = ocx + (ev.xmotion.x - x1);
1090 ny = ocy + (ev.xmotion.y - y1);
1091 if(abs(sx - nx) < SNAP)
1093 else if(abs((sx + sw) - (nx + c->w + 2 * c->border)) < SNAP)
1094 nx = sx + sw - c->w - 2 * c->border;
1095 if(abs(sy - ny) < SNAP)
1097 else if(abs((sy + sh) - (ny + c->h + 2 * c->border)) < SNAP)
1098 ny = sy + sh - c->h - 2 * c->border;
1099 if(!c->isfloating && (lt->arrange != floating) && (abs(nx - c->x) > SNAP || abs(ny - c->y) > SNAP))
1100 togglefloating(NULL);
1101 if((lt->arrange == floating) || c->isfloating)
1102 resize(c, nx, ny, c->w, c->h, False);
1109 nexttiled(Client *c) {
1110 for(; c && (c->isfloating || !isvisible(c)); c = c->next);
1115 propertynotify(XEvent *e) {
1118 XPropertyEvent *ev = &e->xproperty;
1120 if(ev->state == PropertyDelete)
1121 return; /* ignore */
1122 if((c = getclient(ev->window))) {
1125 case XA_WM_TRANSIENT_FOR:
1126 XGetTransientForHint(dpy, c->win, &trans);
1127 if(!c->isfloating && (c->isfloating = (getclient(trans) != NULL)))
1130 case XA_WM_NORMAL_HINTS:
1138 if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
1147 quit(const char *arg) {
1148 readin = running = False;
1152 reapply(const char *arg) {
1153 static Bool zerotags[LENGTH(tags)] = { 0 };
1156 for(c = clients; c; c = c->next) {
1157 memcpy(c->tags, zerotags, sizeof zerotags);
1164 resize(Client *c, int x, int y, int w, int h, Bool sizehints) {
1168 /* set minimum possible */
1174 /* temporarily remove base dimensions */
1178 /* adjust for aspect limits */
1179 if (c->minay > 0 && c->maxay > 0 && c->minax > 0 && c->maxax > 0) {
1180 if (w * c->maxay > h * c->maxax)
1181 w = h * c->maxax / c->maxay;
1182 else if (w * c->minay < h * c->minax)
1183 h = w * c->minay / c->minax;
1186 /* adjust for increment value */
1192 /* restore base dimensions */
1196 if(c->minw > 0 && w < c->minw)
1198 if(c->minh > 0 && h < c->minh)
1200 if(c->maxw > 0 && w > c->maxw)
1202 if(c->maxh > 0 && h > c->maxh)
1205 if(w <= 0 || h <= 0)
1208 x = sw - w - 2 * c->border;
1210 y = sh - h - 2 * c->border;
1211 if(x + w + 2 * c->border < sx)
1213 if(y + h + 2 * c->border < sy)
1215 if(c->x != x || c->y != y || c->w != w || c->h != h) {
1218 c->w = wc.width = w;
1219 c->h = wc.height = h;
1220 wc.border_width = c->border;
1221 XConfigureWindow(dpy, c->win,
1222 CWX|CWY|CWWidth|CWHeight|CWBorderWidth, &wc);
1229 resizemouse(Client *c) {
1236 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1237 None, cursor[CurResize], CurrentTime) != GrabSuccess)
1239 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->border - 1, c->h + c->border - 1);
1241 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask , &ev);
1244 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0,
1245 c->w + c->border - 1, c->h + c->border - 1);
1246 XUngrabPointer(dpy, CurrentTime);
1247 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1249 case ConfigureRequest:
1252 handler[ev.type](&ev);
1256 if((nw = ev.xmotion.x - ocx - 2 * c->border + 1) <= 0)
1258 if((nh = ev.xmotion.y - ocy - 2 * c->border + 1) <= 0)
1260 if(!c->isfloating && (lt->arrange != floating) && (abs(nw - c->w) > SNAP || abs(nh - c->h) > SNAP))
1261 togglefloating(NULL);
1262 if((lt->arrange == floating) || c->isfloating)
1263 resize(c, c->x, c->y, nw, nh, True);
1278 if(sel->isfloating || (lt->arrange == floating))
1279 XRaiseWindow(dpy, sel->win);
1280 if(lt->arrange != floating) {
1281 wc.stack_mode = Below;
1282 wc.sibling = barwin;
1283 if(!sel->isfloating) {
1284 XConfigureWindow(dpy, sel->win, CWSibling|CWStackMode, &wc);
1285 wc.sibling = sel->win;
1287 for(c = nexttiled(clients); c; c = nexttiled(c->next)) {
1290 XConfigureWindow(dpy, c->win, CWSibling|CWStackMode, &wc);
1291 wc.sibling = c->win;
1295 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1301 char sbuf[sizeof stext];
1304 unsigned int len, offset;
1307 /* main event loop, also reads status text from stdin */
1309 xfd = ConnectionNumber(dpy);
1312 len = sizeof stext - 1;
1313 sbuf[len] = stext[len] = '\0'; /* 0-terminator is never touched */
1317 FD_SET(STDIN_FILENO, &rd);
1319 if(select(xfd + 1, &rd, NULL, NULL, NULL) == -1) {
1322 eprint("select failed\n");
1324 if(FD_ISSET(STDIN_FILENO, &rd)) {
1325 switch((r = read(STDIN_FILENO, sbuf + offset, len - offset))) {
1327 strncpy(stext, strerror(errno), len);
1331 strncpy(stext, "EOF", 4);
1335 for(p = sbuf + offset; r > 0; p++, r--, offset++)
1336 if(*p == '\n' || *p == '\0') {
1338 strncpy(stext, sbuf, len);
1339 p += r - 1; /* p is sbuf + offset + r - 1 */
1340 for(r = 0; *(p - r) && *(p - r) != '\n'; r++);
1343 memmove(sbuf, p - r + 1, r);
1350 while(XPending(dpy)) {
1351 XNextEvent(dpy, &ev);
1352 if(handler[ev.type])
1353 (handler[ev.type])(&ev); /* call handler */
1360 unsigned int i, num;
1361 Window *wins, d1, d2;
1362 XWindowAttributes wa;
1365 if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1366 for(i = 0; i < num; i++) {
1367 if(!XGetWindowAttributes(dpy, wins[i], &wa)
1368 || wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1370 if(wa.map_state == IsViewable || getstate(wins[i]) == IconicState)
1371 manage(wins[i], &wa);
1373 for(i = 0; i < num; i++) { /* now the transients */
1374 if(!XGetWindowAttributes(dpy, wins[i], &wa))
1376 if(XGetTransientForHint(dpy, wins[i], &d1)
1377 && (wa.map_state == IsViewable || getstate(wins[i]) == IconicState))
1378 manage(wins[i], &wa);
1386 setclientstate(Client *c, long state) {
1387 long data[] = {state, None};
1389 XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1390 PropModeReplace, (unsigned char *)data, 2);
1394 setlayout(const char *arg) {
1399 for(i = 0; i < LENGTH(layouts); i++)
1400 if(!strcmp(arg, layouts[i].symbol))
1402 if(i == LENGTH(layouts))
1414 XSetWindowAttributes wa;
1417 screen = DefaultScreen(dpy);
1418 root = RootWindow(dpy, screen);
1421 sw = DisplayWidth(dpy, screen);
1422 sh = DisplayHeight(dpy, screen);
1425 wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1426 wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1427 wmatom[WMName] = XInternAtom(dpy, "WM_NAME", False);
1428 wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1429 netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1430 netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1433 wa.cursor = cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1434 cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1435 cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1437 /* init appearance */
1438 dc.norm[ColBorder] = getcolor(NORMBORDERCOLOR);
1439 dc.norm[ColBG] = getcolor(NORMBGCOLOR);
1440 dc.norm[ColFG] = getcolor(NORMFGCOLOR);
1441 dc.sel[ColBorder] = getcolor(SELBORDERCOLOR);
1442 dc.sel[ColBG] = getcolor(SELBGCOLOR);
1443 dc.sel[ColFG] = getcolor(SELFGCOLOR);
1445 dc.h = bh = dc.font.height + 2;
1446 dc.drawable = XCreatePixmap(dpy, root, DisplayWidth(dpy, screen), bh, DefaultDepth(dpy, screen));
1447 dc.gc = XCreateGC(dpy, root, 0, 0);
1448 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
1450 XSetFont(dpy, dc.gc, dc.font.xfont->fid);
1453 seltags = emallocz(TAGSZ);
1454 prevtags = emallocz(TAGSZ);
1455 seltags[0] = prevtags[0] = True;
1461 for(blw = i = 0; i < LENGTH(layouts); i++) {
1462 i = textw(layouts[i].symbol);
1467 wa.override_redirect = 1;
1468 wa.background_pixmap = ParentRelative;
1469 wa.event_mask = ButtonPressMask|ExposureMask;
1471 barwin = XCreateWindow(dpy, root, BX, BY, BW, bh, 0, DefaultDepth(dpy, screen),
1472 CopyFromParent, DefaultVisual(dpy, screen),
1473 CWOverrideRedirect|CWBackPixmap|CWEventMask, &wa);
1474 XDefineCursor(dpy, barwin, cursor[CurNormal]);
1475 XMapRaised(dpy, barwin);
1476 strcpy(stext, "dwm-"VERSION);
1479 /* EWMH support per view */
1480 XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1481 PropModeReplace, (unsigned char *) netatom, NetLast);
1483 /* select for events */
1484 wa.event_mask = SubstructureRedirectMask|SubstructureNotifyMask
1485 |EnterWindowMask|LeaveWindowMask|StructureNotifyMask;
1486 XChangeWindowAttributes(dpy, root, CWEventMask|CWCursor, &wa);
1487 XSelectInput(dpy, root, wa.event_mask);
1495 spawn(const char *arg) {
1496 static char *shell = NULL;
1498 if(!shell && !(shell = getenv("SHELL")))
1502 /* The double-fork construct avoids zombie processes and keeps the code
1503 * clean from stupid signal handlers. */
1507 close(ConnectionNumber(dpy));
1509 execl(shell, shell, "-c", arg, (char *)NULL);
1510 fprintf(stderr, "dwm: execl '%s -c %s'", shell, arg);
1519 tag(const char *arg) {
1524 for(i = 0; i < LENGTH(tags); i++)
1525 sel->tags[i] = (NULL == arg);
1526 sel->tags[idxoftag(arg)] = True;
1531 textnw(const char *text, unsigned int len) {
1535 XmbTextExtents(dc.font.set, text, len, NULL, &r);
1538 return XTextWidth(dc.font.xfont, text, len);
1542 textw(const char *text) {
1543 return textnw(text, strlen(text)) + dc.font.height;
1548 unsigned int i, n, nx, ny, nw, nh, mw, th;
1555 for(n = 0, c = nexttiled(clients); c; c = nexttiled(c->next))
1559 mw = (n == 1) ? MOW : MW;
1560 th = (n > 1) ? TH / (n - 1) : 0;
1561 if(n > 1 && th < bh)
1564 for(i = 0, c = mc = nexttiled(clients); c; c = nexttiled(c->next)) {
1565 if(i == 0) { /* master */
1566 nw = mw - 2 * c->border;
1567 nh = MH - 2 * c->border;
1569 else { /* tile window */
1573 nw = TW - 2 * c->border;
1575 if(i + 1 == n) /* remainder */
1576 nh = (TY + TH) - ny - 2 * c->border;
1578 nh = th - 2 * c->border;
1580 resize(c, nx, ny, nw, nh, RESIZEHINTS);
1581 if((RESIZEHINTS) && ((c->h < bh) || (c->h > nh) || (c->w < bh) || (c->w > nw)))
1582 /* client doesn't accept size constraints */
1583 resize(c, nx, ny, nw, nh, False);
1584 if(n > 1 && th != TH)
1585 ny = c->y + c->h + 2 * c->border;
1591 togglefloating(const char *arg) {
1594 sel->isfloating = !sel->isfloating;
1596 resize(sel, sel->x, sel->y, sel->w, sel->h, True);
1601 toggletag(const char *arg) {
1607 sel->tags[i] = !sel->tags[i];
1608 for(j = 0; j < LENGTH(tags) && !sel->tags[j]; j++);
1609 if(j == LENGTH(tags))
1610 sel->tags[i] = True; /* at least one tag must be enabled */
1615 toggleview(const char *arg) {
1619 seltags[i] = !seltags[i];
1620 for(j = 0; j < LENGTH(tags) && !seltags[j]; j++);
1621 if(j == LENGTH(tags))
1622 seltags[i] = True; /* at least one tag must be viewed */
1630 XMoveWindow(dpy, c->win, c->x, c->y);
1631 c->isbanned = False;
1635 unmanage(Client *c) {
1638 wc.border_width = c->oldborder;
1639 /* The server grab construct avoids race conditions. */
1641 XSetErrorHandler(xerrordummy);
1642 XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
1647 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1648 setclientstate(c, WithdrawnState);
1652 XSetErrorHandler(xerror);
1658 unmapnotify(XEvent *e) {
1660 XUnmapEvent *ev = &e->xunmap;
1662 if((c = getclient(ev->window)))
1667 updatesizehints(Client *c) {
1671 if(!XGetWMNormalHints(dpy, c->win, &size, &msize) || !size.flags)
1673 c->flags = size.flags;
1674 if(c->flags & PBaseSize) {
1675 c->basew = size.base_width;
1676 c->baseh = size.base_height;
1678 else if(c->flags & PMinSize) {
1679 c->basew = size.min_width;
1680 c->baseh = size.min_height;
1683 c->basew = c->baseh = 0;
1684 if(c->flags & PResizeInc) {
1685 c->incw = size.width_inc;
1686 c->inch = size.height_inc;
1689 c->incw = c->inch = 0;
1690 if(c->flags & PMaxSize) {
1691 c->maxw = size.max_width;
1692 c->maxh = size.max_height;
1695 c->maxw = c->maxh = 0;
1696 if(c->flags & PMinSize) {
1697 c->minw = size.min_width;
1698 c->minh = size.min_height;
1700 else if(c->flags & PBaseSize) {
1701 c->minw = size.base_width;
1702 c->minh = size.base_height;
1705 c->minw = c->minh = 0;
1706 if(c->flags & PAspect) {
1707 c->minax = size.min_aspect.x;
1708 c->maxax = size.max_aspect.x;
1709 c->minay = size.min_aspect.y;
1710 c->maxay = size.max_aspect.y;
1713 c->minax = c->maxax = c->minay = c->maxay = 0;
1714 c->isfixed = (c->maxw && c->minw && c->maxh && c->minh
1715 && c->maxw == c->minw && c->maxh == c->minh);
1719 updatetitle(Client *c) {
1720 if(!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
1721 gettextprop(c->win, wmatom[WMName], c->name, sizeof c->name);
1725 updatewmhints(Client *c) {
1728 if((wmh = XGetWMHints(dpy, c->win))) {
1730 sel->isurgent = False;
1732 c->isurgent = (wmh->flags & XUrgencyHint) ? True : False;
1739 view(const char *arg) {
1742 for(i = 0; i < LENGTH(tags); i++)
1743 tmp[i] = (NULL == arg);
1744 tmp[idxoftag(arg)] = True;
1746 if(memcmp(seltags, tmp, TAGSZ) != 0) {
1747 memcpy(prevtags, seltags, TAGSZ);
1748 memcpy(seltags, tmp, TAGSZ);
1754 viewprevtag(const char *arg) {
1756 memcpy(tmp, seltags, TAGSZ);
1757 memcpy(seltags, prevtags, TAGSZ);
1758 memcpy(prevtags, tmp, TAGSZ);
1762 /* There's no way to check accesses to destroyed windows, thus those cases are
1763 * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
1764 * default error handler, which may call exit. */
1766 xerror(Display *dpy, XErrorEvent *ee) {
1767 if(ee->error_code == BadWindow
1768 || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1769 || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1770 || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1771 || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1772 || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1773 || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1774 || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1776 fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1777 ee->request_code, ee->error_code);
1778 return xerrorxlib(dpy, ee); /* may call exit */
1782 xerrordummy(Display *dpy, XErrorEvent *ee) {
1786 /* Startup Error handler to check if another window manager
1787 * is already running. */
1789 xerrorstart(Display *dpy, XErrorEvent *ee) {
1795 zoom(const char *arg) {
1798 if(!sel || !dozoom || sel->isfloating)
1800 if(c == nexttiled(clients))
1801 if(!(c = nexttiled(c->next)))
1810 main(int argc, char *argv[]) {
1811 if(argc == 2 && !strcmp("-v", argv[1]))
1812 eprint("dwm-"VERSION", © 2006-2008 dwm engineers, see LICENSE for details\n");
1814 eprint("usage: dwm [-v]\n");
1816 setlocale(LC_CTYPE, "");
1817 if(!(dpy = XOpenDisplay(0)))
1818 eprint("dwm: cannot open display\n");