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
9 /* See LICENSE file for copyright and license details.
11 * dynamic window manager is designed like any other X client as well. It is
12 * driven through handling X events. In contrast to other X clients, a window
13 * manager selects for SubstructureRedirectMask on the root window, to receive
14 * events about window (dis-)appearance. Only one X connection at a time is
15 * allowed to select for this event mask.
17 * Calls to fetch an X event from the event queue are blocking. Due reading
18 * status text from standard input, a select()-driven main loop has been
19 * implemented which selects for reads on the X connection and STDIN_FILENO to
20 * handle all data smoothly. The event handlers of dwm are organized in an
21 * array which is accessed whenever a new event has been fetched. This allows
22 * event dispatching in O(1) time.
24 * Each child of the root window is called a client, except windows which have
25 * set the override_redirect flag. Clients are organized in a global
26 * doubly-linked client list, the focus history is remembered through a global
27 * stack list. Each client contains an array of Bools of the same size as the
28 * global tags array to indicate the tags of a client.
30 * Keys and tagging rules are organized as arrays and defined in config.h.
32 * To understand everything else, start reading main().
41 #include <sys/select.h>
42 #include <sys/types.h>
45 #include <X11/cursorfont.h>
46 #include <X11/keysym.h>
47 #include <X11/Xatom.h>
49 #include <X11/Xproto.h>
50 #include <X11/Xutil.h>
53 #define BUTTONMASK (ButtonPressMask|ButtonReleaseMask)
54 #define CLEANMASK(mask) (mask & ~(numlockmask|LockMask))
55 #define LENGTH(x) (sizeof x / sizeof x[0])
57 #define MOUSEMASK (BUTTONMASK|PointerMotionMask)
60 enum { CurNormal, CurResize, CurMove, CurLast }; /* cursor */
61 enum { ColBorder, ColFG, ColBG, ColLast }; /* color */
62 enum { NetSupported, NetWMName, NetLast }; /* EWMH atoms */
63 enum { WMProtocols, WMDelete, WMName, WMState, WMLast };/* default atoms */
66 typedef struct Client Client;
71 int basew, baseh, incw, inch, maxw, maxh, minw, minh;
72 int minax, maxax, minay, maxay;
74 unsigned int border, oldborder;
75 Bool isbanned, isfixed, isfloating, isurgent;
85 unsigned long norm[ColLast];
86 unsigned long sel[ColLast];
96 } DC; /* draw context */
101 void (*func)(const char *arg);
107 void (*arrange)(void);
116 /* function declarations */
117 void applyrules(Client *c);
119 void attach(Client *c);
120 void attachstack(Client *c);
122 void buttonpress(XEvent *e);
123 void checkotherwm(void);
125 void configure(Client *c);
126 void configurenotify(XEvent *e);
127 void configurerequest(XEvent *e);
128 void destroynotify(XEvent *e);
129 void detach(Client *c);
130 void detachstack(Client *c);
132 void drawsquare(Bool filled, Bool empty, Bool invert, unsigned long col[ColLast]);
133 void drawtext(const char *text, unsigned long col[ColLast], Bool invert);
134 void *emallocz(unsigned int size);
135 void enternotify(XEvent *e);
136 void eprint(const char *errstr, ...);
137 void expose(XEvent *e);
138 void floating(void); /* default floating layout */
139 void focus(Client *c);
140 void focusin(XEvent *e);
141 void focusnext(const char *arg);
142 void focusprev(const char *arg);
143 Client *getclient(Window w);
144 unsigned long getcolor(const char *colstr);
145 long getstate(Window w);
146 Bool gettextprop(Window w, Atom atom, char *text, unsigned int size);
147 void grabbuttons(Client *c, Bool focused);
149 unsigned int idxoftag(const char *t);
150 void initfont(const char *fontstr);
151 Bool isoccupied(unsigned int t);
152 Bool isprotodel(Client *c);
153 Bool isurgent(unsigned int t);
154 Bool isvisible(Client *c);
155 void keypress(XEvent *e);
156 void killclient(const char *arg);
157 void manage(Window w, XWindowAttributes *wa);
158 void mappingnotify(XEvent *e);
159 void maprequest(XEvent *e);
161 void movemouse(Client *c);
162 Client *nexttiled(Client *c);
163 void propertynotify(XEvent *e);
164 void quit(const char *arg);
165 void reapply(const char *arg);
166 void resize(Client *c, int x, int y, int w, int h, Bool sizehints);
167 void resizemouse(Client *c);
171 void setclientstate(Client *c, long state);
172 void setlayout(const char *arg);
174 void spawn(const char *arg);
175 void tag(const char *arg);
176 unsigned int textnw(const char *text, unsigned int len);
177 unsigned int textw(const char *text);
179 void togglefloating(const char *arg);
180 void toggletag(const char *arg);
181 void toggleview(const char *arg);
182 void unban(Client *c);
183 void unmanage(Client *c);
184 void unmapnotify(XEvent *e);
185 void updatesizehints(Client *c);
186 void updatetitle(Client *c);
187 void updatewmhints(Client *c);
188 void view(const char *arg);
189 void viewprevtag(const char *arg); /* views previous selected tags */
190 int xerror(Display *dpy, XErrorEvent *ee);
191 int xerrordummy(Display *dpy, XErrorEvent *ee);
192 int xerrorstart(Display *dpy, XErrorEvent *ee);
193 void zoom(const char *arg);
196 char stext[256], buf[256];
197 int screen, sx, sy, sw, sh;
198 int (*xerrorxlib)(Display *, XErrorEvent *);
199 unsigned int bh, blw = 0;
200 unsigned int 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;
221 Client *clients = NULL;
223 Client *stack = NULL;
224 Cursor cursor[CurLast];
230 /* configuration, allows nested code to access above variables */
232 #define TAGSZ (LENGTH(tags) * sizeof(Bool))
233 static Bool tmp[LENGTH(tags)];
235 /* function implementations */
238 applyrules(Client *c) {
240 Bool matched = False;
242 XClassHint ch = { 0 };
245 XGetClassHint(dpy, c->win, &ch);
246 for(i = 0; i < LENGTH(rules); i++) {
248 if(strstr(c->name, r->prop)
249 || (ch.res_class && strstr(ch.res_class, r->prop))
250 || (ch.res_name && strstr(ch.res_name, r->prop)))
252 c->isfloating = r->isfloating;
254 c->tags[idxoftag(r->tag)] = True;
264 memcpy(c->tags, seltags, TAGSZ);
271 for(c = clients; c; c = c->next)
291 attachstack(Client *c) {
300 XMoveWindow(dpy, c->win, c->x + 3 * sw, c->y);
305 buttonpress(XEvent *e) {
308 XButtonPressedEvent *ev = &e->xbutton;
310 if(ev->window == barwin) {
312 for(i = 0; i < LENGTH(tags); i++) {
315 if(ev->button == Button1) {
316 if(ev->state & MODKEY)
321 else if(ev->button == Button3) {
322 if(ev->state & MODKEY)
331 else if((c = getclient(ev->window))) {
333 if(CLEANMASK(ev->state) != MODKEY)
335 if(ev->button == Button1) {
339 else if(ev->button == Button2) {
340 if((floating != lt->arrange) && c->isfloating)
341 togglefloating(NULL);
345 else if(ev->button == Button3 && !c->isfixed) {
355 XSetErrorHandler(xerrorstart);
357 /* this causes an error if some other window manager is running */
358 XSelectInput(dpy, DefaultRootWindow(dpy), SubstructureRedirectMask);
361 eprint("dwm: another window manager is already running\n");
363 XSetErrorHandler(NULL);
364 xerrorxlib = XSetErrorHandler(xerror);
376 XFreeFontSet(dpy, dc.font.set);
378 XFreeFont(dpy, dc.font.xfont);
379 XUngrabKey(dpy, AnyKey, AnyModifier, root);
380 XFreePixmap(dpy, dc.drawable);
382 XFreeCursor(dpy, cursor[CurNormal]);
383 XFreeCursor(dpy, cursor[CurResize]);
384 XFreeCursor(dpy, cursor[CurMove]);
385 XDestroyWindow(dpy, barwin);
387 XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime);
391 configure(Client *c) {
394 ce.type = ConfigureNotify;
402 ce.border_width = c->border;
404 ce.override_redirect = False;
405 XSendEvent(dpy, c->win, False, StructureNotifyMask, (XEvent *)&ce);
409 configurenotify(XEvent *e) {
410 XConfigureEvent *ev = &e->xconfigure;
412 if(ev->window == root && (ev->width != sw || ev->height != sh)) {
415 XFreePixmap(dpy, dc.drawable);
416 dc.drawable = XCreatePixmap(dpy, root, BW, bh, DefaultDepth(dpy, screen));
417 XMoveResizeWindow(dpy, barwin, BX, BY, BW, bh);
423 configurerequest(XEvent *e) {
425 XConfigureRequestEvent *ev = &e->xconfigurerequest;
428 if((c = getclient(ev->window))) {
429 if(ev->value_mask & CWBorderWidth)
430 c->border = ev->border_width;
431 if(c->isfixed || c->isfloating || (floating == lt->arrange)) {
432 if(ev->value_mask & CWX)
434 if(ev->value_mask & CWY)
436 if(ev->value_mask & CWWidth)
438 if(ev->value_mask & CWHeight)
440 if((c->x - sx + c->w) > sw && c->isfloating)
441 c->x = sx + (sw / 2 - c->w / 2); /* center in x direction */
442 if((c->y - sy + c->h) > sh && c->isfloating)
443 c->y = sy + (sh / 2 - c->h / 2); /* center in y direction */
444 if((ev->value_mask & (CWX|CWY))
445 && !(ev->value_mask & (CWWidth|CWHeight)))
448 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h);
456 wc.width = ev->width;
457 wc.height = ev->height;
458 wc.border_width = ev->border_width;
459 wc.sibling = ev->above;
460 wc.stack_mode = ev->detail;
461 XConfigureWindow(dpy, ev->window, ev->value_mask, &wc);
467 destroynotify(XEvent *e) {
469 XDestroyWindowEvent *ev = &e->xdestroywindow;
471 if((c = getclient(ev->window)))
478 c->prev->next = c->next;
480 c->next->prev = c->prev;
483 c->next = c->prev = NULL;
487 detachstack(Client *c) {
490 for(tc=&stack; *tc && *tc != c; tc=&(*tc)->snext);
500 for(c = stack; c && !isvisible(c); c = c->snext);
501 for(i = 0; i < LENGTH(tags); i++) {
502 dc.w = textw(tags[i]);
504 drawtext(tags[i], dc.sel, isurgent(i));
505 drawsquare(c && c->tags[i], isoccupied(i), isurgent(i), dc.sel);
508 drawtext(tags[i], dc.norm, isurgent(i));
509 drawsquare(c && c->tags[i], isoccupied(i), isurgent(i), dc.norm);
514 drawtext(lt->symbol, dc.norm, False);
522 drawtext(stext, dc.norm, False);
523 if((dc.w = dc.x - x) > bh) {
526 drawtext(c->name, dc.sel, False);
527 drawsquare(False, c->isfloating, False, dc.sel);
530 drawtext(NULL, dc.norm, False);
532 XCopyArea(dpy, dc.drawable, barwin, dc.gc, 0, 0, BW, bh, 0, 0);
537 drawsquare(Bool filled, Bool empty, Bool invert, unsigned long col[ColLast]) {
540 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
542 gcv.foreground = col[invert ? ColBG : ColFG];
543 XChangeGC(dpy, dc.gc, GCForeground, &gcv);
544 x = (dc.font.ascent + dc.font.descent + 2) / 4;
548 r.width = r.height = x + 1;
549 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
552 r.width = r.height = x;
553 XDrawRectangles(dpy, dc.drawable, dc.gc, &r, 1);
558 drawtext(const char *text, unsigned long col[ColLast], Bool invert) {
560 unsigned int len, olen;
561 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
563 XSetForeground(dpy, dc.gc, col[invert ? ColFG : ColBG]);
564 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
568 olen = len = strlen(text);
569 if(len >= sizeof buf)
570 len = sizeof buf - 1;
571 memcpy(buf, text, len);
573 h = dc.font.ascent + dc.font.descent;
574 y = dc.y + (dc.h / 2) - (h / 2) + dc.font.ascent;
576 /* shorten text if necessary */
577 while(len && (w = textnw(buf, len)) > dc.w - h)
588 return; /* too long */
589 XSetForeground(dpy, dc.gc, col[invert ? ColBG : ColFG]);
591 XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
593 XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
597 emallocz(unsigned int size) {
598 void *res = calloc(1, size);
601 eprint("fatal: could not malloc() %u bytes\n", size);
606 enternotify(XEvent *e) {
608 XCrossingEvent *ev = &e->xcrossing;
610 if((ev->mode != NotifyNormal || ev->detail == NotifyInferior) && ev->window != root)
612 if((c = getclient(ev->window)))
619 eprint(const char *errstr, ...) {
622 va_start(ap, errstr);
623 vfprintf(stderr, errstr, ap);
630 XExposeEvent *ev = &e->xexpose;
632 if(ev->count == 0 && (ev->window == barwin))
637 floating(void) { /* default floating layout */
641 for(c = clients; c; c = c->next)
643 resize(c, c->x, c->y, c->w, c->h, True);
648 if(!c || (c && !isvisible(c)))
649 for(c = stack; c && !isvisible(c); c = c->snext);
650 if(sel && sel != c) {
651 grabbuttons(sel, False);
652 XSetWindowBorder(dpy, sel->win, dc.norm[ColBorder]);
653 if(lt->arrange == monocle)
654 resize(sel, sel->rx, sel->ry, sel->rw, sel->rh, True);
659 grabbuttons(c, True);
660 if(lt->arrange == monocle) {
667 resize(c, MOX, MOY, MOW, MOH, RESIZEHINTS);
672 XSetWindowBorder(dpy, c->win, dc.sel[ColBorder]);
673 XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
676 XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
681 focusin(XEvent *e) { /* there are some broken focus acquiring clients */
682 XFocusChangeEvent *ev = &e->xfocus;
684 if(sel && ev->window != sel->win)
685 XSetInputFocus(dpy, sel->win, RevertToPointerRoot, CurrentTime);
689 focusnext(const char *arg) {
694 for(c = sel->next; c && !isvisible(c); c = c->next);
696 for(c = clients; c && !isvisible(c); c = c->next);
704 focusprev(const char *arg) {
709 for(c = sel->prev; c && !isvisible(c); c = c->prev);
711 for(c = clients; c && c->next; c = c->next);
712 for(; c && !isvisible(c); c = c->prev);
721 getclient(Window w) {
724 for(c = clients; c && c->win != w; c = c->next);
729 getcolor(const char *colstr) {
730 Colormap cmap = DefaultColormap(dpy, screen);
733 if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
734 eprint("error, cannot allocate color '%s'\n", colstr);
742 unsigned char *p = NULL;
743 unsigned long n, extra;
746 status = XGetWindowProperty(dpy, w, wmatom[WMState], 0L, 2L, False, wmatom[WMState],
747 &real, &format, &n, &extra, (unsigned char **)&p);
748 if(status != Success)
757 gettextprop(Window w, Atom atom, char *text, unsigned int size) {
762 if(!text || size == 0)
765 XGetTextProperty(dpy, w, &name, atom);
768 if(name.encoding == XA_STRING)
769 strncpy(text, (char *)name.value, size - 1);
771 if(XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success
773 strncpy(text, *list, size - 1);
774 XFreeStringList(list);
777 text[size - 1] = '\0';
783 grabbuttons(Client *c, Bool focused) {
784 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
787 XGrabButton(dpy, Button1, MODKEY, c->win, False, BUTTONMASK,
788 GrabModeAsync, GrabModeSync, None, None);
789 XGrabButton(dpy, Button1, MODKEY|LockMask, c->win, False, BUTTONMASK,
790 GrabModeAsync, GrabModeSync, None, None);
791 XGrabButton(dpy, Button1, MODKEY|numlockmask, c->win, False, BUTTONMASK,
792 GrabModeAsync, GrabModeSync, None, None);
793 XGrabButton(dpy, Button1, MODKEY|numlockmask|LockMask, c->win, False, BUTTONMASK,
794 GrabModeAsync, GrabModeSync, None, None);
796 XGrabButton(dpy, Button2, MODKEY, c->win, False, BUTTONMASK,
797 GrabModeAsync, GrabModeSync, None, None);
798 XGrabButton(dpy, Button2, MODKEY|LockMask, c->win, False, BUTTONMASK,
799 GrabModeAsync, GrabModeSync, None, None);
800 XGrabButton(dpy, Button2, MODKEY|numlockmask, c->win, False, BUTTONMASK,
801 GrabModeAsync, GrabModeSync, None, None);
802 XGrabButton(dpy, Button2, MODKEY|numlockmask|LockMask, c->win, False, BUTTONMASK,
803 GrabModeAsync, GrabModeSync, None, None);
805 XGrabButton(dpy, Button3, MODKEY, c->win, False, BUTTONMASK,
806 GrabModeAsync, GrabModeSync, None, None);
807 XGrabButton(dpy, Button3, MODKEY|LockMask, c->win, False, BUTTONMASK,
808 GrabModeAsync, GrabModeSync, None, None);
809 XGrabButton(dpy, Button3, MODKEY|numlockmask, c->win, False, BUTTONMASK,
810 GrabModeAsync, GrabModeSync, None, None);
811 XGrabButton(dpy, Button3, MODKEY|numlockmask|LockMask, c->win, False, BUTTONMASK,
812 GrabModeAsync, GrabModeSync, None, None);
815 XGrabButton(dpy, AnyButton, AnyModifier, c->win, False, BUTTONMASK,
816 GrabModeAsync, GrabModeSync, None, None);
823 XModifierKeymap *modmap;
825 /* init modifier map */
826 modmap = XGetModifierMapping(dpy);
827 for(i = 0; i < 8; i++)
828 for(j = 0; j < modmap->max_keypermod; j++) {
829 if(modmap->modifiermap[i * modmap->max_keypermod + j] == XKeysymToKeycode(dpy, XK_Num_Lock))
830 numlockmask = (1 << i);
832 XFreeModifiermap(modmap);
834 XUngrabKey(dpy, AnyKey, AnyModifier, root);
835 for(i = 0; i < LENGTH(keys); i++) {
836 code = XKeysymToKeycode(dpy, keys[i].keysym);
837 XGrabKey(dpy, code, keys[i].mod, root, True,
838 GrabModeAsync, GrabModeAsync);
839 XGrabKey(dpy, code, keys[i].mod|LockMask, root, True,
840 GrabModeAsync, GrabModeAsync);
841 XGrabKey(dpy, code, keys[i].mod|numlockmask, root, True,
842 GrabModeAsync, GrabModeAsync);
843 XGrabKey(dpy, code, keys[i].mod|numlockmask|LockMask, root, True,
844 GrabModeAsync, GrabModeAsync);
849 idxoftag(const char *t) {
852 for(i = 0; (i < LENGTH(tags)) && (tags[i] != t); i++);
853 return (i < LENGTH(tags)) ? i : 0;
857 initfont(const char *fontstr) {
858 char *def, **missing;
863 XFreeFontSet(dpy, dc.font.set);
864 dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
867 fprintf(stderr, "dwm: missing fontset: %s\n", missing[n]);
868 XFreeStringList(missing);
871 XFontSetExtents *font_extents;
872 XFontStruct **xfonts;
874 dc.font.ascent = dc.font.descent = 0;
875 font_extents = XExtentsOfFontSet(dc.font.set);
876 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
877 for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
878 if(dc.font.ascent < (*xfonts)->ascent)
879 dc.font.ascent = (*xfonts)->ascent;
880 if(dc.font.descent < (*xfonts)->descent)
881 dc.font.descent = (*xfonts)->descent;
887 XFreeFont(dpy, dc.font.xfont);
888 dc.font.xfont = NULL;
889 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr))
890 && !(dc.font.xfont = XLoadQueryFont(dpy, "fixed")))
891 eprint("error, cannot load font: '%s'\n", fontstr);
892 dc.font.ascent = dc.font.xfont->ascent;
893 dc.font.descent = dc.font.xfont->descent;
895 dc.font.height = dc.font.ascent + dc.font.descent;
899 isoccupied(unsigned int t) {
902 for(c = clients; c; c = c->next)
909 isprotodel(Client *c) {
914 if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
915 for(i = 0; !ret && i < n; i++)
916 if(protocols[i] == wmatom[WMDelete])
924 isurgent(unsigned int t) {
927 for(c = clients; c; c = c->next)
928 if(c->isurgent && c->tags[t])
934 isvisible(Client *c) {
937 for(i = 0; i < LENGTH(tags); i++)
938 if(c->tags[i] && seltags[i])
944 keypress(XEvent *e) {
950 keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
951 for(i = 0; i < LENGTH(keys); i++)
952 if(keysym == keys[i].keysym
953 && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state))
956 keys[i].func(keys[i].arg);
961 killclient(const char *arg) {
966 if(isprotodel(sel)) {
967 ev.type = ClientMessage;
968 ev.xclient.window = sel->win;
969 ev.xclient.message_type = wmatom[WMProtocols];
970 ev.xclient.format = 32;
971 ev.xclient.data.l[0] = wmatom[WMDelete];
972 ev.xclient.data.l[1] = CurrentTime;
973 XSendEvent(dpy, sel->win, False, NoEventMask, &ev);
976 XKillClient(dpy, sel->win);
980 manage(Window w, XWindowAttributes *wa) {
981 Client *c, *t = NULL;
986 c = emallocz(sizeof(Client));
987 c->tags = emallocz(TAGSZ);
990 c->x = c->rx = wa->x + sx;
991 c->y = c->ry = wa->y + sy;
992 c->w = c->rw = wa->width;
993 c->h = c->rh = wa->height;
994 c->oldborder = wa->border_width;
996 if(c->w == sw && c->h == sh) {
999 c->border = wa->border_width;
1002 if(c->x + c->w + 2 * c->border > sx + sw)
1003 c->x = sx + sw - c->w - 2 * c->border;
1004 if(c->y + c->h + 2 * c->border > sy + sh)
1005 c->y = sy + sh - c->h - 2 * c->border;
1010 c->border = BORDERPX;
1012 wc.border_width = c->border;
1013 XConfigureWindow(dpy, w, CWBorderWidth, &wc);
1014 XSetWindowBorder(dpy, w, dc.norm[ColBorder]);
1015 configure(c); /* propagates border_width, if size doesn't change */
1017 XSelectInput(dpy, w, EnterWindowMask|FocusChangeMask|PropertyChangeMask|StructureNotifyMask);
1018 grabbuttons(c, False);
1020 if((rettrans = XGetTransientForHint(dpy, w, &trans) == Success))
1021 for(t = clients; t && t->win != trans; t = t->next);
1023 memcpy(c->tags, t->tags, TAGSZ);
1027 c->isfloating = (rettrans == Success) || c->isfixed;
1030 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h); /* some windows require this */
1032 XMapWindow(dpy, c->win);
1033 setclientstate(c, NormalState);
1038 mappingnotify(XEvent *e) {
1039 XMappingEvent *ev = &e->xmapping;
1041 XRefreshKeyboardMapping(ev);
1042 if(ev->request == MappingKeyboard)
1047 maprequest(XEvent *e) {
1048 static XWindowAttributes wa;
1049 XMapRequestEvent *ev = &e->xmaprequest;
1051 if(!XGetWindowAttributes(dpy, ev->window, &wa))
1053 if(wa.override_redirect)
1055 if(!getclient(ev->window))
1056 manage(ev->window, &wa);
1065 movemouse(Client *c) {
1066 int x1, y1, ocx, ocy, di, nx, ny;
1073 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1074 None, cursor[CurMove], CurrentTime) != GrabSuccess)
1076 XQueryPointer(dpy, root, &dummy, &dummy, &x1, &y1, &di, &di, &dui);
1078 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
1081 XUngrabPointer(dpy, CurrentTime);
1083 case ConfigureRequest:
1086 handler[ev.type](&ev);
1090 nx = ocx + (ev.xmotion.x - x1);
1091 ny = ocy + (ev.xmotion.y - y1);
1092 if(abs(sx - nx) < SNAP)
1094 else if(abs((sx + sw) - (nx + c->w + 2 * c->border)) < SNAP)
1095 nx = sx + sw - c->w - 2 * c->border;
1096 if(abs(sy - ny) < SNAP)
1098 else if(abs((sy + sh) - (ny + c->h + 2 * c->border)) < SNAP)
1099 ny = sy + sh - c->h - 2 * c->border;
1100 if(!c->isfloating && (lt->arrange != floating) && (abs(nx - c->x) > SNAP || abs(ny - c->y) > SNAP))
1101 togglefloating(NULL);
1102 if((lt->arrange == floating) || c->isfloating)
1103 resize(c, nx, ny, c->w, c->h, False);
1110 nexttiled(Client *c) {
1111 for(; c && (c->isfloating || !isvisible(c)); c = c->next);
1116 propertynotify(XEvent *e) {
1119 XPropertyEvent *ev = &e->xproperty;
1121 if(ev->state == PropertyDelete)
1122 return; /* ignore */
1123 if((c = getclient(ev->window))) {
1126 case XA_WM_TRANSIENT_FOR:
1127 XGetTransientForHint(dpy, c->win, &trans);
1128 if(!c->isfloating && (c->isfloating = (getclient(trans) != NULL)))
1131 case XA_WM_NORMAL_HINTS:
1139 if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
1148 quit(const char *arg) {
1149 readin = running = False;
1153 reapply(const char *arg) {
1154 static Bool zerotags[LENGTH(tags)] = { 0 };
1157 for(c = clients; c; c = c->next) {
1158 memcpy(c->tags, zerotags, sizeof zerotags);
1165 resize(Client *c, int x, int y, int w, int h, Bool sizehints) {
1169 /* set minimum possible */
1175 /* temporarily remove base dimensions */
1179 /* adjust for aspect limits */
1180 if (c->minay > 0 && c->maxay > 0 && c->minax > 0 && c->maxax > 0) {
1181 if (w * c->maxay > h * c->maxax)
1182 w = h * c->maxax / c->maxay;
1183 else if (w * c->minay < h * c->minax)
1184 h = w * c->minay / c->minax;
1187 /* adjust for increment value */
1193 /* restore base dimensions */
1197 if(c->minw > 0 && w < c->minw)
1199 if(c->minh > 0 && h < c->minh)
1201 if(c->maxw > 0 && w > c->maxw)
1203 if(c->maxh > 0 && h > c->maxh)
1206 if(w <= 0 || h <= 0)
1209 x = sw - w - 2 * c->border;
1211 y = sh - h - 2 * c->border;
1212 if(x + w + 2 * c->border < sx)
1214 if(y + h + 2 * c->border < sy)
1216 if(c->x != x || c->y != y || c->w != w || c->h != h) {
1219 c->w = wc.width = w;
1220 c->h = wc.height = h;
1221 wc.border_width = c->border;
1222 XConfigureWindow(dpy, c->win,
1223 CWX|CWY|CWWidth|CWHeight|CWBorderWidth, &wc);
1230 resizemouse(Client *c) {
1237 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1238 None, cursor[CurResize], CurrentTime) != GrabSuccess)
1240 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->border - 1, c->h + c->border - 1);
1242 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask , &ev);
1245 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0,
1246 c->w + c->border - 1, c->h + c->border - 1);
1247 XUngrabPointer(dpy, CurrentTime);
1248 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1250 case ConfigureRequest:
1253 handler[ev.type](&ev);
1257 if((nw = ev.xmotion.x - ocx - 2 * c->border + 1) <= 0)
1259 if((nh = ev.xmotion.y - ocy - 2 * c->border + 1) <= 0)
1261 if(!c->isfloating && (lt->arrange != floating) && (abs(nw - c->w) > SNAP || abs(nh - c->h) > SNAP))
1262 togglefloating(NULL);
1263 if((lt->arrange == floating) || c->isfloating)
1264 resize(c, c->x, c->y, nw, nh, True);
1279 if(sel->isfloating || (lt->arrange == floating))
1280 XRaiseWindow(dpy, sel->win);
1281 if(lt->arrange != floating) {
1282 wc.stack_mode = Below;
1283 wc.sibling = barwin;
1284 if(!sel->isfloating) {
1285 XConfigureWindow(dpy, sel->win, CWSibling|CWStackMode, &wc);
1286 wc.sibling = sel->win;
1288 for(c = nexttiled(clients); c; c = nexttiled(c->next)) {
1291 XConfigureWindow(dpy, c->win, CWSibling|CWStackMode, &wc);
1292 wc.sibling = c->win;
1296 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1302 char sbuf[sizeof stext];
1305 unsigned int len, offset;
1308 /* main event loop, also reads status text from stdin */
1310 xfd = ConnectionNumber(dpy);
1313 len = sizeof stext - 1;
1314 sbuf[len] = stext[len] = '\0'; /* 0-terminator is never touched */
1318 FD_SET(STDIN_FILENO, &rd);
1320 if(select(xfd + 1, &rd, NULL, NULL, NULL) == -1) {
1323 eprint("select failed\n");
1325 if(FD_ISSET(STDIN_FILENO, &rd)) {
1326 switch((r = read(STDIN_FILENO, sbuf + offset, len - offset))) {
1328 strncpy(stext, strerror(errno), len);
1332 strncpy(stext, "EOF", 4);
1336 for(p = sbuf + offset; r > 0; p++, r--, offset++)
1337 if(*p == '\n' || *p == '\0') {
1339 strncpy(stext, sbuf, len);
1340 p += r - 1; /* p is sbuf + offset + r - 1 */
1341 for(r = 0; *(p - r) && *(p - r) != '\n'; r++);
1344 memmove(sbuf, p - r + 1, r);
1351 while(XPending(dpy)) {
1352 XNextEvent(dpy, &ev);
1353 if(handler[ev.type])
1354 (handler[ev.type])(&ev); /* call handler */
1361 unsigned int i, num;
1362 Window *wins, d1, d2;
1363 XWindowAttributes wa;
1366 if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1367 for(i = 0; i < num; i++) {
1368 if(!XGetWindowAttributes(dpy, wins[i], &wa)
1369 || wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1371 if(wa.map_state == IsViewable || getstate(wins[i]) == IconicState)
1372 manage(wins[i], &wa);
1374 for(i = 0; i < num; i++) { /* now the transients */
1375 if(!XGetWindowAttributes(dpy, wins[i], &wa))
1377 if(XGetTransientForHint(dpy, wins[i], &d1)
1378 && (wa.map_state == IsViewable || getstate(wins[i]) == IconicState))
1379 manage(wins[i], &wa);
1387 setclientstate(Client *c, long state) {
1388 long data[] = {state, None};
1390 XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1391 PropModeReplace, (unsigned char *)data, 2);
1395 setlayout(const char *arg) {
1400 for(i = 0; i < LENGTH(layouts); i++)
1401 if(!strcmp(arg, layouts[i].symbol))
1403 if(i == LENGTH(layouts))
1415 XSetWindowAttributes wa;
1418 screen = DefaultScreen(dpy);
1419 root = RootWindow(dpy, screen);
1422 sw = DisplayWidth(dpy, screen);
1423 sh = DisplayHeight(dpy, screen);
1426 wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1427 wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1428 wmatom[WMName] = XInternAtom(dpy, "WM_NAME", False);
1429 wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1430 netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1431 netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1434 wa.cursor = cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1435 cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1436 cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1438 /* init appearance */
1439 dc.norm[ColBorder] = getcolor(NORMBORDERCOLOR);
1440 dc.norm[ColBG] = getcolor(NORMBGCOLOR);
1441 dc.norm[ColFG] = getcolor(NORMFGCOLOR);
1442 dc.sel[ColBorder] = getcolor(SELBORDERCOLOR);
1443 dc.sel[ColBG] = getcolor(SELBGCOLOR);
1444 dc.sel[ColFG] = getcolor(SELFGCOLOR);
1446 dc.h = bh = dc.font.height + 2;
1447 dc.drawable = XCreatePixmap(dpy, root, DisplayWidth(dpy, screen), bh, DefaultDepth(dpy, screen));
1448 dc.gc = XCreateGC(dpy, root, 0, 0);
1449 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
1451 XSetFont(dpy, dc.gc, dc.font.xfont->fid);
1454 seltags = emallocz(TAGSZ);
1455 prevtags = emallocz(TAGSZ);
1456 seltags[0] = prevtags[0] = True;
1462 for(blw = i = 0; i < LENGTH(layouts); i++) {
1463 i = textw(layouts[i].symbol);
1468 wa.override_redirect = 1;
1469 wa.background_pixmap = ParentRelative;
1470 wa.event_mask = ButtonPressMask|ExposureMask;
1472 barwin = XCreateWindow(dpy, root, BX, BY, BW, bh, 0, DefaultDepth(dpy, screen),
1473 CopyFromParent, DefaultVisual(dpy, screen),
1474 CWOverrideRedirect|CWBackPixmap|CWEventMask, &wa);
1475 XDefineCursor(dpy, barwin, cursor[CurNormal]);
1476 XMapRaised(dpy, barwin);
1477 strcpy(stext, "dwm-"VERSION);
1480 /* EWMH support per view */
1481 XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1482 PropModeReplace, (unsigned char *) netatom, NetLast);
1484 /* select for events */
1485 wa.event_mask = SubstructureRedirectMask|SubstructureNotifyMask
1486 |EnterWindowMask|LeaveWindowMask|StructureNotifyMask;
1487 XChangeWindowAttributes(dpy, root, CWEventMask|CWCursor, &wa);
1488 XSelectInput(dpy, root, wa.event_mask);
1496 spawn(const char *arg) {
1497 static char *shell = NULL;
1499 if(!shell && !(shell = getenv("SHELL")))
1503 /* The double-fork construct avoids zombie processes and keeps the code
1504 * clean from stupid signal handlers. */
1508 close(ConnectionNumber(dpy));
1510 execl(shell, shell, "-c", arg, (char *)NULL);
1511 fprintf(stderr, "dwm: execl '%s -c %s'", shell, arg);
1520 tag(const char *arg) {
1525 for(i = 0; i < LENGTH(tags); i++)
1526 sel->tags[i] = (NULL == arg);
1527 sel->tags[idxoftag(arg)] = True;
1532 textnw(const char *text, unsigned int len) {
1536 XmbTextExtents(dc.font.set, text, len, NULL, &r);
1539 return XTextWidth(dc.font.xfont, text, len);
1543 textw(const char *text) {
1544 return textnw(text, strlen(text)) + dc.font.height;
1549 unsigned int i, n, nx, ny, nw, nh, mw, th;
1556 for(n = 0, c = nexttiled(clients); c; c = nexttiled(c->next))
1560 mw = (n == 1) ? MOW : MW;
1561 th = (n > 1) ? TH / (n - 1) : 0;
1562 if(n > 1 && th < bh)
1565 for(i = 0, c = mc = nexttiled(clients); c; c = nexttiled(c->next)) {
1566 if(i == 0) { /* master */
1567 nw = mw - 2 * c->border;
1568 nh = MH - 2 * c->border;
1570 else { /* tile window */
1574 nw = TW - 2 * c->border;
1576 if(i + 1 == n) /* remainder */
1577 nh = (TY + TH) - ny - 2 * c->border;
1579 nh = th - 2 * c->border;
1581 resize(c, nx, ny, nw, nh, RESIZEHINTS);
1582 if((RESIZEHINTS) && ((c->h < bh) || (c->h > nh) || (c->w < bh) || (c->w > nw)))
1583 /* client doesn't accept size constraints */
1584 resize(c, nx, ny, nw, nh, False);
1585 if(n > 1 && th != TH)
1586 ny = c->y + c->h + 2 * c->border;
1592 togglefloating(const char *arg) {
1595 sel->isfloating = !sel->isfloating;
1597 resize(sel, sel->x, sel->y, sel->w, sel->h, True);
1602 toggletag(const char *arg) {
1608 sel->tags[i] = !sel->tags[i];
1609 for(j = 0; j < LENGTH(tags) && !sel->tags[j]; j++);
1610 if(j == LENGTH(tags))
1611 sel->tags[i] = True; /* at least one tag must be enabled */
1616 toggleview(const char *arg) {
1620 seltags[i] = !seltags[i];
1621 for(j = 0; j < LENGTH(tags) && !seltags[j]; j++);
1622 if(j == LENGTH(tags))
1623 seltags[i] = True; /* at least one tag must be viewed */
1631 XMoveWindow(dpy, c->win, c->x, c->y);
1632 c->isbanned = False;
1636 unmanage(Client *c) {
1639 wc.border_width = c->oldborder;
1640 /* The server grab construct avoids race conditions. */
1642 XSetErrorHandler(xerrordummy);
1643 XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
1648 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1649 setclientstate(c, WithdrawnState);
1653 XSetErrorHandler(xerror);
1659 unmapnotify(XEvent *e) {
1661 XUnmapEvent *ev = &e->xunmap;
1663 if((c = getclient(ev->window)))
1668 updatesizehints(Client *c) {
1672 if(!XGetWMNormalHints(dpy, c->win, &size, &msize) || !size.flags)
1674 c->flags = size.flags;
1675 if(c->flags & PBaseSize) {
1676 c->basew = size.base_width;
1677 c->baseh = size.base_height;
1679 else if(c->flags & PMinSize) {
1680 c->basew = size.min_width;
1681 c->baseh = size.min_height;
1684 c->basew = c->baseh = 0;
1685 if(c->flags & PResizeInc) {
1686 c->incw = size.width_inc;
1687 c->inch = size.height_inc;
1690 c->incw = c->inch = 0;
1691 if(c->flags & PMaxSize) {
1692 c->maxw = size.max_width;
1693 c->maxh = size.max_height;
1696 c->maxw = c->maxh = 0;
1697 if(c->flags & PMinSize) {
1698 c->minw = size.min_width;
1699 c->minh = size.min_height;
1701 else if(c->flags & PBaseSize) {
1702 c->minw = size.base_width;
1703 c->minh = size.base_height;
1706 c->minw = c->minh = 0;
1707 if(c->flags & PAspect) {
1708 c->minax = size.min_aspect.x;
1709 c->maxax = size.max_aspect.x;
1710 c->minay = size.min_aspect.y;
1711 c->maxay = size.max_aspect.y;
1714 c->minax = c->maxax = c->minay = c->maxay = 0;
1715 c->isfixed = (c->maxw && c->minw && c->maxh && c->minh
1716 && c->maxw == c->minw && c->maxh == c->minh);
1720 updatetitle(Client *c) {
1721 if(!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
1722 gettextprop(c->win, wmatom[WMName], c->name, sizeof c->name);
1726 updatewmhints(Client *c) {
1729 if((wmh = XGetWMHints(dpy, c->win))) {
1731 sel->isurgent = False;
1733 c->isurgent = (wmh->flags & XUrgencyHint) ? True : False;
1740 view(const char *arg) {
1743 for(i = 0; i < LENGTH(tags); i++)
1744 tmp[i] = (NULL == arg);
1745 tmp[idxoftag(arg)] = True;
1747 if(memcmp(seltags, tmp, TAGSZ) != 0) {
1748 memcpy(prevtags, seltags, TAGSZ);
1749 memcpy(seltags, tmp, TAGSZ);
1755 viewprevtag(const char *arg) {
1757 memcpy(tmp, seltags, TAGSZ);
1758 memcpy(seltags, prevtags, TAGSZ);
1759 memcpy(prevtags, tmp, TAGSZ);
1763 /* There's no way to check accesses to destroyed windows, thus those cases are
1764 * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
1765 * default error handler, which may call exit. */
1767 xerror(Display *dpy, XErrorEvent *ee) {
1768 if(ee->error_code == BadWindow
1769 || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1770 || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1771 || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1772 || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1773 || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1774 || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1775 || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1777 fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1778 ee->request_code, ee->error_code);
1779 return xerrorxlib(dpy, ee); /* may call exit */
1783 xerrordummy(Display *dpy, XErrorEvent *ee) {
1787 /* Startup Error handler to check if another window manager
1788 * is already running. */
1790 xerrorstart(Display *dpy, XErrorEvent *ee) {
1796 zoom(const char *arg) {
1799 if(!sel || !dozoom || sel->isfloating)
1801 if(c == nexttiled(clients))
1802 if(!(c = nexttiled(c->next)))
1811 main(int argc, char *argv[]) {
1812 if(argc == 2 && !strcmp("-v", argv[1]))
1813 eprint("dwm-"VERSION", © 2006-2008 dwm engineers, see LICENSE for details\n");
1815 eprint("usage: dwm [-v]\n");
1817 setlocale(LC_CTYPE, "");
1818 if(!(dpy = XOpenDisplay(0)))
1819 eprint("dwm: cannot open display\n");