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>
37 #include <X11/cursorfont.h>
38 #include <X11/keysym.h>
39 #include <X11/Xatom.h>
41 #include <X11/Xproto.h>
42 #include <X11/Xutil.h>
44 #include <X11/extensions/Xinerama.h>
48 #define BUTTONMASK (ButtonPressMask|ButtonReleaseMask)
49 #define CLEANMASK(mask) (mask & ~(numlockmask|LockMask))
50 #define LENGTH(x) (sizeof x / sizeof x[0])
52 #define MOUSEMASK (BUTTONMASK|PointerMotionMask)
56 enum { BarTop, BarBot, BarOff }; /* bar position */
57 enum { CurNormal, CurResize, CurMove, CurLast }; /* cursor */
58 enum { ColBorder, ColFG, ColBG, ColLast }; /* color */
59 enum { NetSupported, NetWMName, NetLast }; /* EWMH atoms */
60 enum { WMProtocols, WMDelete, WMName, WMState, WMLast };/* default atoms */
63 typedef struct View View;
64 typedef struct Client Client;
68 int basew, baseh, incw, inch, maxw, maxh, minw, minh;
69 int minax, maxax, minay, maxay;
71 unsigned int border, oldborder;
72 Bool isbanned, isfixed, isfloating, isurgent;
82 unsigned long norm[ColLast];
83 unsigned long sel[ColLast];
93 } DC; /* draw context */
98 void (*func)(const char *arg);
104 void (*arrange)(View *);
114 const char name[MAXTAGLEN];
119 int x, y, w, h, wax, way, wah, waw;
125 /* function declarations */
126 void addtag(Client *c, const char *t);
127 void applyrules(Client *c);
129 void attach(Client *c);
130 void attachstack(Client *c);
132 void buttonpress(XEvent *e);
133 void checkotherwm(void);
135 void configure(Client *c);
136 void configurenotify(XEvent *e);
137 void configurerequest(XEvent *e);
138 void destroynotify(XEvent *e);
139 void detach(Client *c);
140 void detachstack(Client *c);
141 void drawbar(View *v);
142 void drawsquare(View *v, Bool filled, Bool empty, Bool invert, unsigned long col[ColLast]);
143 void drawtext(View *v, const char *text, unsigned long col[ColLast], Bool invert);
144 void *emallocz(unsigned int size);
145 void enternotify(XEvent *e);
146 void eprint(const char *errstr, ...);
147 void expose(XEvent *e);
148 void floating(View *v); /* default floating layout */
149 void focus(Client *c);
150 void focusin(XEvent *e);
151 void focusnext(const char *arg);
152 void focusprev(const char *arg);
153 Client *getclient(Window w);
154 unsigned long getcolor(const char *colstr);
155 View *getviewbar(Window barwin);
156 View *getview(Client *c);
157 long getstate(Window w);
158 Bool gettextprop(Window w, Atom atom, char *text, unsigned int size);
159 void grabbuttons(Client *c, Bool focused);
161 unsigned int idxoftag(const char *t);
162 void initfont(const char *fontstr);
163 Bool isoccupied(unsigned int t);
164 Bool isprotodel(Client *c);
165 Bool isurgent(unsigned int t);
166 Bool isvisible(Client *c);
167 void keypress(XEvent *e);
168 void killclient(const char *arg);
169 void manage(Window w, XWindowAttributes *wa);
170 void mappingnotify(XEvent *e);
171 void maprequest(XEvent *e);
173 void movemouse(Client *c);
174 Client *nexttiled(Client *c, View *v);
175 void propertynotify(XEvent *e);
176 void quit(const char *arg);
177 void reapply(const char *arg);
178 void resize(Client *c, int x, int y, int w, int h, Bool sizehints);
179 void resizemouse(Client *c);
180 void restack(View *v);
183 void setclientstate(Client *c, long state);
184 void setlayout(const char *arg);
185 void setmwfact(const char *arg);
187 void spawn(const char *arg);
188 void tag(const char *arg);
189 unsigned int textnw(const char *text, unsigned int len);
190 unsigned int textw(const char *text);
192 void togglebar(const char *arg);
193 void togglefloating(const char *arg);
194 void toggletag(const char *arg);
195 void toggleview(const char *arg);
196 void unban(Client *c);
197 void unmanage(Client *c);
198 void unmapnotify(XEvent *e);
199 void updatebarpos(View *v);
200 void updatesizehints(Client *c);
201 void updatetitle(Client *c);
202 void updatewmhints(Client *c);
203 void view(const char *arg);
204 void viewprevtag(const char *arg); /* views previous selected tags */
205 int xerror(Display *dpy, XErrorEvent *ee);
206 int xerrordummy(Display *dpy, XErrorEvent *ee);
207 int xerrorstart(Display *dpy, XErrorEvent *ee);
208 void zoom(const char *arg);
209 void selectview(const char *arg);
212 char stext[256], buf[256];
216 int (*xerrorxlib)(Display *, XErrorEvent *);
217 unsigned int bh, bpos;
218 unsigned int blw = 0;
219 unsigned int numlockmask = 0;
220 void (*handler[LASTEvent]) (XEvent *) = {
221 [ButtonPress] = buttonpress,
222 [ConfigureRequest] = configurerequest,
223 [ConfigureNotify] = configurenotify,
224 [DestroyNotify] = destroynotify,
225 [EnterNotify] = enternotify,
228 [KeyPress] = keypress,
229 [MappingNotify] = mappingnotify,
230 [MapRequest] = maprequest,
231 [PropertyNotify] = propertynotify,
232 [UnmapNotify] = unmapnotify
234 Atom wmatom[WMLast], netatom[NetLast];
235 Bool isxinerama = False;
236 Bool domwfact = True;
238 Bool otherwm, readin;
242 Client *clients = NULL;
244 Client *stack = NULL;
245 Cursor cursor[CurLast];
251 /* configuration, allows nested code to access above variables */
254 /* function implementations */
256 addtag(Client *c, const char *t) {
257 unsigned int i, tidx = idxoftag(t);
259 for(i = 0; i < LENGTH(tags); i++)
260 if(c->tags[i] && vtags[i] != vtags[tidx])
261 return; /* conflict */
262 c->tags[tidx] = True;
266 applyrules(Client *c) {
268 Bool matched = False;
270 XClassHint ch = { 0 };
273 XGetClassHint(dpy, c->win, &ch);
274 for(i = 0; i < LENGTH(rules); i++) {
276 if(strstr(c->name, r->prop)
277 || (ch.res_class && strstr(ch.res_class, r->prop))
278 || (ch.res_name && strstr(ch.res_name, r->prop)))
280 c->isfloating = r->isfloating;
292 memcpy(c->tags, seltags, sizeof initags);
302 for(c = clients; c; c = c->next)
308 for(i = 0; i < nviews; i++) {
309 views[i].layout->arrange(&views[i]);
324 attachstack(Client *c) {
333 XMoveWindow(dpy, c->win, c->x + 3 * getview(c)->w, c->y);
338 buttonpress(XEvent *e) {
341 XButtonPressedEvent *ev = &e->xbutton;
345 if(ev->window == v->barwin) {
347 for(i = 0; i < LENGTH(tags); i++) {
350 if(ev->button == Button1) {
351 if(ev->state & MODKEY)
356 else if(ev->button == Button3) {
357 if(ev->state & MODKEY)
365 if((ev->x < x + blw) && ev->button == Button1)
368 else if((c = getclient(ev->window))) {
370 if(CLEANMASK(ev->state) != MODKEY)
372 if(ev->button == Button1) {
376 else if(ev->button == Button2) {
377 if((floating != v->layout->arrange) && c->isfloating)
378 togglefloating(NULL);
382 else if(ev->button == Button3 && !c->isfixed) {
392 XSetErrorHandler(xerrorstart);
394 /* this causes an error if some other window manager is running */
395 XSelectInput(dpy, DefaultRootWindow(dpy), SubstructureRedirectMask);
398 eprint("dwm: another window manager is already running\n");
400 XSetErrorHandler(NULL);
401 xerrorxlib = XSetErrorHandler(xerror);
414 XFreeFontSet(dpy, dc.font.set);
416 XFreeFont(dpy, dc.font.xfont);
418 XUngrabKey(dpy, AnyKey, AnyModifier, root);
419 XFreePixmap(dpy, dc.drawable);
421 XFreeCursor(dpy, cursor[CurNormal]);
422 XFreeCursor(dpy, cursor[CurResize]);
423 XFreeCursor(dpy, cursor[CurMove]);
424 for(i = 0; i < nviews; i++)
425 XDestroyWindow(dpy, views[i].barwin);
427 XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime);
431 configure(Client *c) {
434 ce.type = ConfigureNotify;
442 ce.border_width = c->border;
444 ce.override_redirect = False;
445 XSendEvent(dpy, c->win, False, StructureNotifyMask, (XEvent *)&ce);
449 configurenotify(XEvent *e) {
450 XConfigureEvent *ev = &e->xconfigure;
453 if(ev->window == root && (ev->width != v->w || ev->height != v->h)) {
454 /* TODO -- update Xinerama dimensions here */
457 XFreePixmap(dpy, dc.drawable);
458 dc.drawable = XCreatePixmap(dpy, root, DisplayWidth(root, screen), bh, DefaultDepth(dpy, screen));
459 XResizeWindow(dpy, v->barwin, v->w, bh);
466 configurerequest(XEvent *e) {
468 XConfigureRequestEvent *ev = &e->xconfigurerequest;
471 if((c = getclient(ev->window))) {
472 View *v = getview(c);
473 if(ev->value_mask & CWBorderWidth)
474 c->border = ev->border_width;
475 if(c->isfixed || c->isfloating || (floating == v->layout->arrange)) {
476 if(ev->value_mask & CWX)
478 if(ev->value_mask & CWY)
480 if(ev->value_mask & CWWidth)
482 if(ev->value_mask & CWHeight)
484 if((c->x - v->x + c->w) > v->w && c->isfloating)
485 c->x = v->x + (v->w / 2 - c->w / 2); /* center in x direction */
486 if((c->y - v->y + c->h) > v->h && c->isfloating)
487 c->y = v->y + (v->h / 2 - c->h / 2); /* center in y direction */
488 if((ev->value_mask & (CWX|CWY))
489 && !(ev->value_mask & (CWWidth|CWHeight)))
492 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h);
500 wc.width = ev->width;
501 wc.height = ev->height;
502 wc.border_width = ev->border_width;
503 wc.sibling = ev->above;
504 wc.stack_mode = ev->detail;
505 XConfigureWindow(dpy, ev->window, ev->value_mask, &wc);
511 destroynotify(XEvent *e) {
513 XDestroyWindowEvent *ev = &e->xdestroywindow;
515 if((c = getclient(ev->window)))
522 c->prev->next = c->next;
524 c->next->prev = c->prev;
527 c->next = c->prev = NULL;
531 detachstack(Client *c) {
534 for(tc=&stack; *tc && *tc != c; tc=&(*tc)->snext);
544 for(c = stack; c && (!isvisible(c) || getview(c) != v); c = c->snext);
545 for(i = 0; i < LENGTH(tags); i++) {
546 dc.w = textw(tags[i]);
548 drawtext(v, tags[i], dc.sel, isurgent(i));
549 drawsquare(v, c && c->tags[i], isoccupied(i), isurgent(i), dc.sel);
552 drawtext(v, tags[i], dc.norm, isurgent(i));
553 drawsquare(v, c && c->tags[i], isoccupied(i), isurgent(i), dc.norm);
558 drawtext(v, v->layout->symbol, dc.norm, False);
567 drawtext(v, stext, dc.norm, False);
571 if((dc.w = dc.x - x) > bh) {
574 drawtext(v, c->name, dc.sel, False);
575 drawsquare(v, False, c->isfloating, False, dc.sel);
578 drawtext(v, NULL, dc.norm, False);
580 XCopyArea(dpy, dc.drawable, v->barwin, dc.gc, 0, 0, v->w, bh, 0, 0);
585 drawsquare(View *v, Bool filled, Bool empty, Bool invert, unsigned long col[ColLast]) {
588 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
590 gcv.foreground = col[invert ? ColBG : ColFG];
591 XChangeGC(dpy, dc.gc, GCForeground, &gcv);
592 x = (dc.font.ascent + dc.font.descent + 2) / 4;
596 r.width = r.height = x + 1;
597 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
600 r.width = r.height = x;
601 XDrawRectangles(dpy, dc.drawable, dc.gc, &r, 1);
606 drawtext(View *v, const char *text, unsigned long col[ColLast], Bool invert) {
608 unsigned int len, olen;
609 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
611 XSetForeground(dpy, dc.gc, col[invert ? ColFG : ColBG]);
612 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
616 olen = len = strlen(text);
617 if(len >= sizeof buf)
618 len = sizeof buf - 1;
619 memcpy(buf, text, len);
621 h = dc.font.ascent + dc.font.descent;
622 y = dc.y + (dc.h / 2) - (h / 2) + dc.font.ascent;
624 /* shorten text if necessary */
625 while(len && (w = textnw(buf, len)) > dc.w - h)
636 return; /* too long */
637 XSetForeground(dpy, dc.gc, col[invert ? ColBG : ColFG]);
639 XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
641 XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
645 emallocz(unsigned int size) {
646 void *res = calloc(1, size);
649 eprint("fatal: could not malloc() %u bytes\n", size);
654 enternotify(XEvent *e) {
656 XCrossingEvent *ev = &e->xcrossing;
658 if(ev->mode != NotifyNormal || ev->detail == NotifyInferior) {
659 if(!isxinerama || ev->window != root)
662 if((c = getclient(ev->window)))
669 eprint(const char *errstr, ...) {
672 va_start(ap, errstr);
673 vfprintf(stderr, errstr, ap);
681 XExposeEvent *ev = &e->xexpose;
683 if(ev->count == 0 && (v = getviewbar(ev->window)))
688 floating(View *v) { /* default floating layout */
691 domwfact = dozoom = False;
692 for(c = clients; c; c = c->next)
694 resize(c, c->x, c->y, c->w, c->h, True);
701 selview = getview(c);
706 if(!c || (c && !isvisible(c)))
707 for(c = stack; c && (!isvisible(c) || getview(c) != selview); c = c->snext);
708 if(sel && sel != c) {
709 grabbuttons(sel, False);
710 XSetWindowBorder(dpy, sel->win, dc.norm[ColBorder]);
715 grabbuttons(c, True);
719 XSetWindowBorder(dpy, c->win, dc.sel[ColBorder]);
720 XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
721 selview = getview(c);
724 XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
729 focusin(XEvent *e) { /* there are some broken focus acquiring clients */
730 XFocusChangeEvent *ev = &e->xfocus;
732 if(sel && ev->window != sel->win)
733 XSetInputFocus(dpy, sel->win, RevertToPointerRoot, CurrentTime);
737 focusnext(const char *arg) {
742 for(c = sel->next; c && !isvisible(c); c = c->next);
744 for(c = clients; c && !isvisible(c); c = c->next);
752 focusprev(const char *arg) {
757 for(c = sel->prev; c && !isvisible(c); c = c->prev);
759 for(c = clients; c && c->next; c = c->next);
760 for(; c && !isvisible(c); c = c->prev);
769 getclient(Window w) {
772 for(c = clients; c && c->win != w; c = c->next);
777 getcolor(const char *colstr) {
778 Colormap cmap = DefaultColormap(dpy, screen);
781 if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
782 eprint("error, cannot allocate color '%s'\n", colstr);
787 getviewbar(Window barwin) {
790 for(i = 0; i < nviews; i++)
791 if(views[i].barwin == barwin)
800 for(i = 0; i < LENGTH(tags); i++)
802 return &views[c->tags[i] - 1];
803 return &views[0]; /* fallback */
810 unsigned char *p = NULL;
811 unsigned long n, extra;
814 status = XGetWindowProperty(dpy, w, wmatom[WMState], 0L, 2L, False, wmatom[WMState],
815 &real, &format, &n, &extra, (unsigned char **)&p);
816 if(status != Success)
825 gettextprop(Window w, Atom atom, char *text, unsigned int size) {
830 if(!text || size == 0)
833 XGetTextProperty(dpy, w, &name, atom);
836 if(name.encoding == XA_STRING)
837 strncpy(text, (char *)name.value, size - 1);
839 if(XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success
841 strncpy(text, *list, size - 1);
842 XFreeStringList(list);
845 text[size - 1] = '\0';
851 grabbuttons(Client *c, Bool focused) {
852 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
855 XGrabButton(dpy, Button1, MODKEY, c->win, False, BUTTONMASK,
856 GrabModeAsync, GrabModeSync, None, None);
857 XGrabButton(dpy, Button1, MODKEY|LockMask, c->win, False, BUTTONMASK,
858 GrabModeAsync, GrabModeSync, None, None);
859 XGrabButton(dpy, Button1, MODKEY|numlockmask, c->win, False, BUTTONMASK,
860 GrabModeAsync, GrabModeSync, None, None);
861 XGrabButton(dpy, Button1, MODKEY|numlockmask|LockMask, c->win, False, BUTTONMASK,
862 GrabModeAsync, GrabModeSync, None, None);
864 XGrabButton(dpy, Button2, MODKEY, c->win, False, BUTTONMASK,
865 GrabModeAsync, GrabModeSync, None, None);
866 XGrabButton(dpy, Button2, MODKEY|LockMask, c->win, False, BUTTONMASK,
867 GrabModeAsync, GrabModeSync, None, None);
868 XGrabButton(dpy, Button2, MODKEY|numlockmask, c->win, False, BUTTONMASK,
869 GrabModeAsync, GrabModeSync, None, None);
870 XGrabButton(dpy, Button2, MODKEY|numlockmask|LockMask, c->win, False, BUTTONMASK,
871 GrabModeAsync, GrabModeSync, None, None);
873 XGrabButton(dpy, Button3, MODKEY, c->win, False, BUTTONMASK,
874 GrabModeAsync, GrabModeSync, None, None);
875 XGrabButton(dpy, Button3, MODKEY|LockMask, c->win, False, BUTTONMASK,
876 GrabModeAsync, GrabModeSync, None, None);
877 XGrabButton(dpy, Button3, MODKEY|numlockmask, c->win, False, BUTTONMASK,
878 GrabModeAsync, GrabModeSync, None, None);
879 XGrabButton(dpy, Button3, MODKEY|numlockmask|LockMask, c->win, False, BUTTONMASK,
880 GrabModeAsync, GrabModeSync, None, None);
883 XGrabButton(dpy, AnyButton, AnyModifier, c->win, False, BUTTONMASK,
884 GrabModeAsync, GrabModeSync, None, None);
891 XModifierKeymap *modmap;
893 /* init modifier map */
894 modmap = XGetModifierMapping(dpy);
895 for(i = 0; i < 8; i++)
896 for(j = 0; j < modmap->max_keypermod; j++) {
897 if(modmap->modifiermap[i * modmap->max_keypermod + j] == XKeysymToKeycode(dpy, XK_Num_Lock))
898 numlockmask = (1 << i);
900 XFreeModifiermap(modmap);
902 XUngrabKey(dpy, AnyKey, AnyModifier, root);
903 for(i = 0; i < LENGTH(keys); i++) {
904 code = XKeysymToKeycode(dpy, keys[i].keysym);
905 XGrabKey(dpy, code, keys[i].mod, root, True,
906 GrabModeAsync, GrabModeAsync);
907 XGrabKey(dpy, code, keys[i].mod|LockMask, root, True,
908 GrabModeAsync, GrabModeAsync);
909 XGrabKey(dpy, code, keys[i].mod|numlockmask, root, True,
910 GrabModeAsync, GrabModeAsync);
911 XGrabKey(dpy, code, keys[i].mod|numlockmask|LockMask, root, True,
912 GrabModeAsync, GrabModeAsync);
917 idxoftag(const char *t) {
920 for(i = 0; (i < LENGTH(tags)) && (tags[i] != t); i++);
921 return (i < LENGTH(tags)) ? i : 0;
925 initfont(const char *fontstr) {
926 char *def, **missing;
931 XFreeFontSet(dpy, dc.font.set);
932 dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
935 fprintf(stderr, "dwm: missing fontset: %s\n", missing[n]);
936 XFreeStringList(missing);
939 XFontSetExtents *font_extents;
940 XFontStruct **xfonts;
942 dc.font.ascent = dc.font.descent = 0;
943 font_extents = XExtentsOfFontSet(dc.font.set);
944 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
945 for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
946 if(dc.font.ascent < (*xfonts)->ascent)
947 dc.font.ascent = (*xfonts)->ascent;
948 if(dc.font.descent < (*xfonts)->descent)
949 dc.font.descent = (*xfonts)->descent;
955 XFreeFont(dpy, dc.font.xfont);
956 dc.font.xfont = NULL;
957 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr))
958 && !(dc.font.xfont = XLoadQueryFont(dpy, "fixed")))
959 eprint("error, cannot load font: '%s'\n", fontstr);
960 dc.font.ascent = dc.font.xfont->ascent;
961 dc.font.descent = dc.font.xfont->descent;
963 dc.font.height = dc.font.ascent + dc.font.descent;
967 isoccupied(unsigned int t) {
970 for(c = clients; c; c = c->next)
977 isprotodel(Client *c) {
982 if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
983 for(i = 0; !ret && i < n; i++)
984 if(protocols[i] == wmatom[WMDelete])
992 isurgent(unsigned int t) {
995 for(c = clients; c; c = c->next)
996 if(c->isurgent && c->tags[t])
1002 isvisible(Client *c) {
1005 for(i = 0; i < LENGTH(tags); i++)
1006 if(c->tags[i] && seltags[i])
1012 keypress(XEvent *e) {
1018 keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
1019 for(i = 0; i < LENGTH(keys); i++)
1020 if(keysym == keys[i].keysym
1021 && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state))
1024 keys[i].func(keys[i].arg);
1029 killclient(const char *arg) {
1034 if(isprotodel(sel)) {
1035 ev.type = ClientMessage;
1036 ev.xclient.window = sel->win;
1037 ev.xclient.message_type = wmatom[WMProtocols];
1038 ev.xclient.format = 32;
1039 ev.xclient.data.l[0] = wmatom[WMDelete];
1040 ev.xclient.data.l[1] = CurrentTime;
1041 XSendEvent(dpy, sel->win, False, NoEventMask, &ev);
1044 XKillClient(dpy, sel->win);
1048 manage(Window w, XWindowAttributes *wa) {
1049 Client *c, *t = NULL;
1055 c = emallocz(sizeof(Client));
1056 c->tags = emallocz(sizeof initags);
1063 c->x = wa->x + v->x;
1064 c->y = wa->y + v->y;
1067 c->oldborder = wa->border_width;
1069 if(c->w == v->w && c->h == v->h) {
1072 c->border = wa->border_width;
1075 if(c->x + c->w + 2 * c->border > v->wax + v->waw)
1076 c->x = v->wax + v->waw - c->w - 2 * c->border;
1077 if(c->y + c->h + 2 * c->border > v->way + v->wah)
1078 c->y = v->way + v->wah - c->h - 2 * c->border;
1083 c->border = BORDERPX;
1085 wc.border_width = c->border;
1086 XConfigureWindow(dpy, w, CWBorderWidth, &wc);
1087 XSetWindowBorder(dpy, w, dc.norm[ColBorder]);
1088 configure(c); /* propagates border_width, if size doesn't change */
1090 XSelectInput(dpy, w, EnterWindowMask|FocusChangeMask|PropertyChangeMask|StructureNotifyMask);
1091 grabbuttons(c, False);
1093 if((rettrans = XGetTransientForHint(dpy, w, &trans) == Success))
1094 for(t = clients; t && t->win != trans; t = t->next);
1096 memcpy(c->tags, t->tags, sizeof initags);
1098 c->isfloating = (rettrans == Success) || c->isfixed;
1101 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h); /* some windows require this */
1103 XMapWindow(dpy, c->win);
1104 setclientstate(c, NormalState);
1109 mappingnotify(XEvent *e) {
1110 XMappingEvent *ev = &e->xmapping;
1112 XRefreshKeyboardMapping(ev);
1113 if(ev->request == MappingKeyboard)
1118 maprequest(XEvent *e) {
1119 static XWindowAttributes wa;
1120 XMapRequestEvent *ev = &e->xmaprequest;
1122 if(!XGetWindowAttributes(dpy, ev->window, &wa))
1124 if(wa.override_redirect)
1126 if(!getclient(ev->window))
1127 manage(ev->window, &wa);
1131 movemouse(Client *c) {
1132 int x1, y1, ocx, ocy, di, nx, ny;
1141 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1142 None, cursor[CurMove], CurrentTime) != GrabSuccess)
1144 XQueryPointer(dpy, root, &dummy, &dummy, &x1, &y1, &di, &di, &dui);
1146 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
1149 XUngrabPointer(dpy, CurrentTime);
1151 case ConfigureRequest:
1154 handler[ev.type](&ev);
1158 nx = ocx + (ev.xmotion.x - x1);
1159 ny = ocy + (ev.xmotion.y - y1);
1160 if(abs(v->wax - nx) < SNAP)
1162 else if(abs((v->wax + v->waw) - (nx + c->w + 2 * c->border)) < SNAP)
1163 nx = v->wax + v->waw - c->w - 2 * c->border;
1164 if(abs(v->way - ny) < SNAP)
1166 else if(abs((v->way + v->wah) - (ny + c->h + 2 * c->border)) < SNAP)
1167 ny = v->way + v->wah - c->h - 2 * c->border;
1168 if(!c->isfloating && (v->layout->arrange != floating) && (abs(nx - c->x) > SNAP || abs(ny - c->y) > SNAP))
1169 togglefloating(NULL);
1170 if((v->layout->arrange == floating) || c->isfloating)
1171 resize(c, nx, ny, c->w, c->h, False);
1178 nexttiled(Client *c, View *v) {
1179 for(; c && (c->isfloating || getview(c) != v || !isvisible(c)); c = c->next);
1184 propertynotify(XEvent *e) {
1187 XPropertyEvent *ev = &e->xproperty;
1189 if(ev->state == PropertyDelete)
1190 return; /* ignore */
1191 if((c = getclient(ev->window))) {
1194 case XA_WM_TRANSIENT_FOR:
1195 XGetTransientForHint(dpy, c->win, &trans);
1196 if(!c->isfloating && (c->isfloating = (getclient(trans) != NULL)))
1199 case XA_WM_NORMAL_HINTS:
1204 drawbar(getview(c));
1207 if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
1216 quit(const char *arg) {
1217 readin = running = False;
1221 reapply(const char *arg) {
1222 static Bool zerotags[LENGTH(tags)] = { 0 };
1225 for(c = clients; c; c = c->next) {
1226 memcpy(c->tags, zerotags, sizeof zerotags);
1233 resize(Client *c, int x, int y, int w, int h, Bool sizehints) {
1239 /* set minimum possible */
1245 /* temporarily remove base dimensions */
1249 /* adjust for aspect limits */
1250 if (c->minay > 0 && c->maxay > 0 && c->minax > 0 && c->maxax > 0) {
1251 if (w * c->maxay > h * c->maxax)
1252 w = h * c->maxax / c->maxay;
1253 else if (w * c->minay < h * c->minax)
1254 h = w * c->minay / c->minax;
1257 /* adjust for increment value */
1263 /* restore base dimensions */
1267 if(c->minw > 0 && w < c->minw)
1269 if(c->minh > 0 && h < c->minh)
1271 if(c->maxw > 0 && w > c->maxw)
1273 if(c->maxh > 0 && h > c->maxh)
1276 if(w <= 0 || h <= 0)
1279 x = v->w - w - 2 * c->border;
1281 y = v->h - h - 2 * c->border;
1282 if(x + w + 2 * c->border < v->x)
1284 if(y + h + 2 * c->border < v->y)
1286 if(c->x != x || c->y != y || c->w != w || c->h != h) {
1289 c->w = wc.width = w;
1290 c->h = wc.height = h;
1291 wc.border_width = c->border;
1292 XConfigureWindow(dpy, c->win,
1293 CWX|CWY|CWWidth|CWHeight|CWBorderWidth, &wc);
1300 resizemouse(Client *c) {
1309 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1310 None, cursor[CurResize], CurrentTime) != GrabSuccess)
1312 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->border - 1, c->h + c->border - 1);
1314 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask , &ev);
1317 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0,
1318 c->w + c->border - 1, c->h + c->border - 1);
1319 XUngrabPointer(dpy, CurrentTime);
1320 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1322 case ConfigureRequest:
1325 handler[ev.type](&ev);
1329 if((nw = ev.xmotion.x - ocx - 2 * c->border + 1) <= 0)
1331 if((nh = ev.xmotion.y - ocy - 2 * c->border + 1) <= 0)
1333 if(!c->isfloating && (v->layout->arrange != floating) && (abs(nw - c->w) > SNAP || abs(nh - c->h) > SNAP))
1334 togglefloating(NULL);
1335 if((v->layout->arrange == floating) || c->isfloating)
1336 resize(c, c->x, c->y, nw, nh, True);
1351 if(sel->isfloating || (v->layout->arrange == floating))
1352 XRaiseWindow(dpy, sel->win);
1353 if(v->layout->arrange != floating) {
1354 wc.stack_mode = Below;
1355 wc.sibling = v->barwin;
1356 if(!sel->isfloating) {
1357 XConfigureWindow(dpy, sel->win, CWSibling|CWStackMode, &wc);
1358 wc.sibling = sel->win;
1360 for(c = nexttiled(clients, v); c; c = nexttiled(c->next, v)) {
1363 XConfigureWindow(dpy, c->win, CWSibling|CWStackMode, &wc);
1364 wc.sibling = c->win;
1368 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1374 char sbuf[sizeof stext];
1377 unsigned int len, offset;
1380 /* main event loop, also reads status text from stdin */
1382 xfd = ConnectionNumber(dpy);
1385 len = sizeof stext - 1;
1386 sbuf[len] = stext[len] = '\0'; /* 0-terminator is never touched */
1390 FD_SET(STDIN_FILENO, &rd);
1392 if(select(xfd + 1, &rd, NULL, NULL, NULL) == -1) {
1395 eprint("select failed\n");
1397 if(FD_ISSET(STDIN_FILENO, &rd)) {
1398 switch((r = read(STDIN_FILENO, sbuf + offset, len - offset))) {
1400 strncpy(stext, strerror(errno), len);
1404 strncpy(stext, "EOF", 4);
1408 for(p = sbuf + offset; r > 0; p++, r--, offset++)
1409 if(*p == '\n' || *p == '\0') {
1411 strncpy(stext, sbuf, len);
1412 p += r - 1; /* p is sbuf + offset + r - 1 */
1413 for(r = 0; *(p - r) && *(p - r) != '\n'; r++);
1416 memmove(sbuf, p - r + 1, r);
1423 while(XPending(dpy)) {
1424 XNextEvent(dpy, &ev);
1425 if(handler[ev.type])
1426 (handler[ev.type])(&ev); /* call handler */
1433 unsigned int i, num;
1434 Window *wins, d1, d2;
1435 XWindowAttributes wa;
1438 if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1439 for(i = 0; i < num; i++) {
1440 if(!XGetWindowAttributes(dpy, wins[i], &wa)
1441 || wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1443 if(wa.map_state == IsViewable || getstate(wins[i]) == IconicState)
1444 manage(wins[i], &wa);
1446 for(i = 0; i < num; i++) { /* now the transients */
1447 if(!XGetWindowAttributes(dpy, wins[i], &wa))
1449 if(XGetTransientForHint(dpy, wins[i], &d1)
1450 && (wa.map_state == IsViewable || getstate(wins[i]) == IconicState))
1451 manage(wins[i], &wa);
1459 setclientstate(Client *c, long state) {
1460 long data[] = {state, None};
1462 XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1463 PropModeReplace, (unsigned char *)data, 2);
1467 setlayout(const char *arg) {
1473 if(v->layout == &layouts[LENGTH(layouts)])
1474 v->layout = &layouts[0];
1477 for(i = 0; i < LENGTH(layouts); i++)
1478 if(!strcmp(arg, layouts[i].symbol))
1480 if(i == LENGTH(layouts))
1482 v->layout = &layouts[i];
1491 setmwfact(const char *arg) {
1498 /* arg handling, manipulate mwfact */
1501 else if(sscanf(arg, "%lf", &delta) == 1) {
1502 if(arg[0] == '+' || arg[0] == '-')
1508 else if(v->mwfact > 0.9)
1518 XSetWindowAttributes wa;
1519 XineramaScreenInfo *info = NULL;
1522 wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1523 wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1524 wmatom[WMName] = XInternAtom(dpy, "WM_NAME", False);
1525 wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1526 netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1527 netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1530 wa.cursor = cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1531 cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1532 cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1534 if((isxinerama = XineramaIsActive(dpy)))
1535 info = XineramaQueryScreens(dpy, &nviews);
1536 #if defined(AIM_XINERAMA)
1538 nviews = 2; /* aim Xinerama */
1540 selview = views = emallocz(nviews * sizeof(View));
1542 screen = DefaultScreen(dpy);
1543 root = RootWindow(dpy, screen);
1545 /* init appearance */
1546 dc.norm[ColBorder] = getcolor(NORMBORDERCOLOR);
1547 dc.norm[ColBG] = getcolor(NORMBGCOLOR);
1548 dc.norm[ColFG] = getcolor(NORMFGCOLOR);
1549 dc.sel[ColBorder] = getcolor(SELBORDERCOLOR);
1550 dc.sel[ColBG] = getcolor(SELBGCOLOR);
1551 dc.sel[ColFG] = getcolor(SELFGCOLOR);
1553 dc.h = bh = dc.font.height + 2;
1554 dc.drawable = XCreatePixmap(dpy, root, DisplayWidth(dpy, screen), bh, DefaultDepth(dpy, screen));
1555 dc.gc = XCreateGC(dpy, root, 0, 0);
1556 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
1558 XSetFont(dpy, dc.gc, dc.font.xfont->fid);
1560 for(blw = i = 0; i < LENGTH(layouts); i++) {
1561 i = textw(layouts[i].symbol);
1566 seltags = emallocz(sizeof initags);
1567 prevtags = emallocz(sizeof initags);
1568 memcpy(seltags, initags, sizeof initags);
1569 memcpy(prevtags, initags, sizeof initags);
1571 for(i = 0; i < nviews; i++) {
1575 if(nviews != 1 && isxinerama) {
1577 #if defined(AIM_XINERAMA)
1578 v->w = DisplayWidth(dpy, screen) / 2;
1579 v->x = (i == 0) ? 0 : v->w;
1581 v->h = DisplayHeight(dpy, screen);
1583 v->x = info[i].x_org;
1584 v->y = info[i].y_org;
1585 v->w = info[i].width;
1586 v->h = info[i].height;
1592 v->w = DisplayWidth(dpy, screen);
1593 v->h = DisplayHeight(dpy, screen);
1598 v->layout = &layouts[0];
1600 // TODO: bpos per screen?
1602 wa.override_redirect = 1;
1603 wa.background_pixmap = ParentRelative;
1604 wa.event_mask = ButtonPressMask|ExposureMask;
1607 v->barwin = XCreateWindow(dpy, root, v->x, v->y, v->w, bh, 0,
1608 DefaultDepth(dpy, screen), CopyFromParent, DefaultVisual(dpy, screen),
1609 CWOverrideRedirect|CWBackPixmap|CWEventMask, &wa);
1610 XDefineCursor(dpy, v->barwin, cursor[CurNormal]);
1612 XMapRaised(dpy, v->barwin);
1613 strcpy(stext, "dwm-"VERSION);
1615 /* EWMH support per view */
1616 XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1617 PropModeReplace, (unsigned char *) netatom, NetLast);
1619 /* select for events */
1620 wa.event_mask = SubstructureRedirectMask|SubstructureNotifyMask
1621 |EnterWindowMask|LeaveWindowMask|StructureNotifyMask;
1622 XChangeWindowAttributes(dpy, root, CWEventMask|CWCursor, &wa);
1623 XSelectInput(dpy, root, wa.event_mask);
1633 selview = &views[0];
1637 spawn(const char *arg) {
1638 static char *shell = NULL;
1640 if(!shell && !(shell = getenv("SHELL")))
1644 /* The double-fork construct avoids zombie processes and keeps the code
1645 * clean from stupid signal handlers. */
1649 close(ConnectionNumber(dpy));
1651 execl(shell, shell, "-c", arg, (char *)NULL);
1652 fprintf(stderr, "dwm: execl '%s -c %s'", shell, arg);
1661 tag(const char *arg) {
1666 for(i = 0; i < LENGTH(tags); i++)
1667 sel->tags[i] = (NULL == arg);
1668 sel->tags[idxoftag(arg)] = True;
1673 textnw(const char *text, unsigned int len) {
1677 XmbTextExtents(dc.font.set, text, len, NULL, &r);
1680 return XTextWidth(dc.font.xfont, text, len);
1684 textw(const char *text) {
1685 return textnw(text, strlen(text)) + dc.font.height;
1690 unsigned int i, n, nx, ny, nw, nh, mw, th;
1693 domwfact = dozoom = True;
1697 for(n = 0, c = nexttiled(clients, v); c; c = nexttiled(c->next, v))
1701 mw = (n == 1) ? v->waw : v->mwfact * v->waw;
1702 th = (n > 1) ? v->wah / (n - 1) : 0;
1703 if(n > 1 && th < bh)
1706 for(i = 0, c = mc = nexttiled(clients, v); c; c = nexttiled(c->next, v)) {
1707 if(i == 0) { /* master */
1710 nw = mw - 2 * c->border;
1711 nh = v->wah - 2 * c->border;
1713 else { /* tile window */
1716 nx += mc->w + 2 * mc->border;
1717 nw = v->waw - mw - 2 * c->border;
1719 if(i + 1 == n) /* remainder */
1720 nh = (v->way + v->wah) - ny - 2 * c->border;
1722 nh = th - 2 * c->border;
1724 resize(c, nx, ny, nw, nh, RESIZEHINTS);
1725 if((RESIZEHINTS) && ((c->h < bh) || (c->h > nh) || (c->w < bh) || (c->w > nw)))
1726 /* client doesn't accept size constraints */
1727 resize(c, nx, ny, nw, nh, False);
1728 if(n > 1 && th != v->wah)
1729 ny = c->y + c->h + 2 * c->border;
1735 togglebar(const char *arg) {
1737 bpos = (BARPOS == BarOff) ? BarTop : BARPOS;
1740 updatebarpos(selview);
1745 togglefloating(const char *arg) {
1748 sel->isfloating = !sel->isfloating;
1750 resize(sel, sel->x, sel->y, sel->w, sel->h, True);
1755 toggletag(const char *arg) {
1761 sel->tags[i] = !sel->tags[i];
1762 for(j = 0; j < LENGTH(tags) && !sel->tags[j]; j++);
1763 if(j == LENGTH(tags))
1764 sel->tags[i] = True; /* at least one tag must be enabled */
1769 toggleview(const char *arg) {
1773 seltags[i] = !seltags[i];
1774 for(j = 0; j < LENGTH(tags) && !seltags[j]; j++);
1775 if(j == LENGTH(tags))
1776 seltags[i] = True; /* at least one tag must be viewed */
1784 XMoveWindow(dpy, c->win, c->x, c->y);
1785 c->isbanned = False;
1789 unmanage(Client *c) {
1792 wc.border_width = c->oldborder;
1793 /* The server grab construct avoids race conditions. */
1795 XSetErrorHandler(xerrordummy);
1796 XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
1801 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1802 setclientstate(c, WithdrawnState);
1806 XSetErrorHandler(xerror);
1812 unmapnotify(XEvent *e) {
1814 XUnmapEvent *ev = &e->xunmap;
1816 if((c = getclient(ev->window)))
1821 updatebarpos(View *v) {
1832 XMoveWindow(dpy, v->barwin, v->x, v->y);
1836 XMoveWindow(dpy, v->barwin, v->x, v->y + v->wah);
1839 XMoveWindow(dpy, v->barwin, v->x, v->y - bh);
1843 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1847 updatesizehints(Client *c) {
1851 if(!XGetWMNormalHints(dpy, c->win, &size, &msize) || !size.flags)
1853 c->flags = size.flags;
1854 if(c->flags & PBaseSize) {
1855 c->basew = size.base_width;
1856 c->baseh = size.base_height;
1858 else if(c->flags & PMinSize) {
1859 c->basew = size.min_width;
1860 c->baseh = size.min_height;
1863 c->basew = c->baseh = 0;
1864 if(c->flags & PResizeInc) {
1865 c->incw = size.width_inc;
1866 c->inch = size.height_inc;
1869 c->incw = c->inch = 0;
1870 if(c->flags & PMaxSize) {
1871 c->maxw = size.max_width;
1872 c->maxh = size.max_height;
1875 c->maxw = c->maxh = 0;
1876 if(c->flags & PMinSize) {
1877 c->minw = size.min_width;
1878 c->minh = size.min_height;
1880 else if(c->flags & PBaseSize) {
1881 c->minw = size.base_width;
1882 c->minh = size.base_height;
1885 c->minw = c->minh = 0;
1886 if(c->flags & PAspect) {
1887 c->minax = size.min_aspect.x;
1888 c->maxax = size.max_aspect.x;
1889 c->minay = size.min_aspect.y;
1890 c->maxay = size.max_aspect.y;
1893 c->minax = c->maxax = c->minay = c->maxay = 0;
1894 c->isfixed = (c->maxw && c->minw && c->maxh && c->minh
1895 && c->maxw == c->minw && c->maxh == c->minh);
1899 updatetitle(Client *c) {
1900 if(!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
1901 gettextprop(c->win, wmatom[WMName], c->name, sizeof c->name);
1905 updatewmhints(Client *c) {
1908 if((wmh = XGetWMHints(dpy, c->win))) {
1909 c->isurgent = (wmh->flags & XUrgencyHint) ? True : False;
1915 view(const char *arg) {
1917 Bool tmp[LENGTH(tags)];
1919 for(i = 0; i < LENGTH(tags); i++)
1920 tmp[i] = (NULL == arg);
1921 tmp[idxoftag(arg)] = True;
1923 if(memcmp(seltags, tmp, sizeof initags) != 0) {
1924 memcpy(prevtags, seltags, sizeof initags);
1925 memcpy(seltags, tmp, sizeof initags);
1936 XQueryPointer(dpy, root, &win, &win, &x, &y, &i, &i, &mask);
1937 for(i = 0; i < nviews; i++) {
1938 if((x >= views[i].x && x < views[i].x + views[i].w)
1939 && (y >= views[i].y && y < views[i].y + views[i].h))
1946 viewprevtag(const char *arg) {
1947 static Bool tmp[LENGTH(tags)];
1949 memcpy(tmp, seltags, sizeof initags);
1950 memcpy(seltags, prevtags, sizeof initags);
1951 memcpy(prevtags, tmp, sizeof initags);
1955 /* There's no way to check accesses to destroyed windows, thus those cases are
1956 * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
1957 * default error handler, which may call exit. */
1959 xerror(Display *dpy, XErrorEvent *ee) {
1960 if(ee->error_code == BadWindow
1961 || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1962 || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1963 || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1964 || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1965 || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1966 || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1967 || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1969 fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1970 ee->request_code, ee->error_code);
1971 return xerrorxlib(dpy, ee); /* may call exit */
1975 xerrordummy(Display *dpy, XErrorEvent *ee) {
1979 /* Startup Error handler to check if another window manager
1980 * is already running. */
1982 xerrorstart(Display *dpy, XErrorEvent *ee) {
1988 zoom(const char *arg) {
1991 if(!sel || !dozoom || sel->isfloating)
1993 if(c == nexttiled(clients, getview(c)))
1994 if(!(c = nexttiled(c->next, getview(c))))
2003 main(int argc, char *argv[]) {
2004 if(argc == 2 && !strcmp("-v", argv[1]))
2005 eprint("dwm-"VERSION", © 2006-2008 dwm engineers, see LICENSE for details\n");
2007 eprint("usage: dwm [-v]\n");
2009 setlocale(LC_CTYPE, "");
2010 if(!(dpy = XOpenDisplay(0)))
2011 eprint("dwm: cannot open display\n");