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;
83 unsigned long norm[ColLast];
84 unsigned long sel[ColLast];
94 } DC; /* draw context */
99 void (*func)(const char *arg);
105 void (*arrange)(View *);
116 int x, y, w, h, wax, way, wah, waw;
122 /* function declarations */
123 void addtag(Client *c, const char *t);
124 void applyrules(Client *c);
126 void attach(Client *c);
127 void attachstack(Client *c);
129 void buttonpress(XEvent *e);
130 void checkotherwm(void);
132 void configure(Client *c);
133 void configurenotify(XEvent *e);
134 void configurerequest(XEvent *e);
135 void destroynotify(XEvent *e);
136 void detach(Client *c);
137 void detachstack(Client *c);
138 void drawbar(View *v);
139 void drawsquare(Bool filled, Bool empty, Bool invert, unsigned long col[ColLast]);
140 void drawtext(const char *text, unsigned long col[ColLast], Bool invert);
141 void *emallocz(unsigned int size);
142 void enternotify(XEvent *e);
143 void eprint(const char *errstr, ...);
144 void expose(XEvent *e);
145 void floating(View *v); /* default floating layout */
146 void focus(Client *c);
147 void focusin(XEvent *e);
148 void focusnext(const char *arg);
149 void focusprev(const char *arg);
150 Client *getclient(Window w);
151 unsigned long getcolor(const char *colstr);
152 View *getviewbar(Window barwin);
153 long getstate(Window w);
154 Bool gettextprop(Window w, Atom atom, char *text, unsigned int size);
155 void grabbuttons(Client *c, Bool focused);
157 unsigned int idxoftag(const char *t);
158 void initfont(const char *fontstr);
159 Bool isoccupied(unsigned int t);
160 Bool isprotodel(Client *c);
161 Bool isurgent(unsigned int t);
162 Bool isvisible(Client *c);
163 void keypress(XEvent *e);
164 void killclient(const char *arg);
165 void manage(Window w, XWindowAttributes *wa);
166 void mappingnotify(XEvent *e);
167 void maprequest(XEvent *e);
169 void movemouse(Client *c);
170 Client *nexttiled(Client *c, View *v);
171 void propertynotify(XEvent *e);
172 void quit(const char *arg);
173 void reapply(const char *arg);
174 void resize(Client *c, int x, int y, int w, int h, Bool sizehints);
175 void resizemouse(Client *c);
176 void restack(View *v);
179 void setclientstate(Client *c, long state);
180 void setlayout(const char *arg);
181 void setmwfact(const char *arg);
183 void spawn(const char *arg);
184 void tag(const char *arg);
185 unsigned int textnw(const char *text, unsigned int len);
186 unsigned int textw(const char *text);
188 void togglebar(const char *arg);
189 void togglefloating(const char *arg);
190 void toggletag(const char *arg);
191 void toggleview(const char *arg);
192 void unban(Client *c);
193 void unmanage(Client *c);
194 void unmapnotify(XEvent *e);
195 void updatebarpos(View *v);
196 void updatesizehints(Client *c);
197 void updatetitle(Client *c);
198 void updatewmhints(Client *c);
199 void view(const char *arg);
200 void viewprevtag(const char *arg); /* views previous selected tags */
201 int xerror(Display *dpy, XErrorEvent *ee);
202 int xerrordummy(Display *dpy, XErrorEvent *ee);
203 int xerrorstart(Display *dpy, XErrorEvent *ee);
204 void zoom(const char *arg);
205 void selectview(const char *arg);
208 char stext[256], buf[256];
211 int (*xerrorxlib)(Display *, XErrorEvent *);
212 unsigned int bh, bpos;
213 unsigned int blw = 0;
214 unsigned int numlockmask = 0;
215 void (*handler[LASTEvent]) (XEvent *) = {
216 [ButtonPress] = buttonpress,
217 [ConfigureRequest] = configurerequest,
218 [ConfigureNotify] = configurenotify,
219 [DestroyNotify] = destroynotify,
220 [EnterNotify] = enternotify,
223 [KeyPress] = keypress,
224 [MappingNotify] = mappingnotify,
225 [MapRequest] = maprequest,
226 [PropertyNotify] = propertynotify,
227 [UnmapNotify] = unmapnotify
229 Atom wmatom[WMLast], netatom[NetLast];
230 Bool isxinerama = False;
231 Bool domwfact = True;
233 Bool otherwm, readin;
237 Client *clients = NULL;
239 Client *stack = NULL;
240 Cursor cursor[CurLast];
247 /* configuration, allows nested code to access above variables */
250 /* function implementations */
252 addtag(Client *c, const char *t) {
253 unsigned int i, tidx = idxoftag(t);
255 for(i = 0; i < LENGTH(tags); i++)
256 if(c->tags[i] && vtags[i] != vtags[tidx])
257 return; /* conflict */
258 c->tags[tidx] = True;
259 c->view = &views[vtags[tidx]];
263 applyrules(Client *c) {
265 Bool matched = False;
267 XClassHint ch = { 0 };
270 XGetClassHint(dpy, c->win, &ch);
271 for(i = 0; i < LENGTH(rules); i++) {
273 if(strstr(c->name, r->prop)
274 || (ch.res_class && strstr(ch.res_class, r->prop))
275 || (ch.res_name && strstr(ch.res_name, r->prop)))
277 c->isfloating = r->isfloating;
289 memcpy(c->tags, seltags, sizeof initags);
301 for(c = clients; c; c = c->next)
307 for(i = 0; i < nviews; i++) {
308 views[i].layout->arrange(&views[i]);
323 attachstack(Client *c) {
332 XMoveWindow(dpy, c->win, c->x + 3 * c->view->w, c->y);
337 buttonpress(XEvent *e) {
340 XButtonPressedEvent *ev = &e->xbutton;
342 if(ev->window == selview->barwin) {
344 for(i = 0; i < LENGTH(tags); i++) {
347 if(ev->button == Button1) {
348 if(ev->state & MODKEY)
353 else if(ev->button == Button3) {
354 if(ev->state & MODKEY)
362 if((ev->x < x + blw) && ev->button == Button1)
365 else if((c = getclient(ev->window))) {
367 if(CLEANMASK(ev->state) != MODKEY)
369 if(ev->button == Button1) {
373 else if(ev->button == Button2) {
374 if((floating != c->view->layout->arrange) && c->isfloating)
375 togglefloating(NULL);
379 else if(ev->button == Button3 && !c->isfixed) {
389 XSetErrorHandler(xerrorstart);
391 /* this causes an error if some other window manager is running */
392 XSelectInput(dpy, DefaultRootWindow(dpy), SubstructureRedirectMask);
395 eprint("dwm: another window manager is already running\n");
397 XSetErrorHandler(NULL);
398 xerrorxlib = XSetErrorHandler(xerror);
411 XFreeFontSet(dpy, dc.font.set);
413 XFreeFont(dpy, dc.font.xfont);
415 XUngrabKey(dpy, AnyKey, AnyModifier, root);
416 XFreePixmap(dpy, dc.drawable);
418 XFreeCursor(dpy, cursor[CurNormal]);
419 XFreeCursor(dpy, cursor[CurResize]);
420 XFreeCursor(dpy, cursor[CurMove]);
421 for(i = 0; i < nviews; i++)
422 XDestroyWindow(dpy, views[i].barwin);
424 XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime);
428 configure(Client *c) {
431 ce.type = ConfigureNotify;
439 ce.border_width = c->border;
441 ce.override_redirect = False;
442 XSendEvent(dpy, c->win, False, StructureNotifyMask, (XEvent *)&ce);
446 configurenotify(XEvent *e) {
447 XConfigureEvent *ev = &e->xconfigure;
450 if(ev->window == root && (ev->width != v->w || ev->height != v->h)) {
451 /* TODO -- update Xinerama dimensions here */
454 XFreePixmap(dpy, dc.drawable);
455 dc.drawable = XCreatePixmap(dpy, root, DisplayWidth(root, screen), bh, DefaultDepth(dpy, screen));
456 XResizeWindow(dpy, v->barwin, v->w, bh);
457 updatebarpos(selview);
463 configurerequest(XEvent *e) {
465 XConfigureRequestEvent *ev = &e->xconfigurerequest;
468 if((c = getclient(ev->window))) {
470 if(ev->value_mask & CWBorderWidth)
471 c->border = ev->border_width;
472 if(c->isfixed || c->isfloating || (floating == v->layout->arrange)) {
473 if(ev->value_mask & CWX)
475 if(ev->value_mask & CWY)
477 if(ev->value_mask & CWWidth)
479 if(ev->value_mask & CWHeight)
481 if((c->x - v->x + c->w) > v->w && c->isfloating)
482 c->x = v->x + (v->w / 2 - c->w / 2); /* center in x direction */
483 if((c->y - v->y + c->h) > v->h && c->isfloating)
484 c->y = v->y + (v->h / 2 - c->h / 2); /* center in y direction */
485 if((ev->value_mask & (CWX|CWY))
486 && !(ev->value_mask & (CWWidth|CWHeight)))
489 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h);
497 wc.width = ev->width;
498 wc.height = ev->height;
499 wc.border_width = ev->border_width;
500 wc.sibling = ev->above;
501 wc.stack_mode = ev->detail;
502 XConfigureWindow(dpy, ev->window, ev->value_mask, &wc);
508 destroynotify(XEvent *e) {
510 XDestroyWindowEvent *ev = &e->xdestroywindow;
512 if((c = getclient(ev->window)))
519 c->prev->next = c->next;
521 c->next->prev = c->prev;
524 c->next = c->prev = NULL;
528 detachstack(Client *c) {
531 for(tc=&stack; *tc && *tc != c; tc=&(*tc)->snext);
541 for(c = stack; c && (!isvisible(c) || c->view != v); c = c->snext);
542 for(i = 0; i < LENGTH(tags); i++) {
543 if(&views[vtags[i]] != v)
545 dc.w = textw(tags[i]);
547 drawtext(tags[i], dc.sel, isurgent(i));
548 drawsquare(c && c->tags[i], isoccupied(i), isurgent(i), dc.sel);
551 drawtext(tags[i], dc.norm, isurgent(i));
552 drawsquare(c && c->tags[i], isoccupied(i), isurgent(i), dc.norm);
557 drawtext(v->layout->symbol, dc.norm, False);
566 drawtext(stext, dc.norm, False);
570 if((dc.w = dc.x - x) > bh) {
573 drawtext(c->name, dc.sel, False);
574 drawsquare(False, c->isfloating, False, dc.sel);
577 drawtext(NULL, dc.norm, False);
579 XCopyArea(dpy, dc.drawable, v->barwin, dc.gc, 0, 0, v->w, bh, 0, 0);
584 drawsquare(Bool filled, Bool empty, Bool invert, unsigned long col[ColLast]) {
587 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
589 gcv.foreground = col[invert ? ColBG : ColFG];
590 XChangeGC(dpy, dc.gc, GCForeground, &gcv);
591 x = (dc.font.ascent + dc.font.descent + 2) / 4;
595 r.width = r.height = x + 1;
596 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
599 r.width = r.height = x;
600 XDrawRectangles(dpy, dc.drawable, dc.gc, &r, 1);
605 drawtext(const char *text, unsigned long col[ColLast], Bool invert) {
607 unsigned int len, olen;
608 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
610 XSetForeground(dpy, dc.gc, col[invert ? ColFG : ColBG]);
611 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
615 olen = len = strlen(text);
616 if(len >= sizeof buf)
617 len = sizeof buf - 1;
618 memcpy(buf, text, len);
620 h = dc.font.ascent + dc.font.descent;
621 y = dc.y + (dc.h / 2) - (h / 2) + dc.font.ascent;
623 /* shorten text if necessary */
624 while(len && (w = textnw(buf, len)) > dc.w - h)
635 return; /* too long */
636 XSetForeground(dpy, dc.gc, col[invert ? ColBG : ColFG]);
638 XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
640 XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
644 emallocz(unsigned int size) {
645 void *res = calloc(1, size);
648 eprint("fatal: could not malloc() %u bytes\n", size);
653 enternotify(XEvent *e) {
655 XCrossingEvent *ev = &e->xcrossing;
657 if(ev->mode != NotifyNormal || ev->detail == NotifyInferior) {
658 if(!isxinerama || ev->window != root)
661 if((c = getclient(ev->window)))
668 eprint(const char *errstr, ...) {
671 va_start(ap, errstr);
672 vfprintf(stderr, errstr, ap);
680 XExposeEvent *ev = &e->xexpose;
682 if(ev->count == 0 && ((v = getviewbar(ev->window))))
687 floating(View *v) { /* default floating layout */
690 domwfact = dozoom = False;
691 for(c = clients; c; c = c->next)
693 resize(c, c->x, c->y, c->w, c->h, True);
705 if(!c || (c && !isvisible(c)))
706 for(c = stack; c && (!isvisible(c) || c->view != selview); c = c->snext);
707 if(sel && sel != c) {
708 grabbuttons(sel, False);
709 XSetWindowBorder(dpy, sel->win, dc.norm[ColBorder]);
714 grabbuttons(c, True);
718 XSetWindowBorder(dpy, c->win, dc.sel[ColBorder]);
719 XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
723 XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
728 focusin(XEvent *e) { /* there are some broken focus acquiring clients */
729 XFocusChangeEvent *ev = &e->xfocus;
731 if(sel && ev->window != sel->win)
732 XSetInputFocus(dpy, sel->win, RevertToPointerRoot, CurrentTime);
736 focusnext(const char *arg) {
741 for(c = sel->next; c && !isvisible(c); c = c->next);
743 for(c = clients; c && !isvisible(c); c = c->next);
751 focusprev(const char *arg) {
756 for(c = sel->prev; c && !isvisible(c); c = c->prev);
758 for(c = clients; c && c->next; c = c->next);
759 for(; c && !isvisible(c); c = c->prev);
768 getclient(Window w) {
771 for(c = clients; c && c->win != w; c = c->next);
776 getcolor(const char *colstr) {
777 Colormap cmap = DefaultColormap(dpy, screen);
780 if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
781 eprint("error, cannot allocate color '%s'\n", colstr);
786 getviewbar(Window barwin) {
789 for(i = 0; i < nviews; i++)
790 if(views[i].barwin == barwin)
799 unsigned char *p = NULL;
800 unsigned long n, extra;
803 status = XGetWindowProperty(dpy, w, wmatom[WMState], 0L, 2L, False, wmatom[WMState],
804 &real, &format, &n, &extra, (unsigned char **)&p);
805 if(status != Success)
814 gettextprop(Window w, Atom atom, char *text, unsigned int size) {
819 if(!text || size == 0)
822 XGetTextProperty(dpy, w, &name, atom);
825 if(name.encoding == XA_STRING)
826 strncpy(text, (char *)name.value, size - 1);
828 if(XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success
830 strncpy(text, *list, size - 1);
831 XFreeStringList(list);
834 text[size - 1] = '\0';
840 grabbuttons(Client *c, Bool focused) {
841 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
844 XGrabButton(dpy, Button1, MODKEY, c->win, False, BUTTONMASK,
845 GrabModeAsync, GrabModeSync, None, None);
846 XGrabButton(dpy, Button1, MODKEY|LockMask, c->win, False, BUTTONMASK,
847 GrabModeAsync, GrabModeSync, None, None);
848 XGrabButton(dpy, Button1, MODKEY|numlockmask, c->win, False, BUTTONMASK,
849 GrabModeAsync, GrabModeSync, None, None);
850 XGrabButton(dpy, Button1, MODKEY|numlockmask|LockMask, c->win, False, BUTTONMASK,
851 GrabModeAsync, GrabModeSync, None, None);
853 XGrabButton(dpy, Button2, MODKEY, c->win, False, BUTTONMASK,
854 GrabModeAsync, GrabModeSync, None, None);
855 XGrabButton(dpy, Button2, MODKEY|LockMask, c->win, False, BUTTONMASK,
856 GrabModeAsync, GrabModeSync, None, None);
857 XGrabButton(dpy, Button2, MODKEY|numlockmask, c->win, False, BUTTONMASK,
858 GrabModeAsync, GrabModeSync, None, None);
859 XGrabButton(dpy, Button2, MODKEY|numlockmask|LockMask, c->win, False, BUTTONMASK,
860 GrabModeAsync, GrabModeSync, None, None);
862 XGrabButton(dpy, Button3, MODKEY, c->win, False, BUTTONMASK,
863 GrabModeAsync, GrabModeSync, None, None);
864 XGrabButton(dpy, Button3, MODKEY|LockMask, c->win, False, BUTTONMASK,
865 GrabModeAsync, GrabModeSync, None, None);
866 XGrabButton(dpy, Button3, MODKEY|numlockmask, c->win, False, BUTTONMASK,
867 GrabModeAsync, GrabModeSync, None, None);
868 XGrabButton(dpy, Button3, MODKEY|numlockmask|LockMask, c->win, False, BUTTONMASK,
869 GrabModeAsync, GrabModeSync, None, None);
872 XGrabButton(dpy, AnyButton, AnyModifier, c->win, False, BUTTONMASK,
873 GrabModeAsync, GrabModeSync, None, None);
880 XModifierKeymap *modmap;
882 /* init modifier map */
883 modmap = XGetModifierMapping(dpy);
884 for(i = 0; i < 8; i++)
885 for(j = 0; j < modmap->max_keypermod; j++) {
886 if(modmap->modifiermap[i * modmap->max_keypermod + j] == XKeysymToKeycode(dpy, XK_Num_Lock))
887 numlockmask = (1 << i);
889 XFreeModifiermap(modmap);
891 XUngrabKey(dpy, AnyKey, AnyModifier, root);
892 for(i = 0; i < LENGTH(keys); i++) {
893 code = XKeysymToKeycode(dpy, keys[i].keysym);
894 XGrabKey(dpy, code, keys[i].mod, root, True,
895 GrabModeAsync, GrabModeAsync);
896 XGrabKey(dpy, code, keys[i].mod|LockMask, root, True,
897 GrabModeAsync, GrabModeAsync);
898 XGrabKey(dpy, code, keys[i].mod|numlockmask, root, True,
899 GrabModeAsync, GrabModeAsync);
900 XGrabKey(dpy, code, keys[i].mod|numlockmask|LockMask, root, True,
901 GrabModeAsync, GrabModeAsync);
906 idxoftag(const char *t) {
909 for(i = 0; (i < LENGTH(tags)) && (tags[i] != t); i++);
910 return (i < LENGTH(tags)) ? i : 0;
914 initfont(const char *fontstr) {
915 char *def, **missing;
920 XFreeFontSet(dpy, dc.font.set);
921 dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
924 fprintf(stderr, "dwm: missing fontset: %s\n", missing[n]);
925 XFreeStringList(missing);
928 XFontSetExtents *font_extents;
929 XFontStruct **xfonts;
931 dc.font.ascent = dc.font.descent = 0;
932 font_extents = XExtentsOfFontSet(dc.font.set);
933 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
934 for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
935 if(dc.font.ascent < (*xfonts)->ascent)
936 dc.font.ascent = (*xfonts)->ascent;
937 if(dc.font.descent < (*xfonts)->descent)
938 dc.font.descent = (*xfonts)->descent;
944 XFreeFont(dpy, dc.font.xfont);
945 dc.font.xfont = NULL;
946 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr))
947 && !(dc.font.xfont = XLoadQueryFont(dpy, "fixed")))
948 eprint("error, cannot load font: '%s'\n", fontstr);
949 dc.font.ascent = dc.font.xfont->ascent;
950 dc.font.descent = dc.font.xfont->descent;
952 dc.font.height = dc.font.ascent + dc.font.descent;
956 isoccupied(unsigned int t) {
959 for(c = clients; c; c = c->next)
966 isprotodel(Client *c) {
971 if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
972 for(i = 0; !ret && i < n; i++)
973 if(protocols[i] == wmatom[WMDelete])
981 isurgent(unsigned int t) {
984 for(c = clients; c; c = c->next)
985 if(c->isurgent && c->tags[t])
991 isvisible(Client *c) {
994 for(i = 0; i < LENGTH(tags); i++)
995 if(c->tags[i] && seltags[i])
1001 keypress(XEvent *e) {
1007 keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
1008 for(i = 0; i < LENGTH(keys); i++)
1009 if(keysym == keys[i].keysym
1010 && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state))
1013 keys[i].func(keys[i].arg);
1018 killclient(const char *arg) {
1023 if(isprotodel(sel)) {
1024 ev.type = ClientMessage;
1025 ev.xclient.window = sel->win;
1026 ev.xclient.message_type = wmatom[WMProtocols];
1027 ev.xclient.format = 32;
1028 ev.xclient.data.l[0] = wmatom[WMDelete];
1029 ev.xclient.data.l[1] = CurrentTime;
1030 XSendEvent(dpy, sel->win, False, NoEventMask, &ev);
1033 XKillClient(dpy, sel->win);
1037 manage(Window w, XWindowAttributes *wa) {
1038 Client *c, *t = NULL;
1044 c = emallocz(sizeof(Client));
1045 c->tags = emallocz(sizeof initags);
1052 c->x = wa->x + v->x;
1053 c->y = wa->y + v->y;
1056 c->oldborder = wa->border_width;
1058 if(c->w == v->w && c->h == v->h) {
1061 c->border = wa->border_width;
1064 if(c->x + c->w + 2 * c->border > v->wax + v->waw)
1065 c->x = v->wax + v->waw - c->w - 2 * c->border;
1066 if(c->y + c->h + 2 * c->border > v->way + v->wah)
1067 c->y = v->way + v->wah - c->h - 2 * c->border;
1072 c->border = BORDERPX;
1074 wc.border_width = c->border;
1075 XConfigureWindow(dpy, w, CWBorderWidth, &wc);
1076 XSetWindowBorder(dpy, w, dc.norm[ColBorder]);
1077 configure(c); /* propagates border_width, if size doesn't change */
1079 XSelectInput(dpy, w, EnterWindowMask|FocusChangeMask|PropertyChangeMask|StructureNotifyMask);
1080 grabbuttons(c, False);
1082 if((rettrans = XGetTransientForHint(dpy, w, &trans) == Success))
1083 for(t = clients; t && t->win != trans; t = t->next);
1085 memcpy(c->tags, t->tags, sizeof initags);
1087 c->isfloating = (rettrans == Success) || c->isfixed;
1090 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h); /* some windows require this */
1092 XMapWindow(dpy, c->win);
1093 setclientstate(c, NormalState);
1098 mappingnotify(XEvent *e) {
1099 XMappingEvent *ev = &e->xmapping;
1101 XRefreshKeyboardMapping(ev);
1102 if(ev->request == MappingKeyboard)
1107 maprequest(XEvent *e) {
1108 static XWindowAttributes wa;
1109 XMapRequestEvent *ev = &e->xmaprequest;
1111 if(!XGetWindowAttributes(dpy, ev->window, &wa))
1113 if(wa.override_redirect)
1115 if(!getclient(ev->window))
1116 manage(ev->window, &wa);
1120 movemouse(Client *c) {
1121 int x1, y1, ocx, ocy, di, nx, ny;
1130 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1131 None, cursor[CurMove], CurrentTime) != GrabSuccess)
1133 XQueryPointer(dpy, root, &dummy, &dummy, &x1, &y1, &di, &di, &dui);
1135 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
1138 XUngrabPointer(dpy, CurrentTime);
1140 case ConfigureRequest:
1143 handler[ev.type](&ev);
1147 nx = ocx + (ev.xmotion.x - x1);
1148 ny = ocy + (ev.xmotion.y - y1);
1149 if(abs(v->wax - nx) < SNAP)
1151 else if(abs((v->wax + v->waw) - (nx + c->w + 2 * c->border)) < SNAP)
1152 nx = v->wax + v->waw - c->w - 2 * c->border;
1153 if(abs(v->way - ny) < SNAP)
1155 else if(abs((v->way + v->wah) - (ny + c->h + 2 * c->border)) < SNAP)
1156 ny = v->way + v->wah - c->h - 2 * c->border;
1157 if(!c->isfloating && (v->layout->arrange != floating) && (abs(nx - c->x) > SNAP || abs(ny - c->y) > SNAP))
1158 togglefloating(NULL);
1159 if((v->layout->arrange == floating) || c->isfloating)
1160 resize(c, nx, ny, c->w, c->h, False);
1167 nexttiled(Client *c, View *v) {
1168 for(; c && (c->isfloating || c->view != v || !isvisible(c)); c = c->next);
1173 propertynotify(XEvent *e) {
1176 XPropertyEvent *ev = &e->xproperty;
1178 if(ev->state == PropertyDelete)
1179 return; /* ignore */
1180 if((c = getclient(ev->window))) {
1183 case XA_WM_TRANSIENT_FOR:
1184 XGetTransientForHint(dpy, c->win, &trans);
1185 if(!c->isfloating && (c->isfloating = (getclient(trans) != NULL)))
1188 case XA_WM_NORMAL_HINTS:
1196 if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
1205 quit(const char *arg) {
1206 readin = running = False;
1210 reapply(const char *arg) {
1211 static Bool zerotags[LENGTH(tags)] = { 0 };
1214 for(c = clients; c; c = c->next) {
1215 memcpy(c->tags, zerotags, sizeof zerotags);
1222 resize(Client *c, int x, int y, int w, int h, Bool sizehints) {
1228 /* set minimum possible */
1234 /* temporarily remove base dimensions */
1238 /* adjust for aspect limits */
1239 if (c->minay > 0 && c->maxay > 0 && c->minax > 0 && c->maxax > 0) {
1240 if (w * c->maxay > h * c->maxax)
1241 w = h * c->maxax / c->maxay;
1242 else if (w * c->minay < h * c->minax)
1243 h = w * c->minay / c->minax;
1246 /* adjust for increment value */
1252 /* restore base dimensions */
1256 if(c->minw > 0 && w < c->minw)
1258 if(c->minh > 0 && h < c->minh)
1260 if(c->maxw > 0 && w > c->maxw)
1262 if(c->maxh > 0 && h > c->maxh)
1265 if(w <= 0 || h <= 0)
1268 x = v->w - w - 2 * c->border;
1270 y = v->h - h - 2 * c->border;
1271 if(x + w + 2 * c->border < v->x)
1273 if(y + h + 2 * c->border < v->y)
1275 if(c->x != x || c->y != y || c->w != w || c->h != h) {
1278 c->w = wc.width = w;
1279 c->h = wc.height = h;
1280 wc.border_width = c->border;
1281 XConfigureWindow(dpy, c->win,
1282 CWX|CWY|CWWidth|CWHeight|CWBorderWidth, &wc);
1289 resizemouse(Client *c) {
1298 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1299 None, cursor[CurResize], CurrentTime) != GrabSuccess)
1301 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->border - 1, c->h + c->border - 1);
1303 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask , &ev);
1306 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0,
1307 c->w + c->border - 1, c->h + c->border - 1);
1308 XUngrabPointer(dpy, CurrentTime);
1309 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1311 case ConfigureRequest:
1314 handler[ev.type](&ev);
1318 if((nw = ev.xmotion.x - ocx - 2 * c->border + 1) <= 0)
1320 if((nh = ev.xmotion.y - ocy - 2 * c->border + 1) <= 0)
1322 if(!c->isfloating && (v->layout->arrange != floating) && (abs(nw - c->w) > SNAP || abs(nh - c->h) > SNAP))
1323 togglefloating(NULL);
1324 if((v->layout->arrange == floating) || c->isfloating)
1325 resize(c, c->x, c->y, nw, nh, True);
1340 if(sel->isfloating || (v->layout->arrange == floating))
1341 XRaiseWindow(dpy, sel->win);
1342 if(v->layout->arrange != floating) {
1343 wc.stack_mode = Below;
1344 wc.sibling = v->barwin;
1345 if(!sel->isfloating) {
1346 XConfigureWindow(dpy, sel->win, CWSibling|CWStackMode, &wc);
1347 wc.sibling = sel->win;
1349 for(c = nexttiled(clients, v); c; c = nexttiled(c->next, v)) {
1352 XConfigureWindow(dpy, c->win, CWSibling|CWStackMode, &wc);
1353 wc.sibling = c->win;
1357 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1363 char sbuf[sizeof stext];
1366 unsigned int len, offset;
1369 /* main event loop, also reads status text from stdin */
1371 xfd = ConnectionNumber(dpy);
1374 len = sizeof stext - 1;
1375 sbuf[len] = stext[len] = '\0'; /* 0-terminator is never touched */
1379 FD_SET(STDIN_FILENO, &rd);
1381 if(select(xfd + 1, &rd, NULL, NULL, NULL) == -1) {
1384 eprint("select failed\n");
1386 if(FD_ISSET(STDIN_FILENO, &rd)) {
1387 switch((r = read(STDIN_FILENO, sbuf + offset, len - offset))) {
1389 strncpy(stext, strerror(errno), len);
1393 strncpy(stext, "EOF", 4);
1397 for(p = sbuf + offset; r > 0; p++, r--, offset++)
1398 if(*p == '\n' || *p == '\0') {
1400 strncpy(stext, sbuf, len);
1401 p += r - 1; /* p is sbuf + offset + r - 1 */
1402 for(r = 0; *(p - r) && *(p - r) != '\n'; r++);
1405 memmove(sbuf, p - r + 1, r);
1412 while(XPending(dpy)) {
1413 XNextEvent(dpy, &ev);
1414 if(handler[ev.type])
1415 (handler[ev.type])(&ev); /* call handler */
1422 unsigned int i, num;
1423 Window *wins, d1, d2;
1424 XWindowAttributes wa;
1427 if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1428 for(i = 0; i < num; i++) {
1429 if(!XGetWindowAttributes(dpy, wins[i], &wa)
1430 || wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1432 if(wa.map_state == IsViewable || getstate(wins[i]) == IconicState)
1433 manage(wins[i], &wa);
1435 for(i = 0; i < num; i++) { /* now the transients */
1436 if(!XGetWindowAttributes(dpy, wins[i], &wa))
1438 if(XGetTransientForHint(dpy, wins[i], &d1)
1439 && (wa.map_state == IsViewable || getstate(wins[i]) == IconicState))
1440 manage(wins[i], &wa);
1448 setclientstate(Client *c, long state) {
1449 long data[] = {state, None};
1451 XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1452 PropModeReplace, (unsigned char *)data, 2);
1456 setlayout(const char *arg) {
1462 if(v->layout == &layouts[LENGTH(layouts)])
1463 v->layout = &layouts[0];
1466 for(i = 0; i < LENGTH(layouts); i++)
1467 if(!strcmp(arg, layouts[i].symbol))
1469 if(i == LENGTH(layouts))
1471 v->layout = &layouts[i];
1480 setmwfact(const char *arg) {
1486 /* arg handling, manipulate mwfact */
1489 else if(sscanf(arg, "%lf", &delta) == 1) {
1490 if(arg[0] == '+' || arg[0] == '-')
1496 else if(v->mwfact > 0.9)
1506 XSetWindowAttributes wa;
1507 XineramaScreenInfo *info = NULL;
1510 wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1511 wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1512 wmatom[WMName] = XInternAtom(dpy, "WM_NAME", False);
1513 wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1514 netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1515 netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1518 wa.cursor = cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1519 cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1520 cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1522 if((isxinerama = XineramaIsActive(dpy)))
1523 info = XineramaQueryScreens(dpy, &nviews);
1524 #if defined(AIM_XINERAMA)
1526 nviews = 2; /* aim Xinerama */
1528 views = emallocz(nviews * sizeof(View));
1530 screen = DefaultScreen(dpy);
1531 root = RootWindow(dpy, screen);
1533 /* init appearance */
1534 dc.norm[ColBorder] = getcolor(NORMBORDERCOLOR);
1535 dc.norm[ColBG] = getcolor(NORMBGCOLOR);
1536 dc.norm[ColFG] = getcolor(NORMFGCOLOR);
1537 dc.sel[ColBorder] = getcolor(SELBORDERCOLOR);
1538 dc.sel[ColBG] = getcolor(SELBGCOLOR);
1539 dc.sel[ColFG] = getcolor(SELFGCOLOR);
1541 dc.h = bh = dc.font.height + 2;
1542 dc.drawable = XCreatePixmap(dpy, root, DisplayWidth(dpy, screen), bh, DefaultDepth(dpy, screen));
1543 dc.gc = XCreateGC(dpy, root, 0, 0);
1544 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
1546 XSetFont(dpy, dc.gc, dc.font.xfont->fid);
1548 for(blw = i = 0; i < LENGTH(layouts); i++) {
1549 i = textw(layouts[i].symbol);
1554 seltags = emallocz(sizeof initags);
1555 prevtags = emallocz(sizeof initags);
1556 memcpy(seltags, initags, sizeof initags);
1557 memcpy(prevtags, initags, sizeof initags);
1559 for(i = 0; i < nviews; i++) {
1563 if(nviews != 1 && isxinerama) {
1565 #if defined(AIM_XINERAMA)
1566 v->w = DisplayWidth(dpy, screen) / 2;
1567 v->x = (i == 0) ? 0 : v->w;
1569 v->h = DisplayHeight(dpy, screen);
1571 v->x = info[i].x_org;
1572 v->y = info[i].y_org;
1573 v->w = info[i].width;
1574 v->h = info[i].height;
1580 v->w = DisplayWidth(dpy, screen);
1581 v->h = DisplayHeight(dpy, screen);
1586 v->layout = &layouts[0];
1588 // TODO: bpos per screen?
1590 wa.override_redirect = 1;
1591 wa.background_pixmap = ParentRelative;
1592 wa.event_mask = ButtonPressMask|ExposureMask;
1595 v->barwin = XCreateWindow(dpy, root, v->x, v->y, v->w, bh, 0,
1596 DefaultDepth(dpy, screen), CopyFromParent, DefaultVisual(dpy, screen),
1597 CWOverrideRedirect|CWBackPixmap|CWEventMask, &wa);
1598 XDefineCursor(dpy, v->barwin, cursor[CurNormal]);
1600 XMapRaised(dpy, v->barwin);
1601 strcpy(stext, "dwm-"VERSION);
1603 /* EWMH support per view */
1604 XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1605 PropModeReplace, (unsigned char *) netatom, NetLast);
1607 /* select for events */
1608 wa.event_mask = SubstructureRedirectMask|SubstructureNotifyMask
1609 |EnterWindowMask|LeaveWindowMask|StructureNotifyMask;
1610 XChangeWindowAttributes(dpy, root, CWEventMask|CWCursor, &wa);
1611 XSelectInput(dpy, root, wa.event_mask);
1625 spawn(const char *arg) {
1626 static char *shell = NULL;
1628 if(!shell && !(shell = getenv("SHELL")))
1632 /* The double-fork construct avoids zombie processes and keeps the code
1633 * clean from stupid signal handlers. */
1637 close(ConnectionNumber(dpy));
1639 execl(shell, shell, "-c", arg, (char *)NULL);
1640 fprintf(stderr, "dwm: execl '%s -c %s'", shell, arg);
1649 tag(const char *arg) {
1654 for(i = 0; i < LENGTH(tags); i++)
1655 sel->tags[i] = (NULL == arg);
1656 sel->tags[idxoftag(arg)] = True;
1661 textnw(const char *text, unsigned int len) {
1665 XmbTextExtents(dc.font.set, text, len, NULL, &r);
1668 return XTextWidth(dc.font.xfont, text, len);
1672 textw(const char *text) {
1673 return textnw(text, strlen(text)) + dc.font.height;
1678 unsigned int i, n, nx, ny, nw, nh, mw, th;
1681 domwfact = dozoom = True;
1685 for(n = 0, c = nexttiled(clients, v); c; c = nexttiled(c->next, v))
1689 mw = (n == 1) ? v->waw : v->mwfact * v->waw;
1690 th = (n > 1) ? v->wah / (n - 1) : 0;
1691 if(n > 1 && th < bh)
1694 for(i = 0, c = mc = nexttiled(clients, v); c; c = nexttiled(c->next, v)) {
1695 if(i == 0) { /* master */
1698 nw = mw - 2 * c->border;
1699 nh = v->wah - 2 * c->border;
1701 else { /* tile window */
1704 nx += mc->w + 2 * mc->border;
1705 nw = v->waw - mw - 2 * c->border;
1707 if(i + 1 == n) /* remainder */
1708 nh = (v->way + v->wah) - ny - 2 * c->border;
1710 nh = th - 2 * c->border;
1712 resize(c, nx, ny, nw, nh, RESIZEHINTS);
1713 if((RESIZEHINTS) && ((c->h < bh) || (c->h > nh) || (c->w < bh) || (c->w > nw)))
1714 /* client doesn't accept size constraints */
1715 resize(c, nx, ny, nw, nh, False);
1716 if(n > 1 && th != v->wah)
1717 ny = c->y + c->h + 2 * c->border;
1723 togglebar(const char *arg) {
1725 bpos = (BARPOS == BarOff) ? BarTop : BARPOS;
1728 updatebarpos(selview);
1733 togglefloating(const char *arg) {
1736 sel->isfloating = !sel->isfloating;
1738 resize(sel, sel->x, sel->y, sel->w, sel->h, True);
1743 toggletag(const char *arg) {
1749 sel->tags[i] = !sel->tags[i];
1750 for(j = 0; j < LENGTH(tags) && !sel->tags[j]; j++);
1751 if(j == LENGTH(tags))
1752 sel->tags[i] = True; /* at least one tag must be enabled */
1757 toggleview(const char *arg) {
1761 seltags[i] = !seltags[i];
1762 for(j = 0; j < LENGTH(tags) && !seltags[j]; j++);
1763 if(j == LENGTH(tags))
1764 seltags[i] = True; /* at least one tag must be viewed */
1772 XMoveWindow(dpy, c->win, c->x, c->y);
1773 c->isbanned = False;
1777 unmanage(Client *c) {
1780 wc.border_width = c->oldborder;
1781 /* The server grab construct avoids race conditions. */
1783 XSetErrorHandler(xerrordummy);
1784 XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
1789 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1790 setclientstate(c, WithdrawnState);
1794 XSetErrorHandler(xerror);
1800 unmapnotify(XEvent *e) {
1802 XUnmapEvent *ev = &e->xunmap;
1804 if((c = getclient(ev->window)))
1809 updatebarpos(View *v) {
1820 XMoveWindow(dpy, v->barwin, v->x, v->y);
1824 XMoveWindow(dpy, v->barwin, v->x, v->y + v->wah);
1827 XMoveWindow(dpy, v->barwin, v->x, v->y - bh);
1831 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1835 updatesizehints(Client *c) {
1839 if(!XGetWMNormalHints(dpy, c->win, &size, &msize) || !size.flags)
1841 c->flags = size.flags;
1842 if(c->flags & PBaseSize) {
1843 c->basew = size.base_width;
1844 c->baseh = size.base_height;
1846 else if(c->flags & PMinSize) {
1847 c->basew = size.min_width;
1848 c->baseh = size.min_height;
1851 c->basew = c->baseh = 0;
1852 if(c->flags & PResizeInc) {
1853 c->incw = size.width_inc;
1854 c->inch = size.height_inc;
1857 c->incw = c->inch = 0;
1858 if(c->flags & PMaxSize) {
1859 c->maxw = size.max_width;
1860 c->maxh = size.max_height;
1863 c->maxw = c->maxh = 0;
1864 if(c->flags & PMinSize) {
1865 c->minw = size.min_width;
1866 c->minh = size.min_height;
1868 else if(c->flags & PBaseSize) {
1869 c->minw = size.base_width;
1870 c->minh = size.base_height;
1873 c->minw = c->minh = 0;
1874 if(c->flags & PAspect) {
1875 c->minax = size.min_aspect.x;
1876 c->maxax = size.max_aspect.x;
1877 c->minay = size.min_aspect.y;
1878 c->maxay = size.max_aspect.y;
1881 c->minax = c->maxax = c->minay = c->maxay = 0;
1882 c->isfixed = (c->maxw && c->minw && c->maxh && c->minh
1883 && c->maxw == c->minw && c->maxh == c->minh);
1887 updatetitle(Client *c) {
1888 if(!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
1889 gettextprop(c->win, wmatom[WMName], c->name, sizeof c->name);
1893 updatewmhints(Client *c) {
1896 if((wmh = XGetWMHints(dpy, c->win))) {
1897 c->isurgent = (wmh->flags & XUrgencyHint) ? True : False;
1903 view(const char *arg) {
1905 Bool tmp[LENGTH(tags)];
1907 for(i = 0; i < LENGTH(tags); i++)
1908 tmp[i] = (NULL == arg);
1909 tmp[idxoftag(arg)] = True;
1911 if(memcmp(seltags, tmp, sizeof initags) != 0) {
1912 memcpy(prevtags, seltags, sizeof initags);
1913 memcpy(seltags, tmp, sizeof initags);
1924 XQueryPointer(dpy, root, &win, &win, &x, &y, &i, &i, &mask);
1925 for(i = 0; i < nviews; i++) {
1926 if((x >= views[i].x && x < views[i].x + views[i].w)
1927 && (y >= views[i].y && y < views[i].y + views[i].h))
1934 viewprevtag(const char *arg) {
1935 static Bool tmp[LENGTH(tags)];
1937 memcpy(tmp, seltags, sizeof initags);
1938 memcpy(seltags, prevtags, sizeof initags);
1939 memcpy(prevtags, tmp, sizeof initags);
1943 /* There's no way to check accesses to destroyed windows, thus those cases are
1944 * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
1945 * default error handler, which may call exit. */
1947 xerror(Display *dpy, XErrorEvent *ee) {
1948 if(ee->error_code == BadWindow
1949 || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1950 || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1951 || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1952 || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1953 || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1954 || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1955 || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1957 fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1958 ee->request_code, ee->error_code);
1959 return xerrorxlib(dpy, ee); /* may call exit */
1963 xerrordummy(Display *dpy, XErrorEvent *ee) {
1967 /* Startup Error handler to check if another window manager
1968 * is already running. */
1970 xerrorstart(Display *dpy, XErrorEvent *ee) {
1976 zoom(const char *arg) {
1979 if(!sel || !dozoom || sel->isfloating)
1981 if(c == nexttiled(clients, c->view))
1982 if(!(c = nexttiled(c->next, c->view)))
1991 main(int argc, char *argv[]) {
1992 if(argc == 2 && !strcmp("-v", argv[1]))
1993 eprint("dwm-"VERSION", © 2006-2008 dwm engineers, see LICENSE for details\n");
1995 eprint("usage: dwm [-v]\n");
1997 setlocale(LC_CTYPE, "");
1998 if(!(dpy = XOpenDisplay(0)))
1999 eprint("dwm: cannot open display\n");