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>
36 #include <X11/cursorfont.h>
37 #include <X11/keysym.h>
38 #include <X11/Xatom.h>
40 #include <X11/Xproto.h>
41 #include <X11/Xutil.h>
44 #define BUTTONMASK (ButtonPressMask|ButtonReleaseMask)
45 #define CLEANMASK(mask) (mask & ~(numlockmask|LockMask))
46 #define LENGTH(x) (sizeof x / sizeof x[0])
48 #define MOUSEMASK (BUTTONMASK|PointerMotionMask)
51 enum { CurNormal, CurResize, CurMove, CurLast }; /* cursor */
52 enum { ColBorder, ColFG, ColBG, ColLast }; /* color */
53 enum { NetSupported, NetWMName, NetLast }; /* EWMH atoms */
54 enum { WMProtocols, WMDelete, WMName, WMState, WMLast };/* default atoms */
57 typedef struct Client Client;
61 int basew, baseh, incw, inch, maxw, maxh, minw, minh;
62 int minax, maxax, minay, maxay;
64 unsigned int border, oldborder;
65 Bool isbanned, isfixed, isfloating, isurgent;
75 unsigned long norm[ColLast];
76 unsigned long sel[ColLast];
86 } DC; /* draw context */
91 void (*func)(const char *arg);
97 void (*arrange)(void);
103 const char *instance;
109 /* function declarations */
110 void applyrules(Client *c);
112 void attach(Client *c);
113 void attachstack(Client *c);
115 void buttonpress(XEvent *e);
116 void checkotherwm(void);
118 void configure(Client *c);
119 void configurenotify(XEvent *e);
120 void configurerequest(XEvent *e);
121 unsigned int counttiled(void);
122 void destroynotify(XEvent *e);
123 void detach(Client *c);
124 void detachstack(Client *c);
126 void drawsquare(Bool filled, Bool empty, Bool invert, unsigned long col[ColLast]);
127 void drawtext(const char *text, unsigned long col[ColLast], Bool invert);
128 void *emallocz(unsigned int size);
129 void enternotify(XEvent *e);
130 void eprint(const char *errstr, ...);
131 void expose(XEvent *e);
132 void floating(void); /* default floating layout */
133 void focus(Client *c);
134 void focusin(XEvent *e);
135 void focusnext(const char *arg);
136 void focusprev(const char *arg);
137 Client *getclient(Window w);
138 unsigned long getcolor(const char *colstr);
139 double getdouble(const char *s);
140 long getstate(Window w);
141 Bool gettextprop(Window w, Atom atom, char *text, unsigned int size);
142 void grabbuttons(Client *c, Bool focused);
144 unsigned int idxoftag(const char *t);
145 void initfont(const char *fontstr);
146 Bool isoccupied(unsigned int t);
147 Bool isprotodel(Client *c);
148 Bool isurgent(unsigned int t);
149 Bool isvisible(Client *c);
150 void keypress(XEvent *e);
151 void killclient(const char *arg);
152 void manage(Window w, XWindowAttributes *wa);
153 void mappingnotify(XEvent *e);
154 void maprequest(XEvent *e);
156 void movemouse(Client *c);
157 Client *nexttiled(Client *c);
158 void propertynotify(XEvent *e);
159 void quit(const char *arg);
160 void reapply(const char *arg);
161 void resize(Client *c, int x, int y, int w, int h, Bool sizehints);
162 void resizemouse(Client *c);
166 void setclientstate(Client *c, long state);
167 void setgeom(const char *arg);
168 void setlayout(const char *arg);
170 void spawn(const char *arg);
171 void tag(const char *arg);
172 unsigned int textnw(const char *text, unsigned int len);
173 unsigned int textw(const char *text);
175 void tilehstack(unsigned int n);
176 Client *tilemaster(unsigned int n);
177 void tileresize(Client *c, int x, int y, int w, int h);
179 void tilevstack(unsigned int n);
180 void togglefloating(const char *arg);
181 void toggletag(const char *arg);
182 void toggleview(const char *arg);
183 void unban(Client *c);
184 void unmanage(Client *c);
185 void unmapnotify(XEvent *e);
186 void updatebarpos(void);
187 void updatesizehints(Client *c);
188 void updatetitle(Client *c);
189 void updatewmhints(Client *c);
190 void view(const char *arg);
191 void viewprevtag(const char *arg); /* views previous selected tags */
192 int xerror(Display *dpy, XErrorEvent *ee);
193 int xerrordummy(Display *dpy, XErrorEvent *ee);
194 int xerrorstart(Display *dpy, XErrorEvent *ee);
195 void zoom(const char *arg);
198 char stext[256], buf[256];
199 int screen, sx, sy, sw, sh;
200 int (*xerrorxlib)(Display *, XErrorEvent *);
201 int bx, by, bw, bh, blw, mx, my, mw, mh, mox, moy, mow, moh, tx, ty, tw, th, wx, wy, ww, wh;
202 unsigned int numlockmask = 0;
203 void (*handler[LASTEvent]) (XEvent *) = {
204 [ButtonPress] = buttonpress,
205 [ConfigureRequest] = configurerequest,
206 [ConfigureNotify] = configurenotify,
207 [DestroyNotify] = destroynotify,
208 [EnterNotify] = enternotify,
211 [KeyPress] = keypress,
212 [MappingNotify] = mappingnotify,
213 [MapRequest] = maprequest,
214 [PropertyNotify] = propertynotify,
215 [UnmapNotify] = unmapnotify
217 Atom wmatom[WMLast], netatom[NetLast];
218 Bool otherwm, readin;
222 Client *clients = NULL;
224 Client *stack = NULL;
225 Cursor cursor[CurLast];
231 /* configuration, allows nested code to access above variables */
233 #define TAGSZ (LENGTH(tags) * sizeof(Bool))
234 static Bool tmp[LENGTH(tags)];
236 /* function implementations */
239 applyrules(Client *c) {
241 Bool matched = False;
243 XClassHint ch = { 0 };
246 XGetClassHint(dpy, c->win, &ch);
247 for(i = 0; i < LENGTH(rules); i++) {
249 if(strstr(c->name, r->title)
250 || (ch.res_class && r->class && strstr(ch.res_class, r->class))
251 || (ch.res_name && r->instance && strstr(ch.res_name, r->instance)))
253 c->isfloating = r->isfloating;
255 c->tags[idxoftag(r->tag)] = True;
265 memcpy(c->tags, seltags, TAGSZ);
272 for(c = clients; c; c = c->next)
292 attachstack(Client *c) {
301 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
306 buttonpress(XEvent *e) {
309 XButtonPressedEvent *ev = &e->xbutton;
311 if(ev->window == barwin) {
313 for(i = 0; i < LENGTH(tags); i++) {
316 if(ev->button == Button1) {
317 if(ev->state & MODKEY)
322 else if(ev->button == Button3) {
323 if(ev->state & MODKEY)
332 else if((c = getclient(ev->window))) {
334 if(CLEANMASK(ev->state) != MODKEY)
336 if(ev->button == Button1) {
340 else if(ev->button == Button2) {
341 if((floating != lt->arrange) && c->isfloating)
342 togglefloating(NULL);
346 else if(ev->button == Button3 && !c->isfixed) {
356 XSetErrorHandler(xerrorstart);
358 /* this causes an error if some other window manager is running */
359 XSelectInput(dpy, DefaultRootWindow(dpy), SubstructureRedirectMask);
362 eprint("dwm: another window manager is already running\n");
364 XSetErrorHandler(NULL);
365 xerrorxlib = XSetErrorHandler(xerror);
377 XFreeFontSet(dpy, dc.font.set);
379 XFreeFont(dpy, dc.font.xfont);
380 XUngrabKey(dpy, AnyKey, AnyModifier, root);
381 XFreePixmap(dpy, dc.drawable);
383 XFreeCursor(dpy, cursor[CurNormal]);
384 XFreeCursor(dpy, cursor[CurResize]);
385 XFreeCursor(dpy, cursor[CurMove]);
386 XDestroyWindow(dpy, barwin);
388 XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime);
392 configure(Client *c) {
395 ce.type = ConfigureNotify;
403 ce.border_width = c->border;
405 ce.override_redirect = False;
406 XSendEvent(dpy, c->win, False, StructureNotifyMask, (XEvent *)&ce);
410 configurenotify(XEvent *e) {
411 XConfigureEvent *ev = &e->xconfigure;
413 if(ev->window == root && (ev->width != sw || ev->height != sh)) {
421 configurerequest(XEvent *e) {
423 XConfigureRequestEvent *ev = &e->xconfigurerequest;
426 if((c = getclient(ev->window))) {
427 if(ev->value_mask & CWBorderWidth)
428 c->border = ev->border_width;
429 if(c->isfixed || c->isfloating || lt->isfloating) {
430 if(ev->value_mask & CWX)
432 if(ev->value_mask & CWY)
434 if(ev->value_mask & CWWidth)
436 if(ev->value_mask & CWHeight)
438 if((c->x - sx + c->w) > sw && c->isfloating)
439 c->x = sx + (sw / 2 - c->w / 2); /* center in x direction */
440 if((c->y - sy + c->h) > sh && c->isfloating)
441 c->y = sy + (sh / 2 - c->h / 2); /* center in y direction */
442 if((ev->value_mask & (CWX|CWY))
443 && !(ev->value_mask & (CWWidth|CWHeight)))
446 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h);
454 wc.width = ev->width;
455 wc.height = ev->height;
456 wc.border_width = ev->border_width;
457 wc.sibling = ev->above;
458 wc.stack_mode = ev->detail;
459 XConfigureWindow(dpy, ev->window, ev->value_mask, &wc);
469 for(n = 0, c = nexttiled(clients); c; c = nexttiled(c->next), n++);
474 destroynotify(XEvent *e) {
476 XDestroyWindowEvent *ev = &e->xdestroywindow;
478 if((c = getclient(ev->window)))
485 c->prev->next = c->next;
487 c->next->prev = c->prev;
490 c->next = c->prev = NULL;
494 detachstack(Client *c) {
497 for(tc=&stack; *tc && *tc != c; tc=&(*tc)->snext);
507 for(c = stack; c && !isvisible(c); c = c->snext);
508 for(i = 0; i < LENGTH(tags); i++) {
509 dc.w = textw(tags[i]);
511 drawtext(tags[i], dc.sel, isurgent(i));
512 drawsquare(c && c->tags[i], isoccupied(i), isurgent(i), dc.sel);
515 drawtext(tags[i], dc.norm, isurgent(i));
516 drawsquare(c && c->tags[i], isoccupied(i), isurgent(i), dc.norm);
521 drawtext(lt->symbol, dc.norm, False);
529 drawtext(stext, dc.norm, False);
530 if((dc.w = dc.x - x) > bh) {
533 drawtext(c->name, dc.sel, False);
534 drawsquare(False, c->isfloating, False, dc.sel);
537 drawtext(NULL, dc.norm, False);
539 XCopyArea(dpy, dc.drawable, barwin, dc.gc, 0, 0, bw, bh, 0, 0);
544 drawsquare(Bool filled, Bool empty, Bool invert, unsigned long col[ColLast]) {
547 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
549 gcv.foreground = col[invert ? ColBG : ColFG];
550 XChangeGC(dpy, dc.gc, GCForeground, &gcv);
551 x = (dc.font.ascent + dc.font.descent + 2) / 4;
555 r.width = r.height = x + 1;
556 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
559 r.width = r.height = x;
560 XDrawRectangles(dpy, dc.drawable, dc.gc, &r, 1);
565 drawtext(const char *text, unsigned long col[ColLast], Bool invert) {
567 unsigned int len, olen;
568 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
570 XSetForeground(dpy, dc.gc, col[invert ? ColFG : ColBG]);
571 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
575 olen = len = strlen(text);
576 if(len >= sizeof buf)
577 len = sizeof buf - 1;
578 memcpy(buf, text, len);
580 h = dc.font.ascent + dc.font.descent;
581 y = dc.y + (dc.h / 2) - (h / 2) + dc.font.ascent;
583 /* shorten text if necessary */
584 while(len && (w = textnw(buf, len)) > dc.w - h)
595 return; /* too long */
596 XSetForeground(dpy, dc.gc, col[invert ? ColBG : ColFG]);
598 XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
600 XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
604 emallocz(unsigned int size) {
605 void *res = calloc(1, size);
608 eprint("fatal: could not malloc() %u bytes\n", size);
613 enternotify(XEvent *e) {
615 XCrossingEvent *ev = &e->xcrossing;
617 if((ev->mode != NotifyNormal || ev->detail == NotifyInferior) && ev->window != root)
619 if((c = getclient(ev->window)))
626 eprint(const char *errstr, ...) {
629 va_start(ap, errstr);
630 vfprintf(stderr, errstr, ap);
637 XExposeEvent *ev = &e->xexpose;
639 if(ev->count == 0 && (ev->window == barwin))
644 floating(void) { /* default floating layout */
647 for(c = clients; c; c = c->next)
649 resize(c, c->x, c->y, c->w, c->h, True);
654 if(!c || (c && !isvisible(c)))
655 for(c = stack; c && !isvisible(c); c = c->snext);
656 if(sel && sel != c) {
657 grabbuttons(sel, False);
658 XSetWindowBorder(dpy, sel->win, dc.norm[ColBorder]);
663 grabbuttons(c, True);
667 XSetWindowBorder(dpy, c->win, dc.sel[ColBorder]);
668 XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
671 XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
676 focusin(XEvent *e) { /* there are some broken focus acquiring clients */
677 XFocusChangeEvent *ev = &e->xfocus;
679 if(sel && ev->window != sel->win)
680 XSetInputFocus(dpy, sel->win, RevertToPointerRoot, CurrentTime);
684 focusnext(const char *arg) {
689 for(c = sel->next; c && !isvisible(c); c = c->next);
691 for(c = clients; c && !isvisible(c); c = c->next);
699 focusprev(const char *arg) {
704 for(c = sel->prev; c && !isvisible(c); c = c->prev);
706 for(c = clients; c && c->next; c = c->next);
707 for(; c && !isvisible(c); c = c->prev);
716 getclient(Window w) {
719 for(c = clients; c && c->win != w; c = c->next);
724 getcolor(const char *colstr) {
725 Colormap cmap = DefaultColormap(dpy, screen);
728 if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
729 eprint("error, cannot allocate color '%s'\n", colstr);
737 unsigned char *p = NULL;
738 unsigned long n, extra;
741 status = XGetWindowProperty(dpy, w, wmatom[WMState], 0L, 2L, False, wmatom[WMState],
742 &real, &format, &n, &extra, (unsigned char **)&p);
743 if(status != Success)
752 gettextprop(Window w, Atom atom, char *text, unsigned int size) {
757 if(!text || size == 0)
760 XGetTextProperty(dpy, w, &name, atom);
763 if(name.encoding == XA_STRING)
764 strncpy(text, (char *)name.value, size - 1);
766 if(XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success
768 strncpy(text, *list, size - 1);
769 XFreeStringList(list);
772 text[size - 1] = '\0';
778 grabbuttons(Client *c, Bool focused) {
779 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
782 XGrabButton(dpy, Button1, MODKEY, c->win, False, BUTTONMASK,
783 GrabModeAsync, GrabModeSync, None, None);
784 XGrabButton(dpy, Button1, MODKEY|LockMask, c->win, False, BUTTONMASK,
785 GrabModeAsync, GrabModeSync, None, None);
786 XGrabButton(dpy, Button1, MODKEY|numlockmask, c->win, False, BUTTONMASK,
787 GrabModeAsync, GrabModeSync, None, None);
788 XGrabButton(dpy, Button1, MODKEY|numlockmask|LockMask, c->win, False, BUTTONMASK,
789 GrabModeAsync, GrabModeSync, None, None);
791 XGrabButton(dpy, Button2, MODKEY, c->win, False, BUTTONMASK,
792 GrabModeAsync, GrabModeSync, None, None);
793 XGrabButton(dpy, Button2, MODKEY|LockMask, c->win, False, BUTTONMASK,
794 GrabModeAsync, GrabModeSync, None, None);
795 XGrabButton(dpy, Button2, MODKEY|numlockmask, c->win, False, BUTTONMASK,
796 GrabModeAsync, GrabModeSync, None, None);
797 XGrabButton(dpy, Button2, MODKEY|numlockmask|LockMask, c->win, False, BUTTONMASK,
798 GrabModeAsync, GrabModeSync, None, None);
800 XGrabButton(dpy, Button3, MODKEY, c->win, False, BUTTONMASK,
801 GrabModeAsync, GrabModeSync, None, None);
802 XGrabButton(dpy, Button3, MODKEY|LockMask, c->win, False, BUTTONMASK,
803 GrabModeAsync, GrabModeSync, None, None);
804 XGrabButton(dpy, Button3, MODKEY|numlockmask, c->win, False, BUTTONMASK,
805 GrabModeAsync, GrabModeSync, None, None);
806 XGrabButton(dpy, Button3, MODKEY|numlockmask|LockMask, c->win, False, BUTTONMASK,
807 GrabModeAsync, GrabModeSync, None, None);
810 XGrabButton(dpy, AnyButton, AnyModifier, c->win, False, BUTTONMASK,
811 GrabModeAsync, GrabModeSync, None, None);
818 XModifierKeymap *modmap;
820 /* init modifier map */
821 modmap = XGetModifierMapping(dpy);
822 for(i = 0; i < 8; i++)
823 for(j = 0; j < modmap->max_keypermod; j++) {
824 if(modmap->modifiermap[i * modmap->max_keypermod + j] == XKeysymToKeycode(dpy, XK_Num_Lock))
825 numlockmask = (1 << i);
827 XFreeModifiermap(modmap);
829 XUngrabKey(dpy, AnyKey, AnyModifier, root);
830 for(i = 0; i < LENGTH(keys); i++) {
831 code = XKeysymToKeycode(dpy, keys[i].keysym);
832 XGrabKey(dpy, code, keys[i].mod, root, True,
833 GrabModeAsync, GrabModeAsync);
834 XGrabKey(dpy, code, keys[i].mod|LockMask, root, True,
835 GrabModeAsync, GrabModeAsync);
836 XGrabKey(dpy, code, keys[i].mod|numlockmask, root, True,
837 GrabModeAsync, GrabModeAsync);
838 XGrabKey(dpy, code, keys[i].mod|numlockmask|LockMask, root, True,
839 GrabModeAsync, GrabModeAsync);
844 idxoftag(const char *t) {
847 for(i = 0; (i < LENGTH(tags)) && (tags[i] != t); i++);
848 return (i < LENGTH(tags)) ? i : 0;
852 initfont(const char *fontstr) {
853 char *def, **missing;
858 XFreeFontSet(dpy, dc.font.set);
859 dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
862 fprintf(stderr, "dwm: missing fontset: %s\n", missing[n]);
863 XFreeStringList(missing);
866 XFontSetExtents *font_extents;
867 XFontStruct **xfonts;
869 dc.font.ascent = dc.font.descent = 0;
870 font_extents = XExtentsOfFontSet(dc.font.set);
871 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
872 for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
873 if(dc.font.ascent < (*xfonts)->ascent)
874 dc.font.ascent = (*xfonts)->ascent;
875 if(dc.font.descent < (*xfonts)->descent)
876 dc.font.descent = (*xfonts)->descent;
882 XFreeFont(dpy, dc.font.xfont);
883 dc.font.xfont = NULL;
884 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr))
885 && !(dc.font.xfont = XLoadQueryFont(dpy, "fixed")))
886 eprint("error, cannot load font: '%s'\n", fontstr);
887 dc.font.ascent = dc.font.xfont->ascent;
888 dc.font.descent = dc.font.xfont->descent;
890 dc.font.height = dc.font.ascent + dc.font.descent;
894 isoccupied(unsigned int t) {
897 for(c = clients; c; c = c->next)
904 isprotodel(Client *c) {
909 if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
910 for(i = 0; !ret && i < n; i++)
911 if(protocols[i] == wmatom[WMDelete])
919 isurgent(unsigned int t) {
922 for(c = clients; c; c = c->next)
923 if(c->isurgent && c->tags[t])
929 isvisible(Client *c) {
932 for(i = 0; i < LENGTH(tags); i++)
933 if(c->tags[i] && seltags[i])
939 keypress(XEvent *e) {
945 keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
946 for(i = 0; i < LENGTH(keys); i++)
947 if(keysym == keys[i].keysym
948 && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state))
951 keys[i].func(keys[i].arg);
956 killclient(const char *arg) {
961 if(isprotodel(sel)) {
962 ev.type = ClientMessage;
963 ev.xclient.window = sel->win;
964 ev.xclient.message_type = wmatom[WMProtocols];
965 ev.xclient.format = 32;
966 ev.xclient.data.l[0] = wmatom[WMDelete];
967 ev.xclient.data.l[1] = CurrentTime;
968 XSendEvent(dpy, sel->win, False, NoEventMask, &ev);
971 XKillClient(dpy, sel->win);
975 manage(Window w, XWindowAttributes *wa) {
976 Client *c, *t = NULL;
981 c = emallocz(sizeof(Client));
982 c->tags = emallocz(TAGSZ);
990 c->oldborder = wa->border_width;
991 if(c->w == sw && c->h == sh) {
994 c->border = wa->border_width;
997 if(c->x + c->w + 2 * c->border > wx + ww)
998 c->x = wx + ww - c->w - 2 * c->border;
999 if(c->y + c->h + 2 * c->border > wy + wh)
1000 c->y = wy + wh - c->h - 2 * c->border;
1005 c->border = BORDERPX;
1008 wc.border_width = c->border;
1009 XConfigureWindow(dpy, w, CWBorderWidth, &wc);
1010 XSetWindowBorder(dpy, w, dc.norm[ColBorder]);
1011 configure(c); /* propagates border_width, if size doesn't change */
1013 XSelectInput(dpy, w, EnterWindowMask|FocusChangeMask|PropertyChangeMask|StructureNotifyMask);
1014 grabbuttons(c, False);
1016 if((rettrans = XGetTransientForHint(dpy, w, &trans) == Success))
1017 for(t = clients; t && t->win != trans; t = t->next);
1019 memcpy(c->tags, t->tags, TAGSZ);
1023 c->isfloating = (rettrans == Success) || c->isfixed;
1026 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h); /* some windows require this */
1028 XMapWindow(dpy, c->win);
1029 setclientstate(c, NormalState);
1034 mappingnotify(XEvent *e) {
1035 XMappingEvent *ev = &e->xmapping;
1037 XRefreshKeyboardMapping(ev);
1038 if(ev->request == MappingKeyboard)
1043 maprequest(XEvent *e) {
1044 static XWindowAttributes wa;
1045 XMapRequestEvent *ev = &e->xmaprequest;
1047 if(!XGetWindowAttributes(dpy, ev->window, &wa))
1049 if(wa.override_redirect)
1051 if(!getclient(ev->window))
1052 manage(ev->window, &wa);
1059 for(c = clients; c; c = c->next)
1061 resize(c, mox, moy, mow, moh, RESIZEHINTS);
1065 movemouse(Client *c) {
1066 int x1, y1, ocx, ocy, di, nx, ny;
1073 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1074 None, cursor[CurMove], CurrentTime) != GrabSuccess)
1076 XQueryPointer(dpy, root, &dummy, &dummy, &x1, &y1, &di, &di, &dui);
1078 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
1081 XUngrabPointer(dpy, CurrentTime);
1083 case ConfigureRequest:
1086 handler[ev.type](&ev);
1090 nx = ocx + (ev.xmotion.x - x1);
1091 ny = ocy + (ev.xmotion.y - y1);
1092 if(abs(wx - nx) < SNAP)
1094 else if(abs((wx + ww) - (nx + c->w + 2 * c->border)) < SNAP)
1095 nx = wx + ww - c->w - 2 * c->border;
1096 if(abs(wy - ny) < SNAP)
1098 else if(abs((wy + wh) - (ny + c->h + 2 * c->border)) < SNAP)
1099 ny = wy + wh - c->h - 2 * c->border;
1100 if(!c->isfloating && !lt->isfloating && (abs(nx - c->x) > SNAP || abs(ny - c->y) > SNAP))
1101 togglefloating(NULL);
1102 if((lt->isfloating) || c->isfloating)
1103 resize(c, nx, ny, c->w, c->h, False);
1110 nexttiled(Client *c) {
1111 for(; c && (c->isfloating || !isvisible(c)); c = c->next);
1116 propertynotify(XEvent *e) {
1119 XPropertyEvent *ev = &e->xproperty;
1121 if(ev->state == PropertyDelete)
1122 return; /* ignore */
1123 if((c = getclient(ev->window))) {
1126 case XA_WM_TRANSIENT_FOR:
1127 XGetTransientForHint(dpy, c->win, &trans);
1128 if(!c->isfloating && (c->isfloating = (getclient(trans) != NULL)))
1131 case XA_WM_NORMAL_HINTS:
1139 if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
1148 quit(const char *arg) {
1149 readin = running = False;
1153 reapply(const char *arg) {
1154 static Bool zerotags[LENGTH(tags)] = { 0 };
1157 for(c = clients; c; c = c->next) {
1158 memcpy(c->tags, zerotags, sizeof zerotags);
1165 resize(Client *c, int x, int y, int w, int h, Bool sizehints) {
1169 /* set minimum possible */
1175 /* temporarily remove base dimensions */
1179 /* adjust for aspect limits */
1180 if (c->minay > 0 && c->maxay > 0 && c->minax > 0 && c->maxax > 0) {
1181 if (w * c->maxay > h * c->maxax)
1182 w = h * c->maxax / c->maxay;
1183 else if (w * c->minay < h * c->minax)
1184 h = w * c->minay / c->minax;
1187 /* adjust for increment value */
1193 /* restore base dimensions */
1197 if(c->minw > 0 && w < c->minw)
1199 if(c->minh > 0 && h < c->minh)
1201 if(c->maxw > 0 && w > c->maxw)
1203 if(c->maxh > 0 && h > c->maxh)
1206 if(w <= 0 || h <= 0)
1209 x = sw - w - 2 * c->border;
1211 y = sh - h - 2 * c->border;
1212 if(x + w + 2 * c->border < sx)
1214 if(y + h + 2 * c->border < sy)
1216 if(c->x != x || c->y != y || c->w != w || c->h != h) {
1219 c->w = wc.width = w;
1220 c->h = wc.height = h;
1221 wc.border_width = c->border;
1222 XConfigureWindow(dpy, c->win,
1223 CWX|CWY|CWWidth|CWHeight|CWBorderWidth, &wc);
1230 resizemouse(Client *c) {
1237 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1238 None, cursor[CurResize], CurrentTime) != GrabSuccess)
1240 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->border - 1, c->h + c->border - 1);
1242 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask , &ev);
1245 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0,
1246 c->w + c->border - 1, c->h + c->border - 1);
1247 XUngrabPointer(dpy, CurrentTime);
1248 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1250 case ConfigureRequest:
1253 handler[ev.type](&ev);
1257 if((nw = ev.xmotion.x - ocx - 2 * c->border + 1) <= 0)
1259 if((nh = ev.xmotion.y - ocy - 2 * c->border + 1) <= 0)
1261 if(!c->isfloating && !lt->isfloating && (abs(nw - c->w) > SNAP || abs(nh - c->h) > SNAP))
1262 togglefloating(NULL);
1263 if((lt->isfloating) || c->isfloating)
1264 resize(c, c->x, c->y, nw, nh, True);
1279 if(sel->isfloating || lt->isfloating)
1280 XRaiseWindow(dpy, sel->win);
1281 if(!lt->isfloating) {
1282 wc.stack_mode = Below;
1283 wc.sibling = barwin;
1284 if(!sel->isfloating) {
1285 XConfigureWindow(dpy, sel->win, CWSibling|CWStackMode, &wc);
1286 wc.sibling = sel->win;
1288 for(c = nexttiled(clients); c; c = nexttiled(c->next)) {
1291 XConfigureWindow(dpy, c->win, CWSibling|CWStackMode, &wc);
1292 wc.sibling = c->win;
1296 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1302 char sbuf[sizeof stext];
1305 unsigned int len, offset;
1308 /* main event loop, also reads status text from stdin */
1310 xfd = ConnectionNumber(dpy);
1313 len = sizeof stext - 1;
1314 sbuf[len] = stext[len] = '\0'; /* 0-terminator is never touched */
1318 FD_SET(STDIN_FILENO, &rd);
1320 if(select(xfd + 1, &rd, NULL, NULL, NULL) == -1) {
1323 eprint("select failed\n");
1325 if(FD_ISSET(STDIN_FILENO, &rd)) {
1326 switch((r = read(STDIN_FILENO, sbuf + offset, len - offset))) {
1328 strncpy(stext, strerror(errno), len);
1332 strncpy(stext, "EOF", 4);
1336 for(p = sbuf + offset; r > 0; p++, r--, offset++)
1337 if(*p == '\n' || *p == '\0') {
1339 strncpy(stext, sbuf, len);
1340 p += r - 1; /* p is sbuf + offset + r - 1 */
1341 for(r = 0; *(p - r) && *(p - r) != '\n'; r++);
1344 memmove(sbuf, p - r + 1, r);
1351 while(XPending(dpy)) {
1352 XNextEvent(dpy, &ev);
1353 if(handler[ev.type])
1354 (handler[ev.type])(&ev); /* call handler */
1361 unsigned int i, num;
1362 Window *wins, d1, d2;
1363 XWindowAttributes wa;
1366 if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1367 for(i = 0; i < num; i++) {
1368 if(!XGetWindowAttributes(dpy, wins[i], &wa)
1369 || wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1371 if(wa.map_state == IsViewable || getstate(wins[i]) == IconicState)
1372 manage(wins[i], &wa);
1374 for(i = 0; i < num; i++) { /* now the transients */
1375 if(!XGetWindowAttributes(dpy, wins[i], &wa))
1377 if(XGetTransientForHint(dpy, wins[i], &d1)
1378 && (wa.map_state == IsViewable || getstate(wins[i]) == IconicState))
1379 manage(wins[i], &wa);
1387 setclientstate(Client *c, long state) {
1388 long data[] = {state, None};
1390 XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1391 PropModeReplace, (unsigned char *)data, 2);
1397 * having a geom syntax as follows, which is interpreted as integer.
1399 * [-,+][<0..n>|<W,H,B>]
1402 * B = bar height, W = DisplayWidth(), H = DisplayHeight()
1404 * -/+/* /: is relative to current
1406 * Then we would come down with <bx>,<by>,<bw>,<bh>,...
1408 * "0 0 W B 0 0 W W N E B,W,B,
1414 getdouble(const char *s) {
1418 fprintf(stderr, "getdouble '%s'\n", s);
1421 result = strtod(s, &endp);
1422 if(s == endp || *endp != 0)
1423 result = strtol(s, &endp, 0);
1425 case 'B': result = dc.font.height + 2; break;
1426 case 'W': result = sw; break;
1427 case 'H': result = sh; break;
1429 fprintf(stderr, "getdouble returns '%f'\n", result);
1434 setgeom(const char *arg) {
1435 static const char *lastArg = NULL;
1436 char op, *s, *e, *p;
1438 int i, *map[] = { &bx, &by, &bw, &bh,
1442 &mox, &moy, &mow, &moh };
1450 strncpy(buf, arg, sizeof buf);
1451 for(i = 0, e = s = buf; e && *e; e++)
1454 fprintf(stderr, "next geom arg='%s'\n", s);
1456 /* check if there is an operator */
1457 for(p = s; *p && *p != '-' && *p != '+' && *p != '*' && *p != ':'; p++);
1463 fprintf(stderr, "val1: %d\n", val);
1464 if(p > s) { /* intermediate operand, e.g. H-B */
1468 fprintf(stderr, "val2: %d\n", val);
1471 default: *(map[i]) = val; break;
1472 case '-': *(map[i]) -= val; break;
1473 case '+': *(map[i]) += val; break;
1474 case '*': *(map[i]) *= val; break;
1475 case ':': if(val != 0) *(map[i]) /= val; break;
1477 fprintf(stderr, "map[i]='%d'\n", val);
1486 setlayout(const char *arg) {
1487 static Layout *revert = 0;
1492 for(i = 0; i < LENGTH(layouts); i++)
1493 if(!strcmp(arg, layouts[i].symbol))
1495 if(i == LENGTH(layouts))
1497 if(revert && &layouts[i] == lt)
1512 XSetWindowAttributes wa;
1515 screen = DefaultScreen(dpy);
1516 root = RootWindow(dpy, screen);
1519 /* apply default dimensions */
1522 sw = DisplayWidth(dpy, screen);
1523 sh = DisplayHeight(dpy, screen);
1527 wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1528 wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1529 wmatom[WMName] = XInternAtom(dpy, "WM_NAME", False);
1530 wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1531 netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1532 netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1535 wa.cursor = cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1536 cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1537 cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1539 /* init appearance */
1540 dc.norm[ColBorder] = getcolor(NORMBORDERCOLOR);
1541 dc.norm[ColBG] = getcolor(NORMBGCOLOR);
1542 dc.norm[ColFG] = getcolor(NORMFGCOLOR);
1543 dc.sel[ColBorder] = getcolor(SELBORDERCOLOR);
1544 dc.sel[ColBG] = getcolor(SELBGCOLOR);
1545 dc.sel[ColFG] = getcolor(SELFGCOLOR);
1548 dc.drawable = XCreatePixmap(dpy, root, DisplayWidth(dpy, screen), bh, DefaultDepth(dpy, screen));
1549 dc.gc = XCreateGC(dpy, root, 0, 0);
1550 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
1552 XSetFont(dpy, dc.gc, dc.font.xfont->fid);
1555 seltags = emallocz(TAGSZ);
1556 prevtags = emallocz(TAGSZ);
1557 seltags[0] = prevtags[0] = True;
1563 for(blw = i = 0; i < LENGTH(layouts); i++) {
1564 i = textw(layouts[i].symbol);
1569 wa.override_redirect = 1;
1570 wa.background_pixmap = ParentRelative;
1571 wa.event_mask = ButtonPressMask|ExposureMask;
1573 barwin = XCreateWindow(dpy, root, bx, by, bw, bh, 0, DefaultDepth(dpy, screen),
1574 CopyFromParent, DefaultVisual(dpy, screen),
1575 CWOverrideRedirect|CWBackPixmap|CWEventMask, &wa);
1576 XDefineCursor(dpy, barwin, cursor[CurNormal]);
1577 XMapRaised(dpy, barwin);
1578 strcpy(stext, "dwm-"VERSION);
1581 /* EWMH support per view */
1582 XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1583 PropModeReplace, (unsigned char *) netatom, NetLast);
1585 /* select for events */
1586 wa.event_mask = SubstructureRedirectMask|SubstructureNotifyMask
1587 |EnterWindowMask|LeaveWindowMask|StructureNotifyMask;
1588 XChangeWindowAttributes(dpy, root, CWEventMask|CWCursor, &wa);
1589 XSelectInput(dpy, root, wa.event_mask);
1597 spawn(const char *arg) {
1598 static char *shell = NULL;
1600 if(!shell && !(shell = getenv("SHELL")))
1604 /* The double-fork construct avoids zombie processes and keeps the code
1605 * clean from stupid signal handlers. */
1609 close(ConnectionNumber(dpy));
1611 execl(shell, shell, "-c", arg, (char *)NULL);
1612 fprintf(stderr, "dwm: execl '%s -c %s'", shell, arg);
1621 tag(const char *arg) {
1626 for(i = 0; i < LENGTH(tags); i++)
1627 sel->tags[i] = (NULL == arg);
1628 sel->tags[idxoftag(arg)] = True;
1633 textnw(const char *text, unsigned int len) {
1637 XmbTextExtents(dc.font.set, text, len, NULL, &r);
1640 return XTextWidth(dc.font.xfont, text, len);
1644 textw(const char *text) {
1645 return textnw(text, strlen(text)) + dc.font.height;
1651 unsigned int i, n = counttiled();
1665 for(i = 0, c = nexttiled(c->next); c; c = nexttiled(c->next), i++) {
1666 if(i + 1 == n) /* remainder */
1667 tileresize(c, x, ty, (tx + tw) - x - 2 * c->border, th - 2 * c->border);
1669 tileresize(c, x, ty, w - 2 * c->border, th - 2 * c->border);
1671 x = c->x + c->w + 2 * c->border;
1676 tilemaster(unsigned int n) {
1677 Client *c = nexttiled(clients);
1680 tileresize(c, mox, moy, mow - 2 * c->border, moh - 2 * c->border);
1682 tileresize(c, mx, my, mw - 2 * c->border, mh - 2 * c->border);
1687 tileresize(Client *c, int x, int y, int w, int h) {
1688 resize(c, x, y, w, h, RESIZEHINTS);
1689 if((RESIZEHINTS) && ((c->h < bh) || (c->h > h) || (c->w < bh) || (c->w > w)))
1690 /* client doesn't accept size constraints */
1691 resize(c, x, y, w, h, False);
1697 unsigned int i, n = counttiled();
1711 for(i = 0, c = nexttiled(c->next); c; c = nexttiled(c->next), i++) {
1712 if(i + 1 == n) /* remainder */
1713 tileresize(c, tx, y, tw - 2 * c->border, (ty + th) - y - 2 * c->border);
1715 tileresize(c, tx, y, tw - 2 * c->border, h - 2 * c->border);
1717 y = c->y + c->h + 2 * c->border;
1722 togglefloating(const char *arg) {
1725 sel->isfloating = !sel->isfloating;
1727 resize(sel, sel->x, sel->y, sel->w, sel->h, True);
1732 toggletag(const char *arg) {
1738 sel->tags[i] = !sel->tags[i];
1739 for(j = 0; j < LENGTH(tags) && !sel->tags[j]; j++);
1740 if(j == LENGTH(tags))
1741 sel->tags[i] = True; /* at least one tag must be enabled */
1746 toggleview(const char *arg) {
1750 seltags[i] = !seltags[i];
1751 for(j = 0; j < LENGTH(tags) && !seltags[j]; j++);
1752 if(j == LENGTH(tags))
1753 seltags[i] = True; /* at least one tag must be viewed */
1761 XMoveWindow(dpy, c->win, c->x, c->y);
1762 c->isbanned = False;
1766 unmanage(Client *c) {
1769 wc.border_width = c->oldborder;
1770 /* The server grab construct avoids race conditions. */
1772 XSetErrorHandler(xerrordummy);
1773 XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
1778 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1779 setclientstate(c, WithdrawnState);
1783 XSetErrorHandler(xerror);
1789 unmapnotify(XEvent *e) {
1791 XUnmapEvent *ev = &e->xunmap;
1793 if((c = getclient(ev->window)))
1798 updatebarpos(void) {
1800 if(dc.drawable != 0)
1801 XFreePixmap(dpy, dc.drawable);
1802 dc.drawable = XCreatePixmap(dpy, root, bw, bh, DefaultDepth(dpy, screen));
1803 XMoveResizeWindow(dpy, barwin, bx, by, bw, bh);
1807 updatesizehints(Client *c) {
1811 if(!XGetWMNormalHints(dpy, c->win, &size, &msize) || !size.flags)
1813 c->flags = size.flags;
1814 if(c->flags & PBaseSize) {
1815 c->basew = size.base_width;
1816 c->baseh = size.base_height;
1818 else if(c->flags & PMinSize) {
1819 c->basew = size.min_width;
1820 c->baseh = size.min_height;
1823 c->basew = c->baseh = 0;
1824 if(c->flags & PResizeInc) {
1825 c->incw = size.width_inc;
1826 c->inch = size.height_inc;
1829 c->incw = c->inch = 0;
1830 if(c->flags & PMaxSize) {
1831 c->maxw = size.max_width;
1832 c->maxh = size.max_height;
1835 c->maxw = c->maxh = 0;
1836 if(c->flags & PMinSize) {
1837 c->minw = size.min_width;
1838 c->minh = size.min_height;
1840 else if(c->flags & PBaseSize) {
1841 c->minw = size.base_width;
1842 c->minh = size.base_height;
1845 c->minw = c->minh = 0;
1846 if(c->flags & PAspect) {
1847 c->minax = size.min_aspect.x;
1848 c->maxax = size.max_aspect.x;
1849 c->minay = size.min_aspect.y;
1850 c->maxay = size.max_aspect.y;
1853 c->minax = c->maxax = c->minay = c->maxay = 0;
1854 c->isfixed = (c->maxw && c->minw && c->maxh && c->minh
1855 && c->maxw == c->minw && c->maxh == c->minh);
1859 updatetitle(Client *c) {
1860 if(!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
1861 gettextprop(c->win, wmatom[WMName], c->name, sizeof c->name);
1865 updatewmhints(Client *c) {
1868 if((wmh = XGetWMHints(dpy, c->win))) {
1870 sel->isurgent = False;
1872 c->isurgent = (wmh->flags & XUrgencyHint) ? True : False;
1879 view(const char *arg) {
1882 for(i = 0; i < LENGTH(tags); i++)
1883 tmp[i] = (NULL == arg);
1884 tmp[idxoftag(arg)] = True;
1886 if(memcmp(seltags, tmp, TAGSZ) != 0) {
1887 memcpy(prevtags, seltags, TAGSZ);
1888 memcpy(seltags, tmp, TAGSZ);
1894 viewprevtag(const char *arg) {
1896 memcpy(tmp, seltags, TAGSZ);
1897 memcpy(seltags, prevtags, TAGSZ);
1898 memcpy(prevtags, tmp, TAGSZ);
1902 /* There's no way to check accesses to destroyed windows, thus those cases are
1903 * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
1904 * default error handler, which may call exit. */
1906 xerror(Display *dpy, XErrorEvent *ee) {
1907 if(ee->error_code == BadWindow
1908 || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1909 || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1910 || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1911 || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1912 || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1913 || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1914 || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1916 fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1917 ee->request_code, ee->error_code);
1918 return xerrorxlib(dpy, ee); /* may call exit */
1922 xerrordummy(Display *dpy, XErrorEvent *ee) {
1926 /* Startup Error handler to check if another window manager
1927 * is already running. */
1929 xerrorstart(Display *dpy, XErrorEvent *ee) {
1935 zoom(const char *arg) {
1938 if(!sel || lt->isfloating || sel->isfloating)
1940 if(c == nexttiled(clients))
1941 if(!(c = nexttiled(c->next)))
1950 main(int argc, char *argv[]) {
1951 if(argc == 2 && !strcmp("-v", argv[1]))
1952 eprint("dwm-"VERSION", © 2006-2008 dwm engineers, see LICENSE for details\n");
1954 eprint("usage: dwm [-v]\n");
1956 setlocale(LC_CTYPE, "");
1957 if(!(dpy = XOpenDisplay(0)))
1958 eprint("dwm: cannot open display\n");