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 domwfact = True;
232 Bool otherwm, readin;
236 Client *clients = NULL;
238 Client *stack = NULL;
239 Cursor cursor[CurLast];
246 /* configuration, allows nested code to access above variables */
248 #define TAGSZ (LENGTH(tags) * sizeof(Bool))
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, TAGSZ);
299 for(c = clients; c; c = c->next)
305 for(i = 0; i < nviews; i++) {
306 views[i].layout->arrange(&views[i]);
321 attachstack(Client *c) {
330 XMoveWindow(dpy, c->win, c->x + 3 * c->view->w, c->y);
335 buttonpress(XEvent *e) {
338 XButtonPressedEvent *ev = &e->xbutton;
340 if(ev->window == selview->barwin) {
342 for(i = 0; i < LENGTH(tags); i++) {
343 if(&views[vtags[i]] != selview)
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) && ev->window != root)
659 if((c = getclient(ev->window)))
666 eprint(const char *errstr, ...) {
669 va_start(ap, errstr);
670 vfprintf(stderr, errstr, ap);
678 XExposeEvent *ev = &e->xexpose;
680 if(ev->count == 0 && ((v = getviewbar(ev->window))))
685 floating(View *v) { /* default floating layout */
688 domwfact = dozoom = False;
689 for(c = clients; c; c = c->next)
691 resize(c, c->x, c->y, c->w, c->h, True);
703 if(!c || (c && !isvisible(c)))
704 for(c = stack; c && (!isvisible(c) || c->view != selview); c = c->snext);
705 if(sel && sel != c) {
706 grabbuttons(sel, False);
707 XSetWindowBorder(dpy, sel->win, dc.norm[ColBorder]);
712 grabbuttons(c, True);
716 XSetWindowBorder(dpy, c->win, dc.sel[ColBorder]);
717 XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
721 XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
726 focusin(XEvent *e) { /* there are some broken focus acquiring clients */
727 XFocusChangeEvent *ev = &e->xfocus;
729 if(sel && ev->window != sel->win)
730 XSetInputFocus(dpy, sel->win, RevertToPointerRoot, CurrentTime);
734 focusnext(const char *arg) {
739 for(c = sel->next; c && !isvisible(c); c = c->next);
741 for(c = clients; c && !isvisible(c); c = c->next);
749 focusprev(const char *arg) {
754 for(c = sel->prev; c && !isvisible(c); c = c->prev);
756 for(c = clients; c && c->next; c = c->next);
757 for(; c && !isvisible(c); c = c->prev);
766 getclient(Window w) {
769 for(c = clients; c && c->win != w; c = c->next);
774 getcolor(const char *colstr) {
775 Colormap cmap = DefaultColormap(dpy, screen);
778 if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
779 eprint("error, cannot allocate color '%s'\n", colstr);
784 getviewbar(Window barwin) {
787 for(i = 0; i < nviews; i++)
788 if(views[i].barwin == barwin)
797 unsigned char *p = NULL;
798 unsigned long n, extra;
801 status = XGetWindowProperty(dpy, w, wmatom[WMState], 0L, 2L, False, wmatom[WMState],
802 &real, &format, &n, &extra, (unsigned char **)&p);
803 if(status != Success)
812 gettextprop(Window w, Atom atom, char *text, unsigned int size) {
817 if(!text || size == 0)
820 XGetTextProperty(dpy, w, &name, atom);
823 if(name.encoding == XA_STRING)
824 strncpy(text, (char *)name.value, size - 1);
826 if(XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success
828 strncpy(text, *list, size - 1);
829 XFreeStringList(list);
832 text[size - 1] = '\0';
838 grabbuttons(Client *c, Bool focused) {
839 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
842 XGrabButton(dpy, Button1, MODKEY, c->win, False, BUTTONMASK,
843 GrabModeAsync, GrabModeSync, None, None);
844 XGrabButton(dpy, Button1, MODKEY|LockMask, c->win, False, BUTTONMASK,
845 GrabModeAsync, GrabModeSync, None, None);
846 XGrabButton(dpy, Button1, MODKEY|numlockmask, c->win, False, BUTTONMASK,
847 GrabModeAsync, GrabModeSync, None, None);
848 XGrabButton(dpy, Button1, MODKEY|numlockmask|LockMask, c->win, False, BUTTONMASK,
849 GrabModeAsync, GrabModeSync, None, None);
851 XGrabButton(dpy, Button2, MODKEY, c->win, False, BUTTONMASK,
852 GrabModeAsync, GrabModeSync, None, None);
853 XGrabButton(dpy, Button2, MODKEY|LockMask, c->win, False, BUTTONMASK,
854 GrabModeAsync, GrabModeSync, None, None);
855 XGrabButton(dpy, Button2, MODKEY|numlockmask, c->win, False, BUTTONMASK,
856 GrabModeAsync, GrabModeSync, None, None);
857 XGrabButton(dpy, Button2, MODKEY|numlockmask|LockMask, c->win, False, BUTTONMASK,
858 GrabModeAsync, GrabModeSync, None, None);
860 XGrabButton(dpy, Button3, MODKEY, c->win, False, BUTTONMASK,
861 GrabModeAsync, GrabModeSync, None, None);
862 XGrabButton(dpy, Button3, MODKEY|LockMask, c->win, False, BUTTONMASK,
863 GrabModeAsync, GrabModeSync, None, None);
864 XGrabButton(dpy, Button3, MODKEY|numlockmask, c->win, False, BUTTONMASK,
865 GrabModeAsync, GrabModeSync, None, None);
866 XGrabButton(dpy, Button3, MODKEY|numlockmask|LockMask, c->win, False, BUTTONMASK,
867 GrabModeAsync, GrabModeSync, None, None);
870 XGrabButton(dpy, AnyButton, AnyModifier, c->win, False, BUTTONMASK,
871 GrabModeAsync, GrabModeSync, None, None);
878 XModifierKeymap *modmap;
880 /* init modifier map */
881 modmap = XGetModifierMapping(dpy);
882 for(i = 0; i < 8; i++)
883 for(j = 0; j < modmap->max_keypermod; j++) {
884 if(modmap->modifiermap[i * modmap->max_keypermod + j] == XKeysymToKeycode(dpy, XK_Num_Lock))
885 numlockmask = (1 << i);
887 XFreeModifiermap(modmap);
889 XUngrabKey(dpy, AnyKey, AnyModifier, root);
890 for(i = 0; i < LENGTH(keys); i++) {
891 code = XKeysymToKeycode(dpy, keys[i].keysym);
892 XGrabKey(dpy, code, keys[i].mod, root, True,
893 GrabModeAsync, GrabModeAsync);
894 XGrabKey(dpy, code, keys[i].mod|LockMask, root, True,
895 GrabModeAsync, GrabModeAsync);
896 XGrabKey(dpy, code, keys[i].mod|numlockmask, root, True,
897 GrabModeAsync, GrabModeAsync);
898 XGrabKey(dpy, code, keys[i].mod|numlockmask|LockMask, root, True,
899 GrabModeAsync, GrabModeAsync);
904 idxoftag(const char *t) {
907 for(i = 0; (i < LENGTH(tags)) && (tags[i] != t); i++);
908 return (i < LENGTH(tags)) ? i : 0;
912 initfont(const char *fontstr) {
913 char *def, **missing;
918 XFreeFontSet(dpy, dc.font.set);
919 dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
922 fprintf(stderr, "dwm: missing fontset: %s\n", missing[n]);
923 XFreeStringList(missing);
926 XFontSetExtents *font_extents;
927 XFontStruct **xfonts;
929 dc.font.ascent = dc.font.descent = 0;
930 font_extents = XExtentsOfFontSet(dc.font.set);
931 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
932 for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
933 if(dc.font.ascent < (*xfonts)->ascent)
934 dc.font.ascent = (*xfonts)->ascent;
935 if(dc.font.descent < (*xfonts)->descent)
936 dc.font.descent = (*xfonts)->descent;
942 XFreeFont(dpy, dc.font.xfont);
943 dc.font.xfont = NULL;
944 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr))
945 && !(dc.font.xfont = XLoadQueryFont(dpy, "fixed")))
946 eprint("error, cannot load font: '%s'\n", fontstr);
947 dc.font.ascent = dc.font.xfont->ascent;
948 dc.font.descent = dc.font.xfont->descent;
950 dc.font.height = dc.font.ascent + dc.font.descent;
954 isoccupied(unsigned int t) {
957 for(c = clients; c; c = c->next)
964 isprotodel(Client *c) {
969 if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
970 for(i = 0; !ret && i < n; i++)
971 if(protocols[i] == wmatom[WMDelete])
979 isurgent(unsigned int t) {
982 for(c = clients; c; c = c->next)
983 if(c->isurgent && c->tags[t])
989 isvisible(Client *c) {
992 for(i = 0; i < LENGTH(tags); i++)
993 if(c->tags[i] && seltags[i])
999 keypress(XEvent *e) {
1005 keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
1006 for(i = 0; i < LENGTH(keys); i++)
1007 if(keysym == keys[i].keysym
1008 && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state))
1011 keys[i].func(keys[i].arg);
1016 killclient(const char *arg) {
1021 if(isprotodel(sel)) {
1022 ev.type = ClientMessage;
1023 ev.xclient.window = sel->win;
1024 ev.xclient.message_type = wmatom[WMProtocols];
1025 ev.xclient.format = 32;
1026 ev.xclient.data.l[0] = wmatom[WMDelete];
1027 ev.xclient.data.l[1] = CurrentTime;
1028 XSendEvent(dpy, sel->win, False, NoEventMask, &ev);
1031 XKillClient(dpy, sel->win);
1035 manage(Window w, XWindowAttributes *wa) {
1036 Client *c, *t = NULL;
1042 c = emallocz(sizeof(Client));
1043 c->tags = emallocz(TAGSZ);
1050 c->x = wa->x + v->x;
1051 c->y = wa->y + v->y;
1054 c->oldborder = wa->border_width;
1056 if(c->w == v->w && c->h == v->h) {
1059 c->border = wa->border_width;
1062 if(c->x + c->w + 2 * c->border > v->wax + v->waw)
1063 c->x = v->wax + v->waw - c->w - 2 * c->border;
1064 if(c->y + c->h + 2 * c->border > v->way + v->wah)
1065 c->y = v->way + v->wah - c->h - 2 * c->border;
1070 c->border = BORDERPX;
1072 wc.border_width = c->border;
1073 XConfigureWindow(dpy, w, CWBorderWidth, &wc);
1074 XSetWindowBorder(dpy, w, dc.norm[ColBorder]);
1075 configure(c); /* propagates border_width, if size doesn't change */
1077 XSelectInput(dpy, w, EnterWindowMask|FocusChangeMask|PropertyChangeMask|StructureNotifyMask);
1078 grabbuttons(c, False);
1080 if((rettrans = XGetTransientForHint(dpy, w, &trans) == Success))
1081 for(t = clients; t && t->win != trans; t = t->next);
1083 memcpy(c->tags, t->tags, TAGSZ);
1085 c->isfloating = (rettrans == Success) || c->isfixed;
1088 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h); /* some windows require this */
1090 XMapWindow(dpy, c->win);
1091 setclientstate(c, NormalState);
1096 mappingnotify(XEvent *e) {
1097 XMappingEvent *ev = &e->xmapping;
1099 XRefreshKeyboardMapping(ev);
1100 if(ev->request == MappingKeyboard)
1105 maprequest(XEvent *e) {
1106 static XWindowAttributes wa;
1107 XMapRequestEvent *ev = &e->xmaprequest;
1109 if(!XGetWindowAttributes(dpy, ev->window, &wa))
1111 if(wa.override_redirect)
1113 if(!getclient(ev->window))
1114 manage(ev->window, &wa);
1118 movemouse(Client *c) {
1119 int x1, y1, ocx, ocy, di, nx, ny;
1128 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1129 None, cursor[CurMove], CurrentTime) != GrabSuccess)
1131 XQueryPointer(dpy, root, &dummy, &dummy, &x1, &y1, &di, &di, &dui);
1133 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
1136 XUngrabPointer(dpy, CurrentTime);
1138 case ConfigureRequest:
1141 handler[ev.type](&ev);
1145 nx = ocx + (ev.xmotion.x - x1);
1146 ny = ocy + (ev.xmotion.y - y1);
1147 if(abs(v->wax - nx) < SNAP)
1149 else if(abs((v->wax + v->waw) - (nx + c->w + 2 * c->border)) < SNAP)
1150 nx = v->wax + v->waw - c->w - 2 * c->border;
1151 if(abs(v->way - ny) < SNAP)
1153 else if(abs((v->way + v->wah) - (ny + c->h + 2 * c->border)) < SNAP)
1154 ny = v->way + v->wah - c->h - 2 * c->border;
1155 if(!c->isfloating && (v->layout->arrange != floating) && (abs(nx - c->x) > SNAP || abs(ny - c->y) > SNAP))
1156 togglefloating(NULL);
1157 if((v->layout->arrange == floating) || c->isfloating)
1158 resize(c, nx, ny, c->w, c->h, False);
1165 nexttiled(Client *c, View *v) {
1166 for(; c && (c->isfloating || c->view != v || !isvisible(c)); c = c->next);
1171 propertynotify(XEvent *e) {
1174 XPropertyEvent *ev = &e->xproperty;
1176 if(ev->state == PropertyDelete)
1177 return; /* ignore */
1178 if((c = getclient(ev->window))) {
1181 case XA_WM_TRANSIENT_FOR:
1182 XGetTransientForHint(dpy, c->win, &trans);
1183 if(!c->isfloating && (c->isfloating = (getclient(trans) != NULL)))
1186 case XA_WM_NORMAL_HINTS:
1194 if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
1203 quit(const char *arg) {
1204 readin = running = False;
1208 reapply(const char *arg) {
1209 static Bool zerotags[LENGTH(tags)] = { 0 };
1212 for(c = clients; c; c = c->next) {
1213 memcpy(c->tags, zerotags, sizeof zerotags);
1220 resize(Client *c, int x, int y, int w, int h, Bool sizehints) {
1226 /* set minimum possible */
1232 /* temporarily remove base dimensions */
1236 /* adjust for aspect limits */
1237 if (c->minay > 0 && c->maxay > 0 && c->minax > 0 && c->maxax > 0) {
1238 if (w * c->maxay > h * c->maxax)
1239 w = h * c->maxax / c->maxay;
1240 else if (w * c->minay < h * c->minax)
1241 h = w * c->minay / c->minax;
1244 /* adjust for increment value */
1250 /* restore base dimensions */
1254 if(c->minw > 0 && w < c->minw)
1256 if(c->minh > 0 && h < c->minh)
1258 if(c->maxw > 0 && w > c->maxw)
1260 if(c->maxh > 0 && h > c->maxh)
1263 if(w <= 0 || h <= 0)
1266 x = v->w - w - 2 * c->border;
1268 y = v->h - h - 2 * c->border;
1269 if(x + w + 2 * c->border < v->x)
1271 if(y + h + 2 * c->border < v->y)
1273 if(c->x != x || c->y != y || c->w != w || c->h != h) {
1276 c->w = wc.width = w;
1277 c->h = wc.height = h;
1278 wc.border_width = c->border;
1279 XConfigureWindow(dpy, c->win,
1280 CWX|CWY|CWWidth|CWHeight|CWBorderWidth, &wc);
1287 resizemouse(Client *c) {
1296 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1297 None, cursor[CurResize], CurrentTime) != GrabSuccess)
1299 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->border - 1, c->h + c->border - 1);
1301 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask , &ev);
1304 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0,
1305 c->w + c->border - 1, c->h + c->border - 1);
1306 XUngrabPointer(dpy, CurrentTime);
1307 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1309 case ConfigureRequest:
1312 handler[ev.type](&ev);
1316 if((nw = ev.xmotion.x - ocx - 2 * c->border + 1) <= 0)
1318 if((nh = ev.xmotion.y - ocy - 2 * c->border + 1) <= 0)
1320 if(!c->isfloating && (v->layout->arrange != floating) && (abs(nw - c->w) > SNAP || abs(nh - c->h) > SNAP))
1321 togglefloating(NULL);
1322 if((v->layout->arrange == floating) || c->isfloating)
1323 resize(c, c->x, c->y, nw, nh, True);
1338 if(sel->isfloating || (v->layout->arrange == floating))
1339 XRaiseWindow(dpy, sel->win);
1340 if(v->layout->arrange != floating) {
1341 wc.stack_mode = Below;
1342 wc.sibling = v->barwin;
1343 if(!sel->isfloating) {
1344 XConfigureWindow(dpy, sel->win, CWSibling|CWStackMode, &wc);
1345 wc.sibling = sel->win;
1347 for(c = nexttiled(clients, v); c; c = nexttiled(c->next, v)) {
1350 XConfigureWindow(dpy, c->win, CWSibling|CWStackMode, &wc);
1351 wc.sibling = c->win;
1355 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1361 char sbuf[sizeof stext];
1364 unsigned int len, offset;
1367 /* main event loop, also reads status text from stdin */
1369 xfd = ConnectionNumber(dpy);
1372 len = sizeof stext - 1;
1373 sbuf[len] = stext[len] = '\0'; /* 0-terminator is never touched */
1377 FD_SET(STDIN_FILENO, &rd);
1379 if(select(xfd + 1, &rd, NULL, NULL, NULL) == -1) {
1382 eprint("select failed\n");
1384 if(FD_ISSET(STDIN_FILENO, &rd)) {
1385 switch((r = read(STDIN_FILENO, sbuf + offset, len - offset))) {
1387 strncpy(stext, strerror(errno), len);
1391 strncpy(stext, "EOF", 4);
1395 for(p = sbuf + offset; r > 0; p++, r--, offset++)
1396 if(*p == '\n' || *p == '\0') {
1398 strncpy(stext, sbuf, len);
1399 p += r - 1; /* p is sbuf + offset + r - 1 */
1400 for(r = 0; *(p - r) && *(p - r) != '\n'; r++);
1403 memmove(sbuf, p - r + 1, r);
1410 while(XPending(dpy)) {
1411 XNextEvent(dpy, &ev);
1412 if(handler[ev.type])
1413 (handler[ev.type])(&ev); /* call handler */
1420 unsigned int i, num;
1421 Window *wins, d1, d2;
1422 XWindowAttributes wa;
1425 if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1426 for(i = 0; i < num; i++) {
1427 if(!XGetWindowAttributes(dpy, wins[i], &wa)
1428 || wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1430 if(wa.map_state == IsViewable || getstate(wins[i]) == IconicState)
1431 manage(wins[i], &wa);
1433 for(i = 0; i < num; i++) { /* now the transients */
1434 if(!XGetWindowAttributes(dpy, wins[i], &wa))
1436 if(XGetTransientForHint(dpy, wins[i], &d1)
1437 && (wa.map_state == IsViewable || getstate(wins[i]) == IconicState))
1438 manage(wins[i], &wa);
1446 setclientstate(Client *c, long state) {
1447 long data[] = {state, None};
1449 XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1450 PropModeReplace, (unsigned char *)data, 2);
1454 setlayout(const char *arg) {
1460 if(v->layout == &layouts[LENGTH(layouts)])
1461 v->layout = &layouts[0];
1464 for(i = 0; i < LENGTH(layouts); i++)
1465 if(!strcmp(arg, layouts[i].symbol))
1467 if(i == LENGTH(layouts))
1469 v->layout = &layouts[i];
1478 setmwfact(const char *arg) {
1484 /* arg handling, manipulate mwfact */
1487 else if(sscanf(arg, "%lf", &delta) == 1) {
1488 if(arg[0] == '+' || arg[0] == '-')
1494 else if(v->mwfact > 0.9)
1504 XSetWindowAttributes wa;
1505 XineramaScreenInfo *info = NULL;
1508 wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1509 wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1510 wmatom[WMName] = XInternAtom(dpy, "WM_NAME", False);
1511 wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1512 netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1513 netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1516 wa.cursor = cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1517 cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1518 cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1520 if(XineramaIsActive(dpy))
1521 info = XineramaQueryScreens(dpy, &nviews);
1523 #if defined(AIM_XINERAMA)
1524 nviews = 2; /* aim Xinerama */
1526 views = emallocz(nviews * sizeof(View));
1528 screen = DefaultScreen(dpy);
1529 root = RootWindow(dpy, screen);
1531 /* init appearance */
1532 dc.norm[ColBorder] = getcolor(NORMBORDERCOLOR);
1533 dc.norm[ColBG] = getcolor(NORMBGCOLOR);
1534 dc.norm[ColFG] = getcolor(NORMFGCOLOR);
1535 dc.sel[ColBorder] = getcolor(SELBORDERCOLOR);
1536 dc.sel[ColBG] = getcolor(SELBGCOLOR);
1537 dc.sel[ColFG] = getcolor(SELFGCOLOR);
1539 dc.h = bh = dc.font.height + 2;
1540 dc.drawable = XCreatePixmap(dpy, root, DisplayWidth(dpy, screen), bh, DefaultDepth(dpy, screen));
1541 dc.gc = XCreateGC(dpy, root, 0, 0);
1542 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
1544 XSetFont(dpy, dc.gc, dc.font.xfont->fid);
1546 for(blw = i = 0; i < LENGTH(layouts); i++) {
1547 i = textw(layouts[i].symbol);
1552 seltags = emallocz(TAGSZ);
1553 prevtags = emallocz(TAGSZ);
1555 /* check, if vtags need assistance, because there is only 1 view */
1557 for(i = 0; i < LENGTH(tags); i++)
1560 for(i = 0; i < nviews; i++) {
1564 /* select first tag in each view */
1565 for(j = 0; j < LENGTH(tags); j++)
1567 seltags[j] = prevtags[j] = True;
1574 #if defined(AIM_XINERAMA)
1575 v->w = DisplayWidth(dpy, screen) / 2;
1576 v->x = (i == 0) ? 0 : v->w;
1578 v->h = DisplayHeight(dpy, screen);
1580 v->x = info[i].x_org;
1581 v->y = info[i].y_org;
1582 v->w = info[i].width;
1583 v->h = info[i].height;
1589 v->w = DisplayWidth(dpy, screen);
1590 v->h = DisplayHeight(dpy, screen);
1595 v->layout = &layouts[0];
1597 // TODO: bpos per screen?
1599 wa.override_redirect = 1;
1600 wa.background_pixmap = ParentRelative;
1601 wa.event_mask = ButtonPressMask|ExposureMask;
1604 v->barwin = XCreateWindow(dpy, root, v->x, v->y, v->w, bh, 0,
1605 DefaultDepth(dpy, screen), CopyFromParent, DefaultVisual(dpy, screen),
1606 CWOverrideRedirect|CWBackPixmap|CWEventMask, &wa);
1607 XDefineCursor(dpy, v->barwin, cursor[CurNormal]);
1609 XMapRaised(dpy, v->barwin);
1610 strcpy(stext, "dwm-"VERSION);
1612 /* EWMH support per view */
1613 XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1614 PropModeReplace, (unsigned char *) netatom, NetLast);
1616 /* select for events */
1617 wa.event_mask = SubstructureRedirectMask|SubstructureNotifyMask
1618 |EnterWindowMask|LeaveWindowMask|StructureNotifyMask;
1619 XChangeWindowAttributes(dpy, root, CWEventMask|CWCursor, &wa);
1620 XSelectInput(dpy, root, wa.event_mask);
1634 spawn(const char *arg) {
1635 static char *shell = NULL;
1637 if(!shell && !(shell = getenv("SHELL")))
1641 /* The double-fork construct avoids zombie processes and keeps the code
1642 * clean from stupid signal handlers. */
1646 close(ConnectionNumber(dpy));
1648 execl(shell, shell, "-c", arg, (char *)NULL);
1649 fprintf(stderr, "dwm: execl '%s -c %s'", shell, arg);
1658 tag(const char *arg) {
1663 for(i = 0; i < LENGTH(tags); i++)
1664 sel->tags[i] = (NULL == arg);
1665 sel->tags[idxoftag(arg)] = True;
1670 textnw(const char *text, unsigned int len) {
1674 XmbTextExtents(dc.font.set, text, len, NULL, &r);
1677 return XTextWidth(dc.font.xfont, text, len);
1681 textw(const char *text) {
1682 return textnw(text, strlen(text)) + dc.font.height;
1687 unsigned int i, n, nx, ny, nw, nh, mw, th;
1690 domwfact = dozoom = True;
1694 for(n = 0, c = nexttiled(clients, v); c; c = nexttiled(c->next, v))
1698 mw = (n == 1) ? v->waw : v->mwfact * v->waw;
1699 th = (n > 1) ? v->wah / (n - 1) : 0;
1700 if(n > 1 && th < bh)
1703 for(i = 0, c = mc = nexttiled(clients, v); c; c = nexttiled(c->next, v)) {
1704 if(i == 0) { /* master */
1705 nw = mw - 2 * c->border;
1706 nh = v->wah - 2 * c->border;
1708 else { /* tile window */
1711 nx += mc->w + 2 * mc->border;
1712 nw = v->waw - mw - 2 * c->border;
1714 if(i + 1 == n) /* remainder */
1715 nh = (v->way + v->wah) - ny - 2 * c->border;
1717 nh = th - 2 * c->border;
1719 resize(c, nx, ny, nw, nh, RESIZEHINTS);
1720 if((RESIZEHINTS) && ((c->h < bh) || (c->h > nh) || (c->w < bh) || (c->w > nw)))
1721 /* client doesn't accept size constraints */
1722 resize(c, nx, ny, nw, nh, False);
1723 if(n > 1 && th != v->wah)
1724 ny = c->y + c->h + 2 * c->border;
1730 togglebar(const char *arg) {
1732 bpos = (BARPOS == BarOff) ? BarTop : BARPOS;
1735 updatebarpos(selview);
1740 togglefloating(const char *arg) {
1743 sel->isfloating = !sel->isfloating;
1745 resize(sel, sel->x, sel->y, sel->w, sel->h, True);
1750 toggletag(const char *arg) {
1756 sel->tags[i] = !sel->tags[i];
1757 for(j = 0; j < LENGTH(tags) && !sel->tags[j]; j++);
1758 if(j == LENGTH(tags))
1759 sel->tags[i] = True; /* at least one tag must be enabled */
1764 toggleview(const char *arg) {
1768 seltags[i] = !seltags[i];
1769 for(j = 0; j < LENGTH(tags) && !seltags[j]; j++);
1770 if(j == LENGTH(tags))
1771 seltags[i] = True; /* at least one tag must be viewed */
1779 XMoveWindow(dpy, c->win, c->x, c->y);
1780 c->isbanned = False;
1784 unmanage(Client *c) {
1787 wc.border_width = c->oldborder;
1788 /* The server grab construct avoids race conditions. */
1790 XSetErrorHandler(xerrordummy);
1791 XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
1796 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1797 setclientstate(c, WithdrawnState);
1801 XSetErrorHandler(xerror);
1807 unmapnotify(XEvent *e) {
1809 XUnmapEvent *ev = &e->xunmap;
1811 if((c = getclient(ev->window)))
1816 updatebarpos(View *v) {
1827 XMoveWindow(dpy, v->barwin, v->x, v->y);
1831 XMoveWindow(dpy, v->barwin, v->x, v->y + v->wah);
1834 XMoveWindow(dpy, v->barwin, v->x, v->y - bh);
1838 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1842 updatesizehints(Client *c) {
1846 if(!XGetWMNormalHints(dpy, c->win, &size, &msize) || !size.flags)
1848 c->flags = size.flags;
1849 if(c->flags & PBaseSize) {
1850 c->basew = size.base_width;
1851 c->baseh = size.base_height;
1853 else if(c->flags & PMinSize) {
1854 c->basew = size.min_width;
1855 c->baseh = size.min_height;
1858 c->basew = c->baseh = 0;
1859 if(c->flags & PResizeInc) {
1860 c->incw = size.width_inc;
1861 c->inch = size.height_inc;
1864 c->incw = c->inch = 0;
1865 if(c->flags & PMaxSize) {
1866 c->maxw = size.max_width;
1867 c->maxh = size.max_height;
1870 c->maxw = c->maxh = 0;
1871 if(c->flags & PMinSize) {
1872 c->minw = size.min_width;
1873 c->minh = size.min_height;
1875 else if(c->flags & PBaseSize) {
1876 c->minw = size.base_width;
1877 c->minh = size.base_height;
1880 c->minw = c->minh = 0;
1881 if(c->flags & PAspect) {
1882 c->minax = size.min_aspect.x;
1883 c->maxax = size.max_aspect.x;
1884 c->minay = size.min_aspect.y;
1885 c->maxay = size.max_aspect.y;
1888 c->minax = c->maxax = c->minay = c->maxay = 0;
1889 c->isfixed = (c->maxw && c->minw && c->maxh && c->minh
1890 && c->maxw == c->minw && c->maxh == c->minh);
1894 updatetitle(Client *c) {
1895 if(!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
1896 gettextprop(c->win, wmatom[WMName], c->name, sizeof c->name);
1900 updatewmhints(Client *c) {
1903 if((wmh = XGetWMHints(dpy, c->win))) {
1904 c->isurgent = (wmh->flags & XUrgencyHint) ? True : False;
1910 view(const char *arg) {
1912 Bool tmp[LENGTH(tags)];
1914 for(i = 0; i < LENGTH(tags); i++)
1915 tmp[i] = (NULL == arg);
1916 tmp[idxoftag(arg)] = True;
1918 if(memcmp(seltags, tmp, TAGSZ) != 0) {
1919 memcpy(prevtags, seltags, TAGSZ);
1920 memcpy(seltags, tmp, TAGSZ);
1931 XQueryPointer(dpy, root, &win, &win, &x, &y, &i, &i, &mask);
1932 for(i = 0; i < nviews; i++) {
1933 if((x >= views[i].x && x < views[i].x + views[i].w)
1934 && (y >= views[i].y && y < views[i].y + views[i].h))
1941 viewprevtag(const char *arg) {
1942 static Bool tmp[LENGTH(tags)];
1944 memcpy(tmp, seltags, TAGSZ);
1945 memcpy(seltags, prevtags, TAGSZ);
1946 memcpy(prevtags, tmp, TAGSZ);
1950 /* There's no way to check accesses to destroyed windows, thus those cases are
1951 * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
1952 * default error handler, which may call exit. */
1954 xerror(Display *dpy, XErrorEvent *ee) {
1955 if(ee->error_code == BadWindow
1956 || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1957 || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1958 || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1959 || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1960 || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1961 || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1962 || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1964 fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1965 ee->request_code, ee->error_code);
1966 return xerrorxlib(dpy, ee); /* may call exit */
1970 xerrordummy(Display *dpy, XErrorEvent *ee) {
1974 /* Startup Error handler to check if another window manager
1975 * is already running. */
1977 xerrorstart(Display *dpy, XErrorEvent *ee) {
1983 zoom(const char *arg) {
1986 if(!sel || !dozoom || sel->isfloating)
1988 if(c == nexttiled(clients, c->view))
1989 if(!(c = nexttiled(c->next, c->view)))
1998 main(int argc, char *argv[]) {
1999 if(argc == 2 && !strcmp("-v", argv[1]))
2000 eprint("dwm-"VERSION", © 2006-2008 dwm engineers, see LICENSE for details\n");
2002 eprint("usage: dwm [-v]\n");
2004 setlocale(LC_CTYPE, "");
2005 if(!(dpy = XOpenDisplay(0)))
2006 eprint("dwm: cannot open display\n");