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 MAX(a, b) ((a)>(b)?(a):(b))
45 #define MIN(a, b) ((a)<(b)?(a):(b))
46 #define BUTTONMASK (ButtonPressMask|ButtonReleaseMask)
47 #define CLEANMASK(mask) (mask & ~(numlockmask|LockMask))
48 #define LENGTH(x) (sizeof x / sizeof x[0])
50 #define MOUSEMASK (BUTTONMASK|PointerMotionMask)
51 #define DEFGEOM(GEONAME,BX,BY,BW,WX,WY,WW,WH,MX,MY,MW,MH,TX,TY,TW,TH,MOX,MOY,MOW,MOH) \
52 void GEONAME(void) { \
53 bx = (BX); by = (BY); bw = (BW); \
54 wx = (WX); wy = (WY); ww = (WW); wh = (WH); \
55 mx = (MX); my = (MY); mw = (MW); mh = (MH); \
56 tx = (TX); ty = (TY); tw = (TW); th = (TH); \
57 mox = (MOX); moy = (MOY); mow = (MOW); moh = (MOH); \
61 enum { CurNormal, CurResize, CurMove, CurLast }; /* cursor */
62 enum { ColBorder, ColFG, ColBG, ColLast }; /* color */
63 enum { NetSupported, NetWMName, NetLast }; /* EWMH atoms */
64 enum { WMProtocols, WMDelete, WMName, WMState, WMLast };/* default atoms */
67 typedef struct Client Client;
72 int basew, baseh, incw, inch, maxw, maxh, minw, minh;
73 int minax, maxax, minay, maxay;
75 unsigned int bw, oldbw;
76 Bool isbanned, isfixed, isfloating, isurgent;
86 unsigned long norm[ColLast];
87 unsigned long sel[ColLast];
97 } DC; /* draw context */
107 void (*func)(const char *arg);
113 void (*arrange)(void);
119 const char *instance;
125 /* function declarations */
126 void applyrules(Client *c);
128 void attach(Client *c);
129 void attachstack(Client *c);
131 void buttonpress(XEvent *e);
132 void checkotherwm(void);
134 void configure(Client *c);
135 void configurenotify(XEvent *e);
136 void configurerequest(XEvent *e);
137 unsigned int counttiled(void);
138 void destroynotify(XEvent *e);
139 void detach(Client *c);
140 void detachstack(Client *c);
142 void drawsquare(Bool filled, Bool empty, Bool invert, unsigned long col[ColLast]);
143 void drawtext(const char *text, unsigned long col[ColLast], Bool invert);
144 void *emallocz(unsigned int size);
145 void enternotify(XEvent *e);
146 void eprint(const char *errstr, ...);
147 void expose(XEvent *e);
148 void focus(Client *c);
149 void focusin(XEvent *e);
150 void focusnext(const char *arg);
151 void focusprev(const char *arg);
152 Client *getclient(Window w);
153 unsigned long getcolor(const char *colstr);
154 long getstate(Window w);
155 Bool gettextprop(Window w, Atom atom, char *text, unsigned int size);
156 void grabbuttons(Client *c, Bool focused);
158 unsigned int idxoftag(const char *t);
159 void initfont(const char *fontstr);
160 Bool isoccupied(unsigned int t);
161 Bool isprotodel(Client *c);
162 Bool isurgent(unsigned int t);
163 Bool isvisible(Client *c, Bool *cmp);
164 void keypress(XEvent *e);
165 void killclient(const char *arg);
166 void manage(Window w, XWindowAttributes *wa);
167 void mappingnotify(XEvent *e);
168 void maprequest(XEvent *e);
170 void movemouse(Client *c);
171 Client *nexttiled(Client *c);
172 void propertynotify(XEvent *e);
173 void quit(const char *arg);
174 void reapply(const char *arg);
175 void resize(Client *c, int x, int y, int w, int h, Bool sizehints);
176 void resizemouse(Client *c);
180 void setclientstate(Client *c, long state);
181 void setgeom(const char *arg);
182 void setlayout(const char *arg);
183 void setmfact(const char *arg);
185 void spawn(const char *arg);
186 void tag(const char *arg);
187 unsigned int textnw(const char *text, unsigned int len);
188 unsigned int textw(const char *text);
190 void tilehstack(unsigned int n);
191 Client *tilemaster(unsigned int n);
192 void tileresize(Client *c, int x, int y, int w, int h);
194 void tilevstack(unsigned int n);
195 void togglefloating(const char *arg);
196 void toggletag(const char *arg);
197 void toggleview(const char *arg);
198 void unban(Client *c);
199 void unmanage(Client *c);
200 void unmapnotify(XEvent *e);
201 void updatebarpos(void);
202 void updatesizehints(Client *c);
203 void updatetitle(Client *c);
204 void updatewmhints(Client *c);
205 void view(const char *arg);
206 void viewprevtag(const char *arg); /* views previous selected tags */
207 int xerror(Display *dpy, XErrorEvent *ee);
208 int xerrordummy(Display *dpy, XErrorEvent *ee);
209 int xerrorstart(Display *dpy, XErrorEvent *ee);
210 void zoom(const char *arg);
214 int screen, sx, sy, sw, sh;
215 int (*xerrorxlib)(Display *, XErrorEvent *);
216 int bx, by, bw, bh, blw, bgw, mx, my, mw, mh, mox, moy, mow, moh, tx, ty, tw, th, wx, wy, ww, wh;
219 unsigned int numlockmask = 0;
220 void (*handler[LASTEvent]) (XEvent *) = {
221 [ButtonPress] = buttonpress,
222 [ConfigureRequest] = configurerequest,
223 [ConfigureNotify] = configurenotify,
224 [DestroyNotify] = destroynotify,
225 [EnterNotify] = enternotify,
228 [KeyPress] = keypress,
229 [MappingNotify] = mappingnotify,
230 [MapRequest] = maprequest,
231 [PropertyNotify] = propertynotify,
232 [UnmapNotify] = unmapnotify
234 Atom wmatom[WMLast], netatom[NetLast];
235 Bool otherwm, readin;
238 Client *clients = NULL;
240 Client *stack = NULL;
241 Cursor cursor[CurLast];
247 Layout *lt = layouts;
250 /* configuration, allows nested code to access above variables */
252 #define TAGSZ (LENGTH(tags) * sizeof(Bool))
254 /* function implementations */
257 applyrules(Client *c) {
259 Bool matched = False;
261 XClassHint ch = { 0 };
264 XGetClassHint(dpy, c->win, &ch);
265 for(i = 0; i < LENGTH(rules); i++) {
267 if((!r->title || strstr(c->name, r->title))
268 && (!r->class || (ch.res_class && strstr(ch.res_class, r->class)))
269 && (!r->instance || (ch.res_name && strstr(ch.res_name, r->instance)))) {
270 c->isfloating = r->isfloating;
272 c->tags[idxoftag(r->tag)] = True;
282 memcpy(c->tags, tagset[seltags], TAGSZ);
289 for(c = clients; c; c = c->next)
290 if(isvisible(c, NULL)) {
292 if(lt->isfloating || c->isfloating)
293 resize(c, c->fx, c->fy, c->fw, c->fh, True);
313 attachstack(Client *c) {
322 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
327 buttonpress(XEvent *e) {
330 XButtonPressedEvent *ev = &e->xbutton;
332 if(ev->window == barwin) {
333 if((ev->x < bgw) && ev->button == Button1) {
338 for(i = 0; i < LENGTH(tags); i++) {
340 if(ev->x >= bgw && ev->x < x) {
341 if(ev->button == Button1) {
342 if(ev->state & MODKEY)
347 else if(ev->button == Button3) {
348 if(ev->state & MODKEY)
356 if((ev->x < x + blw) && ev->button == Button1)
359 else if((c = getclient(ev->window))) {
361 if(CLEANMASK(ev->state) != MODKEY)
363 if(ev->button == Button1) {
367 else if(ev->button == Button2) {
368 if(!lt->isfloating && c->isfloating)
369 togglefloating(NULL);
373 else if(ev->button == Button3 && !c->isfixed) {
383 XSetErrorHandler(xerrorstart);
385 /* this causes an error if some other window manager is running */
386 XSelectInput(dpy, DefaultRootWindow(dpy), SubstructureRedirectMask);
389 eprint("dwm: another window manager is already running\n");
391 XSetErrorHandler(NULL);
392 xerrorxlib = XSetErrorHandler(xerror);
404 XFreeFontSet(dpy, dc.font.set);
406 XFreeFont(dpy, dc.font.xfont);
407 XUngrabKey(dpy, AnyKey, AnyModifier, root);
408 XFreePixmap(dpy, dc.drawable);
410 XFreeCursor(dpy, cursor[CurNormal]);
411 XFreeCursor(dpy, cursor[CurResize]);
412 XFreeCursor(dpy, cursor[CurMove]);
413 XDestroyWindow(dpy, barwin);
415 XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime);
419 configure(Client *c) {
422 ce.type = ConfigureNotify;
430 ce.border_width = c->bw;
432 ce.override_redirect = False;
433 XSendEvent(dpy, c->win, False, StructureNotifyMask, (XEvent *)&ce);
437 configurenotify(XEvent *e) {
438 XConfigureEvent *ev = &e->xconfigure;
440 if(ev->window == root && (ev->width != sw || ev->height != sh)) {
443 setgeom(geom->symbol);
448 configurerequest(XEvent *e) {
450 XConfigureRequestEvent *ev = &e->xconfigurerequest;
453 if((c = getclient(ev->window))) {
454 if(ev->value_mask & CWBorderWidth)
455 c->bw = ev->border_width;
456 if(c->isfixed || c->isfloating || lt->isfloating) {
457 if(ev->value_mask & CWX)
459 if(ev->value_mask & CWY)
461 if(ev->value_mask & CWWidth)
463 if(ev->value_mask & CWHeight)
465 if((c->x - sx + c->w) > sw && c->isfloating)
466 c->x = sx + (sw / 2 - c->w / 2); /* center in x direction */
467 if((c->y - sy + c->h) > sh && c->isfloating)
468 c->y = sy + (sh / 2 - c->h / 2); /* center in y direction */
469 if((ev->value_mask & (CWX|CWY))
470 && !(ev->value_mask & (CWWidth|CWHeight)))
472 if(isvisible(c, NULL))
473 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h);
481 wc.width = ev->width;
482 wc.height = ev->height;
483 wc.border_width = ev->border_width;
484 wc.sibling = ev->above;
485 wc.stack_mode = ev->detail;
486 XConfigureWindow(dpy, ev->window, ev->value_mask, &wc);
496 for(n = 0, c = nexttiled(clients); c; c = nexttiled(c->next), n++);
501 destroynotify(XEvent *e) {
503 XDestroyWindowEvent *ev = &e->xdestroywindow;
505 if((c = getclient(ev->window)))
512 c->prev->next = c->next;
514 c->next->prev = c->prev;
517 c->next = c->prev = NULL;
521 detachstack(Client *c) {
524 for(tc=&stack; *tc && *tc != c; tc=&(*tc)->snext);
536 drawtext(geom->symbol, dc.norm, False);
539 for(c = stack; c && !isvisible(c, NULL); c = c->snext);
540 for(i = 0; i < LENGTH(tags); i++) {
541 dc.w = textw(tags[i]);
542 if(tagset[seltags][i]) {
543 drawtext(tags[i], dc.sel, isurgent(i));
544 drawsquare(c && c->tags[i], isoccupied(i), isurgent(i), dc.sel);
547 drawtext(tags[i], dc.norm, isurgent(i));
548 drawsquare(c && c->tags[i], isoccupied(i), isurgent(i), dc.norm);
554 drawtext(lt->symbol, dc.norm, False);
565 drawtext(stext, dc.norm, False);
566 if((dc.w = dc.x - x) > bh) {
569 drawtext(c->name, dc.sel, False);
570 drawsquare(False, c->isfloating, False, dc.sel);
573 drawtext(NULL, dc.norm, False);
575 XCopyArea(dpy, dc.drawable, barwin, dc.gc, 0, 0, bw, bh, 0, 0);
580 drawsquare(Bool filled, Bool empty, Bool invert, unsigned long col[ColLast]) {
583 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
585 gcv.foreground = col[invert ? ColBG : ColFG];
586 XChangeGC(dpy, dc.gc, GCForeground, &gcv);
587 x = (dc.font.ascent + dc.font.descent + 2) / 4;
591 r.width = r.height = x + 1;
592 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
595 r.width = r.height = x;
596 XDrawRectangles(dpy, dc.drawable, dc.gc, &r, 1);
601 drawtext(const char *text, unsigned long col[ColLast], Bool invert) {
603 unsigned int len, olen;
604 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
607 XSetForeground(dpy, dc.gc, col[invert ? ColFG : ColBG]);
608 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
612 len = MIN(olen, sizeof buf);
613 memcpy(buf, text, len);
615 h = dc.font.ascent + dc.font.descent;
616 y = dc.y + (dc.h / 2) - (h / 2) + dc.font.ascent;
618 /* shorten text if necessary */
619 for(; len && (w = textnw(buf, len)) > dc.w - h; len--);
630 XSetForeground(dpy, dc.gc, col[invert ? ColBG : ColFG]);
632 XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
634 XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
638 emallocz(unsigned int size) {
639 void *res = calloc(1, size);
642 eprint("fatal: could not malloc() %u bytes\n", size);
647 enternotify(XEvent *e) {
649 XCrossingEvent *ev = &e->xcrossing;
651 if((ev->mode != NotifyNormal || ev->detail == NotifyInferior) && ev->window != root)
653 if((c = getclient(ev->window)))
660 eprint(const char *errstr, ...) {
663 va_start(ap, errstr);
664 vfprintf(stderr, errstr, ap);
671 XExposeEvent *ev = &e->xexpose;
673 if(ev->count == 0 && (ev->window == barwin))
679 if(!c || (c && !isvisible(c, NULL)))
680 for(c = stack; c && !isvisible(c, NULL); c = c->snext);
681 if(sel && sel != c) {
682 grabbuttons(sel, False);
683 XSetWindowBorder(dpy, sel->win, dc.norm[ColBorder]);
688 grabbuttons(c, True);
692 XSetWindowBorder(dpy, c->win, dc.sel[ColBorder]);
693 XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
696 XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
701 focusin(XEvent *e) { /* there are some broken focus acquiring clients */
702 XFocusChangeEvent *ev = &e->xfocus;
704 if(sel && ev->window != sel->win)
705 XSetInputFocus(dpy, sel->win, RevertToPointerRoot, CurrentTime);
709 focusnext(const char *arg) {
714 for(c = sel->next; c && !isvisible(c, arg ? sel->tags : NULL); c = c->next);
716 for(c = clients; c && !isvisible(c, arg ? sel->tags : NULL); c = c->next);
724 focusprev(const char *arg) {
729 for(c = sel->prev; c && !isvisible(c, arg ? sel->tags : NULL); c = c->prev);
731 for(c = clients; c && c->next; c = c->next);
732 for(; c && !isvisible(c, arg ? sel->tags : NULL); c = c->prev);
741 getclient(Window w) {
744 for(c = clients; c && c->win != w; c = c->next);
749 getcolor(const char *colstr) {
750 Colormap cmap = DefaultColormap(dpy, screen);
753 if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
754 eprint("error, cannot allocate color '%s'\n", colstr);
762 unsigned char *p = NULL;
763 unsigned long n, extra;
766 status = XGetWindowProperty(dpy, w, wmatom[WMState], 0L, 2L, False, wmatom[WMState],
767 &real, &format, &n, &extra, (unsigned char **)&p);
768 if(status != Success)
777 gettextprop(Window w, Atom atom, char *text, unsigned int size) {
782 if(!text || size == 0)
785 XGetTextProperty(dpy, w, &name, atom);
788 if(name.encoding == XA_STRING)
789 strncpy(text, (char *)name.value, size - 1);
791 if(XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success
793 strncpy(text, *list, size - 1);
794 XFreeStringList(list);
797 text[size - 1] = '\0';
803 grabbuttons(Client *c, Bool focused) {
805 unsigned int buttons[] = { Button1, Button2, Button3 };
806 unsigned int modifiers[] = { MODKEY, MODKEY|LockMask, MODKEY|numlockmask,
807 MODKEY|numlockmask|LockMask} ;
809 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
811 for(i = 0; i < LENGTH(buttons); i++)
812 for(j = 0; j < LENGTH(modifiers); j++)
813 XGrabButton(dpy, buttons[i], modifiers[j], c->win, False,
814 BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
816 XGrabButton(dpy, AnyButton, AnyModifier, c->win, False,
817 BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
824 XModifierKeymap *modmap;
826 /* init modifier map */
827 modmap = XGetModifierMapping(dpy);
828 for(i = 0; i < 8; i++)
829 for(j = 0; j < modmap->max_keypermod; j++) {
830 if(modmap->modifiermap[i * modmap->max_keypermod + j] == XKeysymToKeycode(dpy, XK_Num_Lock))
831 numlockmask = (1 << i);
833 XFreeModifiermap(modmap);
835 XUngrabKey(dpy, AnyKey, AnyModifier, root);
836 for(i = 0; i < LENGTH(keys); i++) {
837 code = XKeysymToKeycode(dpy, keys[i].keysym);
838 XGrabKey(dpy, code, keys[i].mod, root, True,
839 GrabModeAsync, GrabModeAsync);
840 XGrabKey(dpy, code, keys[i].mod|LockMask, root, True,
841 GrabModeAsync, GrabModeAsync);
842 XGrabKey(dpy, code, keys[i].mod|numlockmask, root, True,
843 GrabModeAsync, GrabModeAsync);
844 XGrabKey(dpy, code, keys[i].mod|numlockmask|LockMask, root, True,
845 GrabModeAsync, GrabModeAsync);
850 idxoftag(const char *t) {
853 for(i = 0; (i < LENGTH(tags)) && t && strcmp(tags[i], t); i++);
854 return (i < LENGTH(tags)) ? i : 0;
858 initfont(const char *fontstr) {
859 char *def, **missing;
864 XFreeFontSet(dpy, dc.font.set);
865 dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
868 fprintf(stderr, "dwm: missing fontset: %s\n", missing[n]);
869 XFreeStringList(missing);
872 XFontSetExtents *font_extents;
873 XFontStruct **xfonts;
875 dc.font.ascent = dc.font.descent = 0;
876 font_extents = XExtentsOfFontSet(dc.font.set);
877 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
878 for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
879 dc.font.ascent = MAX(dc.font.ascent, (*xfonts)->ascent);
880 dc.font.descent = MAX(dc.font.descent,(*xfonts)->descent);
886 XFreeFont(dpy, dc.font.xfont);
887 dc.font.xfont = NULL;
888 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr))
889 && !(dc.font.xfont = XLoadQueryFont(dpy, "fixed")))
890 eprint("error, cannot load font: '%s'\n", fontstr);
891 dc.font.ascent = dc.font.xfont->ascent;
892 dc.font.descent = dc.font.xfont->descent;
894 dc.font.height = dc.font.ascent + dc.font.descent;
898 isoccupied(unsigned int t) {
901 for(c = clients; c; c = c->next)
908 isprotodel(Client *c) {
913 if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
914 for(i = 0; !ret && i < n; i++)
915 if(protocols[i] == wmatom[WMDelete])
923 isurgent(unsigned int t) {
926 for(c = clients; c; c = c->next)
927 if(c->isurgent && c->tags[t])
933 isvisible(Client *c, Bool *cmp) {
937 cmp = tagset[seltags];
938 for(i = 0; i < LENGTH(tags); i++)
939 if(c->tags[i] && cmp[i])
945 keypress(XEvent *e) {
951 keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
952 for(i = 0; i < LENGTH(keys); i++)
953 if(keysym == keys[i].keysym
954 && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state))
957 keys[i].func(keys[i].arg);
962 killclient(const char *arg) {
967 if(isprotodel(sel)) {
968 ev.type = ClientMessage;
969 ev.xclient.window = sel->win;
970 ev.xclient.message_type = wmatom[WMProtocols];
971 ev.xclient.format = 32;
972 ev.xclient.data.l[0] = wmatom[WMDelete];
973 ev.xclient.data.l[1] = CurrentTime;
974 XSendEvent(dpy, sel->win, False, NoEventMask, &ev);
977 XKillClient(dpy, sel->win);
981 manage(Window w, XWindowAttributes *wa) {
982 Client *c, *t = NULL;
987 c = emallocz(sizeof(Client));
988 c->tags = emallocz(TAGSZ);
994 c->w = c->fw = wa->width;
995 c->h = c->fh = wa->height;
996 c->oldbw = wa->border_width;
997 if(c->w == sw && c->h == sh) {
1000 c->bw = wa->border_width;
1003 if(c->x + c->w + 2 * c->bw > wx + ww)
1004 c->x = wx + ww - c->w - 2 * c->bw;
1005 if(c->y + c->h + 2 * c->bw > wy + wh)
1006 c->y = wy + wh - c->h - 2 * c->bw;
1007 c->x = MAX(c->x, wx);
1008 c->y = MAX(c->y, wy);
1014 wc.border_width = c->bw;
1015 XConfigureWindow(dpy, w, CWBorderWidth, &wc);
1016 XSetWindowBorder(dpy, w, dc.norm[ColBorder]);
1017 configure(c); /* propagates border_width, if size doesn't change */
1019 XSelectInput(dpy, w, EnterWindowMask|FocusChangeMask|PropertyChangeMask|StructureNotifyMask);
1020 grabbuttons(c, False);
1022 if((rettrans = XGetTransientForHint(dpy, w, &trans) == Success))
1023 for(t = clients; t && t->win != trans; t = t->next);
1025 memcpy(c->tags, t->tags, TAGSZ);
1029 c->isfloating = (rettrans == Success) || c->isfixed;
1032 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h); /* some windows require this */
1034 XMapWindow(dpy, c->win);
1035 setclientstate(c, NormalState);
1040 mappingnotify(XEvent *e) {
1041 XMappingEvent *ev = &e->xmapping;
1043 XRefreshKeyboardMapping(ev);
1044 if(ev->request == MappingKeyboard)
1049 maprequest(XEvent *e) {
1050 static XWindowAttributes wa;
1051 XMapRequestEvent *ev = &e->xmaprequest;
1053 if(!XGetWindowAttributes(dpy, ev->window, &wa))
1055 if(wa.override_redirect)
1057 if(!getclient(ev->window))
1058 manage(ev->window, &wa);
1065 for(c = clients; c; c = c->next)
1066 if((lt->isfloating || !c->isfloating) && isvisible(c, NULL))
1067 resize(c, mox, moy, mow - 2 * c->bw, moh - 2 * c->bw, RESIZEHINTS);
1071 movemouse(Client *c) {
1072 int x1, y1, ocx, ocy, di, nx, ny;
1079 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1080 None, cursor[CurMove], CurrentTime) != GrabSuccess)
1082 XQueryPointer(dpy, root, &dummy, &dummy, &x1, &y1, &di, &di, &dui);
1084 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
1087 XUngrabPointer(dpy, CurrentTime);
1089 case ConfigureRequest:
1092 handler[ev.type](&ev);
1096 nx = ocx + (ev.xmotion.x - x1);
1097 ny = ocy + (ev.xmotion.y - y1);
1098 if(abs(wx - nx) < SNAP)
1100 else if(abs((wx + ww) - (nx + c->w + 2 * c->bw)) < SNAP)
1101 nx = wx + ww - c->w - 2 * c->bw;
1102 if(abs(wy - ny) < SNAP)
1104 else if(abs((wy + wh) - (ny + c->h + 2 * c->bw)) < SNAP)
1105 ny = wy + wh - c->h - 2 * c->bw;
1106 if(!c->isfloating && !lt->isfloating && (abs(nx - c->x) > SNAP || abs(ny - c->y) > SNAP))
1107 togglefloating(NULL);
1108 if(lt->isfloating || c->isfloating) {
1111 resize(c, nx, ny, c->w, c->h, False);
1119 nexttiled(Client *c) {
1120 for(; c && (c->isfloating || !isvisible(c, NULL)); c = c->next);
1125 propertynotify(XEvent *e) {
1128 XPropertyEvent *ev = &e->xproperty;
1130 if(ev->state == PropertyDelete)
1131 return; /* ignore */
1132 if((c = getclient(ev->window))) {
1135 case XA_WM_TRANSIENT_FOR:
1136 XGetTransientForHint(dpy, c->win, &trans);
1137 if(!c->isfloating && (c->isfloating = (getclient(trans) != NULL)))
1140 case XA_WM_NORMAL_HINTS:
1148 if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
1157 quit(const char *arg) {
1158 readin = running = False;
1162 reapply(const char *arg) {
1165 for(c = clients; c; c = c->next) {
1166 memset(c->tags, 0, TAGSZ);
1173 resize(Client *c, int x, int y, int w, int h, Bool sizehints) {
1177 /* set minimum possible */
1181 /* temporarily remove base dimensions */
1185 /* adjust for aspect limits */
1186 if(c->minax != c->maxax && c->minay != c->maxay
1187 && c->minax > 0 && c->maxax > 0 && c->minay > 0 && c->maxay > 0)
1189 if(w * c->maxay > h * c->maxax)
1190 w = h * c->maxax / c->maxay;
1191 else if(w * c->minay < h * c->minax)
1192 h = w * c->minay / c->minax;
1195 /* adjust for increment value */
1201 /* restore base dimensions */
1205 w = MAX(w, c->minw);
1206 h = MAX(h, c->minh);
1209 w = MIN(w, c->maxw);
1212 h = MIN(h, c->maxh);
1214 if(w <= 0 || h <= 0)
1217 x = sw - w - 2 * c->bw;
1219 y = sh - h - 2 * c->bw;
1220 if(x + w + 2 * c->bw < sx)
1222 if(y + h + 2 * c->bw < sy)
1224 if(c->x != x || c->y != y || c->w != w || c->h != h) {
1227 c->w = wc.width = w;
1228 c->h = wc.height = h;
1229 wc.border_width = c->bw;
1230 XConfigureWindow(dpy, c->win,
1231 CWX|CWY|CWWidth|CWHeight|CWBorderWidth, &wc);
1238 resizemouse(Client *c) {
1245 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1246 None, cursor[CurResize], CurrentTime) != GrabSuccess)
1248 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->bw - 1, c->h + c->bw - 1);
1250 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask , &ev);
1253 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0,
1254 c->w + c->bw - 1, c->h + c->bw - 1);
1255 XUngrabPointer(dpy, CurrentTime);
1256 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1258 case ConfigureRequest:
1261 handler[ev.type](&ev);
1265 nw = MAX(ev.xmotion.x - ocx - 2 * c->bw + 1, 1);
1266 nh = MAX(ev.xmotion.y - ocy - 2 * c->bw + 1, 1);
1267 if(!c->isfloating && !lt->isfloating && (abs(nw - c->w) > SNAP || abs(nh - c->h) > SNAP)) {
1270 togglefloating(NULL);
1272 if((lt->isfloating) || c->isfloating) {
1273 resize(c, c->x, c->y, nw, nh, True);
1291 if(sel->isfloating || lt->isfloating)
1292 XRaiseWindow(dpy, sel->win);
1293 if(!lt->isfloating) {
1294 wc.stack_mode = Below;
1295 wc.sibling = barwin;
1296 for(c = stack; c; c = c->snext)
1297 if(!c->isfloating && isvisible(c, NULL)) {
1298 XConfigureWindow(dpy, c->win, CWSibling|CWStackMode, &wc);
1299 wc.sibling = c->win;
1303 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1309 char sbuf[sizeof stext];
1312 unsigned int len, offset;
1315 /* main event loop, also reads status text from stdin */
1317 xfd = ConnectionNumber(dpy);
1320 len = sizeof stext - 1;
1321 sbuf[len] = stext[len] = '\0'; /* 0-terminator is never touched */
1325 FD_SET(STDIN_FILENO, &rd);
1327 if(select(xfd + 1, &rd, NULL, NULL, NULL) == -1) {
1330 eprint("select failed\n");
1332 if(FD_ISSET(STDIN_FILENO, &rd)) {
1333 switch((r = read(STDIN_FILENO, sbuf + offset, len - offset))) {
1335 strncpy(stext, strerror(errno), len);
1339 strncpy(stext, "EOF", 4);
1343 for(p = sbuf + offset; r > 0; p++, r--, offset++)
1344 if(*p == '\n' || *p == '\0') {
1346 strncpy(stext, sbuf, len);
1347 p += r - 1; /* p is sbuf + offset + r - 1 */
1348 for(r = 0; *(p - r) && *(p - r) != '\n'; r++);
1351 memmove(sbuf, p - r + 1, r);
1358 while(XPending(dpy)) {
1359 XNextEvent(dpy, &ev);
1360 if(handler[ev.type])
1361 (handler[ev.type])(&ev); /* call handler */
1368 unsigned int i, num;
1369 Window *wins, d1, d2;
1370 XWindowAttributes wa;
1373 if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1374 for(i = 0; i < num; i++) {
1375 if(!XGetWindowAttributes(dpy, wins[i], &wa)
1376 || wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1378 if(wa.map_state == IsViewable || getstate(wins[i]) == IconicState)
1379 manage(wins[i], &wa);
1381 for(i = 0; i < num; i++) { /* now the transients */
1382 if(!XGetWindowAttributes(dpy, wins[i], &wa))
1384 if(XGetTransientForHint(dpy, wins[i], &d1)
1385 && (wa.map_state == IsViewable || getstate(wins[i]) == IconicState))
1386 manage(wins[i], &wa);
1394 setclientstate(Client *c, long state) {
1395 long data[] = {state, None};
1397 XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1398 PropModeReplace, (unsigned char *)data, 2);
1402 setgeom(const char *arg) {
1406 if(++geom == &geoms[LENGTH(geoms)])
1410 for(i = 0; i < LENGTH(geoms); i++)
1411 if(!strcmp(geoms[i].symbol, arg))
1413 if(i == LENGTH(geoms))
1423 setlayout(const char *arg) {
1427 if(++lt == &layouts[LENGTH(layouts)])
1431 for(i = 0; i < LENGTH(layouts); i++)
1432 if(!strcmp(arg, layouts[i].symbol))
1434 if(i == LENGTH(layouts))
1445 setmfact(const char *arg) {
1453 d = strtod(arg, NULL);
1454 if(arg[0] == '-' || arg[0] == '+')
1456 if(d < 0.1 || d > 0.9)
1460 setgeom(geom->symbol);
1466 XSetWindowAttributes wa;
1469 screen = DefaultScreen(dpy);
1470 root = RootWindow(dpy, screen);
1473 /* apply default geometry */
1476 sw = DisplayWidth(dpy, screen);
1477 sh = DisplayHeight(dpy, screen);
1478 bh = dc.font.height + 2;
1483 wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1484 wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1485 wmatom[WMName] = XInternAtom(dpy, "WM_NAME", False);
1486 wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1487 netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1488 netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1491 wa.cursor = cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1492 cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1493 cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1495 /* init appearance */
1496 dc.norm[ColBorder] = getcolor(NORMBORDERCOLOR);
1497 dc.norm[ColBG] = getcolor(NORMBGCOLOR);
1498 dc.norm[ColFG] = getcolor(NORMFGCOLOR);
1499 dc.sel[ColBorder] = getcolor(SELBORDERCOLOR);
1500 dc.sel[ColBG] = getcolor(SELBGCOLOR);
1501 dc.sel[ColFG] = getcolor(SELFGCOLOR);
1504 dc.drawable = XCreatePixmap(dpy, root, DisplayWidth(dpy, screen), bh, DefaultDepth(dpy, screen));
1505 dc.gc = XCreateGC(dpy, root, 0, 0);
1506 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
1508 XSetFont(dpy, dc.gc, dc.font.xfont->fid);
1511 tagset[0] = emallocz(TAGSZ);
1512 tagset[1] = emallocz(TAGSZ);
1513 tagset[0][0] = tagset[1][0] = True;
1516 for(blw = i = 0; LENGTH(layouts) > 1 && i < LENGTH(layouts); i++) {
1517 w = textw(layouts[i].symbol);
1520 for(bgw = i = 0; LENGTH(geoms) > 1 && i < LENGTH(geoms); i++) {
1521 w = textw(geoms[i].symbol);
1525 wa.override_redirect = 1;
1526 wa.background_pixmap = ParentRelative;
1527 wa.event_mask = ButtonPressMask|ExposureMask;
1529 barwin = XCreateWindow(dpy, root, bx, by, bw, bh, 0, DefaultDepth(dpy, screen),
1530 CopyFromParent, DefaultVisual(dpy, screen),
1531 CWOverrideRedirect|CWBackPixmap|CWEventMask, &wa);
1532 XDefineCursor(dpy, barwin, cursor[CurNormal]);
1533 XMapRaised(dpy, barwin);
1534 strcpy(stext, "dwm-"VERSION);
1537 /* EWMH support per view */
1538 XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1539 PropModeReplace, (unsigned char *) netatom, NetLast);
1541 /* select for events */
1542 wa.event_mask = SubstructureRedirectMask|SubstructureNotifyMask
1543 |EnterWindowMask|LeaveWindowMask|StructureNotifyMask;
1544 XChangeWindowAttributes(dpy, root, CWEventMask|CWCursor, &wa);
1545 XSelectInput(dpy, root, wa.event_mask);
1553 spawn(const char *arg) {
1554 static char *shell = NULL;
1556 if(!shell && !(shell = getenv("SHELL")))
1560 /* The double-fork construct avoids zombie processes and keeps the code
1561 * clean from stupid signal handlers. */
1565 close(ConnectionNumber(dpy));
1567 execl(shell, shell, "-c", arg, (char *)NULL);
1568 fprintf(stderr, "dwm: execl '%s -c %s'", shell, arg);
1577 tag(const char *arg) {
1582 for(i = 0; i < LENGTH(tags); i++)
1583 sel->tags[i] = (NULL == arg);
1584 sel->tags[idxoftag(arg)] = True;
1589 textnw(const char *text, unsigned int len) {
1593 XmbTextExtents(dc.font.set, text, len, NULL, &r);
1596 return XTextWidth(dc.font.xfont, text, len);
1600 textw(const char *text) {
1601 return textnw(text, strlen(text)) + dc.font.height;
1607 unsigned int i, n = counttiled();
1621 for(i = 0, c = nexttiled(c->next); c; c = nexttiled(c->next), i++) {
1622 if(i + 1 == n) /* remainder */
1623 tileresize(c, x, ty, (tx + tw) - x - 2 * c->bw, th - 2 * c->bw);
1625 tileresize(c, x, ty, w - 2 * c->bw, th - 2 * c->bw);
1627 x = c->x + c->w + 2 * c->bw;
1632 tilemaster(unsigned int n) {
1633 Client *c = nexttiled(clients);
1636 tileresize(c, mox, moy, mow - 2 * c->bw, moh - 2 * c->bw);
1638 tileresize(c, mx, my, mw - 2 * c->bw, mh - 2 * c->bw);
1643 tileresize(Client *c, int x, int y, int w, int h) {
1644 resize(c, x, y, w, h, RESIZEHINTS);
1645 if((RESIZEHINTS) && ((c->h < bh) || (c->h > h) || (c->w < bh) || (c->w > w)))
1646 /* client doesn't accept size constraints */
1647 resize(c, x, y, w, h, False);
1653 unsigned int i, n = counttiled();
1667 for(i = 0, c = nexttiled(c->next); c; c = nexttiled(c->next), i++) {
1668 if(i + 1 == n) /* remainder */
1669 tileresize(c, tx, y, tw - 2 * c->bw, (ty + th) - y - 2 * c->bw);
1671 tileresize(c, tx, y, tw - 2 * c->bw, h - 2 * c->bw);
1673 y = c->y + c->h + 2 * c->bw;
1678 togglefloating(const char *arg) {
1681 sel->isfloating = !sel->isfloating;
1683 resize(sel, sel->x, sel->y, sel->w, sel->h, True);
1688 toggletag(const char *arg) {
1694 sel->tags[i] = !sel->tags[i];
1695 for(j = 0; j < LENGTH(tags) && !sel->tags[j]; j++);
1696 if(j == LENGTH(tags))
1697 sel->tags[i] = True; /* at least one tag must be enabled */
1702 toggleview(const char *arg) {
1706 tagset[seltags][i] = !tagset[seltags][i];
1707 for(j = 0; j < LENGTH(tags) && !tagset[seltags][j]; j++);
1708 if(j == LENGTH(tags))
1709 tagset[seltags][i] = True; /* at least one tag must be viewed */
1717 XMoveWindow(dpy, c->win, c->x, c->y);
1718 c->isbanned = False;
1722 unmanage(Client *c) {
1725 wc.border_width = c->oldbw;
1726 /* The server grab construct avoids race conditions. */
1728 XSetErrorHandler(xerrordummy);
1729 XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
1734 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1735 setclientstate(c, WithdrawnState);
1739 XSetErrorHandler(xerror);
1745 unmapnotify(XEvent *e) {
1747 XUnmapEvent *ev = &e->xunmap;
1749 if((c = getclient(ev->window)))
1754 updatebarpos(void) {
1756 if(dc.drawable != 0)
1757 XFreePixmap(dpy, dc.drawable);
1758 dc.drawable = XCreatePixmap(dpy, root, bw, bh, DefaultDepth(dpy, screen));
1759 XMoveResizeWindow(dpy, barwin, bx, by, bw, bh);
1763 updatesizehints(Client *c) {
1767 if(!XGetWMNormalHints(dpy, c->win, &size, &msize) || !size.flags)
1769 c->flags = size.flags;
1770 if(c->flags & PBaseSize) {
1771 c->basew = size.base_width;
1772 c->baseh = size.base_height;
1774 else if(c->flags & PMinSize) {
1775 c->basew = size.min_width;
1776 c->baseh = size.min_height;
1779 c->basew = c->baseh = 0;
1780 if(c->flags & PResizeInc) {
1781 c->incw = size.width_inc;
1782 c->inch = size.height_inc;
1785 c->incw = c->inch = 0;
1786 if(c->flags & PMaxSize) {
1787 c->maxw = size.max_width;
1788 c->maxh = size.max_height;
1791 c->maxw = c->maxh = 0;
1792 if(c->flags & PMinSize) {
1793 c->minw = size.min_width;
1794 c->minh = size.min_height;
1796 else if(c->flags & PBaseSize) {
1797 c->minw = size.base_width;
1798 c->minh = size.base_height;
1801 c->minw = c->minh = 0;
1802 if(c->flags & PAspect) {
1803 c->minax = size.min_aspect.x;
1804 c->maxax = size.max_aspect.x;
1805 c->minay = size.min_aspect.y;
1806 c->maxay = size.max_aspect.y;
1809 c->minax = c->maxax = c->minay = c->maxay = 0;
1810 c->isfixed = (c->maxw && c->minw && c->maxh && c->minh
1811 && c->maxw == c->minw && c->maxh == c->minh);
1815 updatetitle(Client *c) {
1816 if(!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
1817 gettextprop(c->win, wmatom[WMName], c->name, sizeof c->name);
1821 updatewmhints(Client *c) {
1824 if((wmh = XGetWMHints(dpy, c->win))) {
1826 sel->isurgent = False;
1828 c->isurgent = (wmh->flags & XUrgencyHint) ? True : False;
1834 view(const char *arg) {
1836 memset(tagset[seltags], (NULL == arg), TAGSZ);
1837 tagset[seltags][idxoftag(arg)] = True;
1842 viewprevtag(const char *arg) {
1843 seltags ^= 1; /* toggle sel tagset */
1847 /* There's no way to check accesses to destroyed windows, thus those cases are
1848 * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
1849 * default error handler, which may call exit. */
1851 xerror(Display *dpy, XErrorEvent *ee) {
1852 if(ee->error_code == BadWindow
1853 || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1854 || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1855 || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1856 || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1857 || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1858 || (ee->request_code == X_GrabButton && ee->error_code == BadAccess)
1859 || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1860 || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1862 fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1863 ee->request_code, ee->error_code);
1864 return xerrorxlib(dpy, ee); /* may call exit */
1868 xerrordummy(Display *dpy, XErrorEvent *ee) {
1872 /* Startup Error handler to check if another window manager
1873 * is already running. */
1875 xerrorstart(Display *dpy, XErrorEvent *ee) {
1881 zoom(const char *arg) {
1884 if(c == nexttiled(clients))
1885 if(!c || !(c = nexttiled(c->next)))
1887 if(!lt->isfloating && !sel->isfloating) {
1896 main(int argc, char *argv[]) {
1897 if(argc == 2 && !strcmp("-v", argv[1]))
1898 eprint("dwm-"VERSION", © 2006-2008 dwm engineers, see LICENSE for details\n");
1900 eprint("usage: dwm [-v]\n");
1902 setlocale(LC_CTYPE, "");
1903 if(!(dpy = XOpenDisplay(0)))
1904 eprint("dwm: cannot open display\n");