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)
49 #define DEFGEOM(GEONAME,BX,BY,BW,WX,WY,WW,WH,MX,MY,MW,MH,TX,TY,TW,TH,MOX,MOY,MOW,MOH) \
50 void GEONAME(void) { \
51 bx = (BX); by = (BY); bw = (BW); \
52 wx = (WX); wy = (WY); ww = (WW); wh = (WH); \
53 mx = (MX); my = (MY); mw = (MW); mh = (MH); \
54 tx = (TX); ty = (TY); tw = (TW); th = (TH); \
55 mox = (MOX); moy = (MOY); mow = (MOW); moh = (MOH); \
59 enum { CurNormal, CurResize, CurMove, CurLast }; /* cursor */
60 enum { ColBorder, ColFG, ColBG, ColLast }; /* color */
61 enum { NetSupported, NetWMName, NetLast }; /* EWMH atoms */
62 enum { WMProtocols, WMDelete, WMName, WMState, WMLast };/* default atoms */
65 typedef struct Client Client;
69 int basew, baseh, incw, inch, maxw, maxh, minw, minh;
70 int minax, maxax, minay, maxay;
72 unsigned int bw, oldbw;
73 Bool isbanned, isfixed, isfloating, isurgent;
83 unsigned long norm[ColLast];
84 unsigned long sel[ColLast];
94 } DC; /* draw context */
104 void (*func)(const char *arg);
110 void (*arrange)(void);
116 const char *instance;
122 /* function declarations */
123 void applyrules(Client *c);
125 void attach(Client *c);
126 void attachstack(Client *c);
128 void buttonpress(XEvent *e);
129 void checkotherwm(void);
131 void configure(Client *c);
132 void configurenotify(XEvent *e);
133 void configurerequest(XEvent *e);
134 unsigned int counttiled(void);
135 void destroynotify(XEvent *e);
136 void detach(Client *c);
137 void detachstack(Client *c);
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(void); /* 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 long getstate(Window w);
153 Bool gettextprop(Window w, Atom atom, char *text, unsigned int size);
154 void grabbuttons(Client *c, Bool focused);
156 unsigned int idxoftag(const char *t);
157 void initfont(const char *fontstr);
158 Bool isoccupied(unsigned int t);
159 Bool isprotodel(Client *c);
160 Bool isurgent(unsigned int t);
161 Bool isvisible(Client *c);
162 void keypress(XEvent *e);
163 void killclient(const char *arg);
164 void manage(Window w, XWindowAttributes *wa);
165 void mappingnotify(XEvent *e);
166 void maprequest(XEvent *e);
168 void movemouse(Client *c);
169 Client *nexttiled(Client *c);
170 void propertynotify(XEvent *e);
171 void quit(const char *arg);
172 void reapply(const char *arg);
173 void resize(Client *c, int x, int y, int w, int h, Bool sizehints);
174 void resizemouse(Client *c);
178 void setclientstate(Client *c, long state);
179 void setgeom(const char *arg);
180 void setlayout(const char *arg);
182 void spawn(const char *arg);
183 void tag(const char *arg);
184 unsigned int textnw(const char *text, unsigned int len);
185 unsigned int textw(const char *text);
187 void tilehstack(unsigned int n);
188 Client *tilemaster(unsigned int n);
189 void tileresize(Client *c, int x, int y, int w, int h);
191 void tilevstack(unsigned int n);
192 void togglefloating(const char *arg);
193 void toggletag(const char *arg);
194 void toggleview(const char *arg);
195 void unban(Client *c);
196 void unmanage(Client *c);
197 void unmapnotify(XEvent *e);
198 void updatebarpos(void);
199 void updatesizehints(Client *c);
200 void updatetitle(Client *c);
201 void updatewmhints(Client *c);
202 void view(const char *arg);
203 void viewprevtag(const char *arg); /* views previous selected tags */
204 int xerror(Display *dpy, XErrorEvent *ee);
205 int xerrordummy(Display *dpy, XErrorEvent *ee);
206 int xerrorstart(Display *dpy, XErrorEvent *ee);
207 void zoom(const char *arg);
210 char stext[256], buf[256];
211 int screen, sx, sy, sw, sh;
212 int (*xerrorxlib)(Display *, XErrorEvent *);
213 int bx, by, bw, bh, blw, bgw, mx, my, mw, mh, mox, moy, mow, moh, tx, ty, tw, th, wx, wy, ww, wh;
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 otherwm, readin;
234 Client *clients = NULL;
236 Client *stack = NULL;
237 Cursor cursor[CurLast];
244 /* configuration, allows nested code to access above variables */
246 #define TAGSZ (LENGTH(tags) * sizeof(Bool))
247 static Bool tmp[LENGTH(tags)];
249 /* function implementations */
252 applyrules(Client *c) {
254 Bool matched = False;
256 XClassHint ch = { 0 };
259 XGetClassHint(dpy, c->win, &ch);
260 for(i = 0; i < LENGTH(rules); i++) {
262 if((r->title && strstr(c->name, r->title))
263 || (ch.res_class && r->class && strstr(ch.res_class, r->class))
264 || (ch.res_name && r->instance && strstr(ch.res_name, r->instance)))
266 c->isfloating = r->isfloating;
268 c->tags[idxoftag(r->tag)] = True;
278 memcpy(c->tags, seltags, TAGSZ);
285 for(c = clients; c; c = c->next)
305 attachstack(Client *c) {
314 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
319 buttonpress(XEvent *e) {
322 XButtonPressedEvent *ev = &e->xbutton;
324 if(ev->window == barwin) {
326 for(i = 0; i < LENGTH(tags); i++) {
328 if(ev->x > bgw && ev->x < x) {
329 if(ev->button == Button1) {
330 if(ev->state & MODKEY)
335 else if(ev->button == Button3) {
336 if(ev->state & MODKEY)
345 else if((c = getclient(ev->window))) {
347 if(CLEANMASK(ev->state) != MODKEY)
349 if(ev->button == Button1) {
353 else if(ev->button == Button2) {
354 if((floating != lt->arrange) && c->isfloating)
355 togglefloating(NULL);
359 else if(ev->button == Button3 && !c->isfixed) {
369 XSetErrorHandler(xerrorstart);
371 /* this causes an error if some other window manager is running */
372 XSelectInput(dpy, DefaultRootWindow(dpy), SubstructureRedirectMask);
375 eprint("dwm: another window manager is already running\n");
377 XSetErrorHandler(NULL);
378 xerrorxlib = XSetErrorHandler(xerror);
390 XFreeFontSet(dpy, dc.font.set);
392 XFreeFont(dpy, dc.font.xfont);
393 XUngrabKey(dpy, AnyKey, AnyModifier, root);
394 XFreePixmap(dpy, dc.drawable);
396 XFreeCursor(dpy, cursor[CurNormal]);
397 XFreeCursor(dpy, cursor[CurResize]);
398 XFreeCursor(dpy, cursor[CurMove]);
399 XDestroyWindow(dpy, barwin);
401 XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime);
405 configure(Client *c) {
408 ce.type = ConfigureNotify;
416 ce.border_width = c->bw;
418 ce.override_redirect = False;
419 XSendEvent(dpy, c->win, False, StructureNotifyMask, (XEvent *)&ce);
423 configurenotify(XEvent *e) {
424 XConfigureEvent *ev = &e->xconfigure;
426 if(ev->window == root && (ev->width != sw || ev->height != sh)) {
434 configurerequest(XEvent *e) {
436 XConfigureRequestEvent *ev = &e->xconfigurerequest;
439 if((c = getclient(ev->window))) {
440 if(ev->value_mask & CWBorderWidth)
441 c->bw = ev->border_width;
442 if(c->isfixed || c->isfloating || lt->isfloating) {
443 if(ev->value_mask & CWX)
445 if(ev->value_mask & CWY)
447 if(ev->value_mask & CWWidth)
449 if(ev->value_mask & CWHeight)
451 if((c->x - sx + c->w) > sw && c->isfloating)
452 c->x = sx + (sw / 2 - c->w / 2); /* center in x direction */
453 if((c->y - sy + c->h) > sh && c->isfloating)
454 c->y = sy + (sh / 2 - c->h / 2); /* center in y direction */
455 if((ev->value_mask & (CWX|CWY))
456 && !(ev->value_mask & (CWWidth|CWHeight)))
459 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h);
467 wc.width = ev->width;
468 wc.height = ev->height;
469 wc.border_width = ev->border_width;
470 wc.sibling = ev->above;
471 wc.stack_mode = ev->detail;
472 XConfigureWindow(dpy, ev->window, ev->value_mask, &wc);
482 for(n = 0, c = nexttiled(clients); c; c = nexttiled(c->next), n++);
487 destroynotify(XEvent *e) {
489 XDestroyWindowEvent *ev = &e->xdestroywindow;
491 if((c = getclient(ev->window)))
498 c->prev->next = c->next;
500 c->next->prev = c->prev;
503 c->next = c->prev = NULL;
507 detachstack(Client *c) {
510 for(tc=&stack; *tc && *tc != c; tc=&(*tc)->snext);
521 drawtext(geom->symbol, dc.norm, False);
523 for(c = stack; c && !isvisible(c); c = c->snext);
524 for(i = 0; i < LENGTH(tags); i++) {
525 dc.w = textw(tags[i]);
527 drawtext(tags[i], dc.sel, isurgent(i));
528 drawsquare(c && c->tags[i], isoccupied(i), isurgent(i), dc.sel);
531 drawtext(tags[i], dc.norm, isurgent(i));
532 drawsquare(c && c->tags[i], isoccupied(i), isurgent(i), dc.norm);
537 drawtext(lt->symbol, dc.norm, False);
545 drawtext(stext, dc.norm, False);
546 if((dc.w = dc.x - x) > bh) {
549 drawtext(c->name, dc.sel, False);
550 drawsquare(False, c->isfloating, False, dc.sel);
553 drawtext(NULL, dc.norm, False);
555 XCopyArea(dpy, dc.drawable, barwin, dc.gc, 0, 0, bw, bh, 0, 0);
560 drawsquare(Bool filled, Bool empty, Bool invert, unsigned long col[ColLast]) {
563 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
565 gcv.foreground = col[invert ? ColBG : ColFG];
566 XChangeGC(dpy, dc.gc, GCForeground, &gcv);
567 x = (dc.font.ascent + dc.font.descent + 2) / 4;
571 r.width = r.height = x + 1;
572 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
575 r.width = r.height = x;
576 XDrawRectangles(dpy, dc.drawable, dc.gc, &r, 1);
581 drawtext(const char *text, unsigned long col[ColLast], Bool invert) {
583 unsigned int len, olen;
584 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
586 XSetForeground(dpy, dc.gc, col[invert ? ColFG : ColBG]);
587 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
591 olen = len = strlen(text);
592 if(len >= sizeof buf)
593 len = sizeof buf - 1;
594 memcpy(buf, text, len);
596 h = dc.font.ascent + dc.font.descent;
597 y = dc.y + (dc.h / 2) - (h / 2) + dc.font.ascent;
599 /* shorten text if necessary */
600 while(len && (w = textnw(buf, len)) > dc.w - h)
611 return; /* too long */
612 XSetForeground(dpy, dc.gc, col[invert ? ColBG : ColFG]);
614 XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
616 XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
620 emallocz(unsigned int size) {
621 void *res = calloc(1, size);
624 eprint("fatal: could not malloc() %u bytes\n", size);
629 enternotify(XEvent *e) {
631 XCrossingEvent *ev = &e->xcrossing;
633 if((ev->mode != NotifyNormal || ev->detail == NotifyInferior) && ev->window != root)
635 if((c = getclient(ev->window)))
642 eprint(const char *errstr, ...) {
645 va_start(ap, errstr);
646 vfprintf(stderr, errstr, ap);
653 XExposeEvent *ev = &e->xexpose;
655 if(ev->count == 0 && (ev->window == barwin))
660 floating(void) { /* default floating layout */
663 for(c = clients; c; c = c->next)
665 resize(c, c->x, c->y, c->w, c->h, True);
670 if(!c || (c && !isvisible(c)))
671 for(c = stack; c && !isvisible(c); c = c->snext);
672 if(sel && sel != c) {
673 grabbuttons(sel, False);
674 XSetWindowBorder(dpy, sel->win, dc.norm[ColBorder]);
679 grabbuttons(c, True);
683 XSetWindowBorder(dpy, c->win, dc.sel[ColBorder]);
684 XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
687 XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
692 focusin(XEvent *e) { /* there are some broken focus acquiring clients */
693 XFocusChangeEvent *ev = &e->xfocus;
695 if(sel && ev->window != sel->win)
696 XSetInputFocus(dpy, sel->win, RevertToPointerRoot, CurrentTime);
700 focusnext(const char *arg) {
705 for(c = sel->next; c && !isvisible(c); c = c->next);
707 for(c = clients; c && !isvisible(c); c = c->next);
715 focusprev(const char *arg) {
720 for(c = sel->prev; c && !isvisible(c); c = c->prev);
722 for(c = clients; c && c->next; c = c->next);
723 for(; c && !isvisible(c); c = c->prev);
732 getclient(Window w) {
735 for(c = clients; c && c->win != w; c = c->next);
740 getcolor(const char *colstr) {
741 Colormap cmap = DefaultColormap(dpy, screen);
744 if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
745 eprint("error, cannot allocate color '%s'\n", colstr);
753 unsigned char *p = NULL;
754 unsigned long n, extra;
757 status = XGetWindowProperty(dpy, w, wmatom[WMState], 0L, 2L, False, wmatom[WMState],
758 &real, &format, &n, &extra, (unsigned char **)&p);
759 if(status != Success)
768 gettextprop(Window w, Atom atom, char *text, unsigned int size) {
773 if(!text || size == 0)
776 XGetTextProperty(dpy, w, &name, atom);
779 if(name.encoding == XA_STRING)
780 strncpy(text, (char *)name.value, size - 1);
782 if(XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success
784 strncpy(text, *list, size - 1);
785 XFreeStringList(list);
788 text[size - 1] = '\0';
794 grabbuttons(Client *c, Bool focused) {
795 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
798 XGrabButton(dpy, Button1, MODKEY, c->win, False, BUTTONMASK,
799 GrabModeAsync, GrabModeSync, None, None);
800 XGrabButton(dpy, Button1, MODKEY|LockMask, c->win, False, BUTTONMASK,
801 GrabModeAsync, GrabModeSync, None, None);
802 XGrabButton(dpy, Button1, MODKEY|numlockmask, c->win, False, BUTTONMASK,
803 GrabModeAsync, GrabModeSync, None, None);
804 XGrabButton(dpy, Button1, MODKEY|numlockmask|LockMask, c->win, False, BUTTONMASK,
805 GrabModeAsync, GrabModeSync, None, None);
807 XGrabButton(dpy, Button2, MODKEY, c->win, False, BUTTONMASK,
808 GrabModeAsync, GrabModeSync, None, None);
809 XGrabButton(dpy, Button2, MODKEY|LockMask, c->win, False, BUTTONMASK,
810 GrabModeAsync, GrabModeSync, None, None);
811 XGrabButton(dpy, Button2, MODKEY|numlockmask, c->win, False, BUTTONMASK,
812 GrabModeAsync, GrabModeSync, None, None);
813 XGrabButton(dpy, Button2, MODKEY|numlockmask|LockMask, c->win, False, BUTTONMASK,
814 GrabModeAsync, GrabModeSync, None, None);
816 XGrabButton(dpy, Button3, MODKEY, c->win, False, BUTTONMASK,
817 GrabModeAsync, GrabModeSync, None, None);
818 XGrabButton(dpy, Button3, MODKEY|LockMask, c->win, False, BUTTONMASK,
819 GrabModeAsync, GrabModeSync, None, None);
820 XGrabButton(dpy, Button3, MODKEY|numlockmask, c->win, False, BUTTONMASK,
821 GrabModeAsync, GrabModeSync, None, None);
822 XGrabButton(dpy, Button3, MODKEY|numlockmask|LockMask, c->win, False, BUTTONMASK,
823 GrabModeAsync, GrabModeSync, None, None);
826 XGrabButton(dpy, AnyButton, AnyModifier, c->win, False, BUTTONMASK,
827 GrabModeAsync, GrabModeSync, None, None);
834 XModifierKeymap *modmap;
836 /* init modifier map */
837 modmap = XGetModifierMapping(dpy);
838 for(i = 0; i < 8; i++)
839 for(j = 0; j < modmap->max_keypermod; j++) {
840 if(modmap->modifiermap[i * modmap->max_keypermod + j] == XKeysymToKeycode(dpy, XK_Num_Lock))
841 numlockmask = (1 << i);
843 XFreeModifiermap(modmap);
845 XUngrabKey(dpy, AnyKey, AnyModifier, root);
846 for(i = 0; i < LENGTH(keys); i++) {
847 code = XKeysymToKeycode(dpy, keys[i].keysym);
848 XGrabKey(dpy, code, keys[i].mod, root, True,
849 GrabModeAsync, GrabModeAsync);
850 XGrabKey(dpy, code, keys[i].mod|LockMask, root, True,
851 GrabModeAsync, GrabModeAsync);
852 XGrabKey(dpy, code, keys[i].mod|numlockmask, root, True,
853 GrabModeAsync, GrabModeAsync);
854 XGrabKey(dpy, code, keys[i].mod|numlockmask|LockMask, root, True,
855 GrabModeAsync, GrabModeAsync);
860 idxoftag(const char *t) {
863 for(i = 0; (i < LENGTH(tags)) && t && strcmp(tags[i], t); i++);
864 return (i < LENGTH(tags)) ? i : 0;
868 initfont(const char *fontstr) {
869 char *def, **missing;
874 XFreeFontSet(dpy, dc.font.set);
875 dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
878 fprintf(stderr, "dwm: missing fontset: %s\n", missing[n]);
879 XFreeStringList(missing);
882 XFontSetExtents *font_extents;
883 XFontStruct **xfonts;
885 dc.font.ascent = dc.font.descent = 0;
886 font_extents = XExtentsOfFontSet(dc.font.set);
887 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
888 for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
889 if(dc.font.ascent < (*xfonts)->ascent)
890 dc.font.ascent = (*xfonts)->ascent;
891 if(dc.font.descent < (*xfonts)->descent)
892 dc.font.descent = (*xfonts)->descent;
898 XFreeFont(dpy, dc.font.xfont);
899 dc.font.xfont = NULL;
900 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr))
901 && !(dc.font.xfont = XLoadQueryFont(dpy, "fixed")))
902 eprint("error, cannot load font: '%s'\n", fontstr);
903 dc.font.ascent = dc.font.xfont->ascent;
904 dc.font.descent = dc.font.xfont->descent;
906 dc.font.height = dc.font.ascent + dc.font.descent;
910 isoccupied(unsigned int t) {
913 for(c = clients; c; c = c->next)
920 isprotodel(Client *c) {
925 if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
926 for(i = 0; !ret && i < n; i++)
927 if(protocols[i] == wmatom[WMDelete])
935 isurgent(unsigned int t) {
938 for(c = clients; c; c = c->next)
939 if(c->isurgent && c->tags[t])
945 isvisible(Client *c) {
948 for(i = 0; i < LENGTH(tags); i++)
949 if(c->tags[i] && seltags[i])
955 keypress(XEvent *e) {
961 keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
962 for(i = 0; i < LENGTH(keys); i++)
963 if(keysym == keys[i].keysym
964 && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state))
967 keys[i].func(keys[i].arg);
972 killclient(const char *arg) {
977 if(isprotodel(sel)) {
978 ev.type = ClientMessage;
979 ev.xclient.window = sel->win;
980 ev.xclient.message_type = wmatom[WMProtocols];
981 ev.xclient.format = 32;
982 ev.xclient.data.l[0] = wmatom[WMDelete];
983 ev.xclient.data.l[1] = CurrentTime;
984 XSendEvent(dpy, sel->win, False, NoEventMask, &ev);
987 XKillClient(dpy, sel->win);
991 manage(Window w, XWindowAttributes *wa) {
992 Client *c, *t = NULL;
997 c = emallocz(sizeof(Client));
998 c->tags = emallocz(TAGSZ);
1006 c->oldbw = wa->border_width;
1007 if(c->w == sw && c->h == sh) {
1010 c->bw = wa->border_width;
1013 if(c->x + c->w + 2 * c->bw > wx + ww)
1014 c->x = wx + ww - c->w - 2 * c->bw;
1015 if(c->y + c->h + 2 * c->bw > wy + wh)
1016 c->y = wy + wh - c->h - 2 * c->bw;
1024 wc.border_width = c->bw;
1025 XConfigureWindow(dpy, w, CWBorderWidth, &wc);
1026 XSetWindowBorder(dpy, w, dc.norm[ColBorder]);
1027 configure(c); /* propagates border_width, if size doesn't change */
1029 XSelectInput(dpy, w, EnterWindowMask|FocusChangeMask|PropertyChangeMask|StructureNotifyMask);
1030 grabbuttons(c, False);
1032 if((rettrans = XGetTransientForHint(dpy, w, &trans) == Success))
1033 for(t = clients; t && t->win != trans; t = t->next);
1035 memcpy(c->tags, t->tags, TAGSZ);
1039 c->isfloating = (rettrans == Success) || c->isfixed;
1042 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h); /* some windows require this */
1044 XMapWindow(dpy, c->win);
1045 setclientstate(c, NormalState);
1050 mappingnotify(XEvent *e) {
1051 XMappingEvent *ev = &e->xmapping;
1053 XRefreshKeyboardMapping(ev);
1054 if(ev->request == MappingKeyboard)
1059 maprequest(XEvent *e) {
1060 static XWindowAttributes wa;
1061 XMapRequestEvent *ev = &e->xmaprequest;
1063 if(!XGetWindowAttributes(dpy, ev->window, &wa))
1065 if(wa.override_redirect)
1067 if(!getclient(ev->window))
1068 manage(ev->window, &wa);
1075 for(c = clients; c; c = c->next)
1077 resize(c, mox, moy, mow - 2 * c->bw, moh - 2 * c->bw, RESIZEHINTS);
1081 movemouse(Client *c) {
1082 int x1, y1, ocx, ocy, di, nx, ny;
1089 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1090 None, cursor[CurMove], CurrentTime) != GrabSuccess)
1092 XQueryPointer(dpy, root, &dummy, &dummy, &x1, &y1, &di, &di, &dui);
1094 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
1097 XUngrabPointer(dpy, CurrentTime);
1099 case ConfigureRequest:
1102 handler[ev.type](&ev);
1106 nx = ocx + (ev.xmotion.x - x1);
1107 ny = ocy + (ev.xmotion.y - y1);
1108 if(abs(wx - nx) < SNAP)
1110 else if(abs((wx + ww) - (nx + c->w + 2 * c->bw)) < SNAP)
1111 nx = wx + ww - c->w - 2 * c->bw;
1112 if(abs(wy - ny) < SNAP)
1114 else if(abs((wy + wh) - (ny + c->h + 2 * c->bw)) < SNAP)
1115 ny = wy + wh - c->h - 2 * c->bw;
1116 if(!c->isfloating && !lt->isfloating && (abs(nx - c->x) > SNAP || abs(ny - c->y) > SNAP))
1117 togglefloating(NULL);
1118 if((lt->isfloating) || c->isfloating)
1119 resize(c, nx, ny, c->w, c->h, False);
1126 nexttiled(Client *c) {
1127 for(; c && (c->isfloating || !isvisible(c)); c = c->next);
1132 propertynotify(XEvent *e) {
1135 XPropertyEvent *ev = &e->xproperty;
1137 if(ev->state == PropertyDelete)
1138 return; /* ignore */
1139 if((c = getclient(ev->window))) {
1142 case XA_WM_TRANSIENT_FOR:
1143 XGetTransientForHint(dpy, c->win, &trans);
1144 if(!c->isfloating && (c->isfloating = (getclient(trans) != NULL)))
1147 case XA_WM_NORMAL_HINTS:
1155 if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
1164 quit(const char *arg) {
1165 readin = running = False;
1169 reapply(const char *arg) {
1170 static Bool zerotags[LENGTH(tags)] = { 0 };
1173 for(c = clients; c; c = c->next) {
1174 memcpy(c->tags, zerotags, sizeof zerotags);
1181 resize(Client *c, int x, int y, int w, int h, Bool sizehints) {
1185 /* set minimum possible */
1191 /* temporarily remove base dimensions */
1195 /* adjust for aspect limits */
1196 if (c->minay > 0 && c->maxay > 0 && c->minax > 0 && c->maxax > 0) {
1197 if (w * c->maxay > h * c->maxax)
1198 w = h * c->maxax / c->maxay;
1199 else if (w * c->minay < h * c->minax)
1200 h = w * c->minay / c->minax;
1203 /* adjust for increment value */
1209 /* restore base dimensions */
1213 if(c->minw > 0 && w < c->minw)
1215 if(c->minh > 0 && h < c->minh)
1217 if(c->maxw > 0 && w > c->maxw)
1219 if(c->maxh > 0 && h > c->maxh)
1222 if(w <= 0 || h <= 0)
1225 x = sw - w - 2 * c->bw;
1227 y = sh - h - 2 * c->bw;
1228 if(x + w + 2 * c->bw < sx)
1230 if(y + h + 2 * c->bw < sy)
1232 if(c->x != x || c->y != y || c->w != w || c->h != h) {
1235 c->w = wc.width = w;
1236 c->h = wc.height = h;
1237 wc.border_width = c->bw;
1238 XConfigureWindow(dpy, c->win,
1239 CWX|CWY|CWWidth|CWHeight|CWBorderWidth, &wc);
1246 resizemouse(Client *c) {
1253 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1254 None, cursor[CurResize], CurrentTime) != GrabSuccess)
1256 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->bw - 1, c->h + c->bw - 1);
1258 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask , &ev);
1261 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0,
1262 c->w + c->bw - 1, c->h + c->bw - 1);
1263 XUngrabPointer(dpy, CurrentTime);
1264 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1266 case ConfigureRequest:
1269 handler[ev.type](&ev);
1273 if((nw = ev.xmotion.x - ocx - 2 * c->bw + 1) <= 0)
1275 if((nh = ev.xmotion.y - ocy - 2 * c->bw + 1) <= 0)
1277 if(!c->isfloating && !lt->isfloating && (abs(nw - c->w) > SNAP || abs(nh - c->h) > SNAP))
1278 togglefloating(NULL);
1279 if((lt->isfloating) || c->isfloating)
1280 resize(c, c->x, c->y, nw, nh, True);
1295 if(sel->isfloating || lt->isfloating)
1296 XRaiseWindow(dpy, sel->win);
1297 if(!lt->isfloating) {
1298 wc.stack_mode = Below;
1299 wc.sibling = barwin;
1300 if(!sel->isfloating) {
1301 XConfigureWindow(dpy, sel->win, CWSibling|CWStackMode, &wc);
1302 wc.sibling = sel->win;
1304 for(c = nexttiled(clients); c; c = nexttiled(c->next)) {
1307 XConfigureWindow(dpy, c->win, CWSibling|CWStackMode, &wc);
1308 wc.sibling = c->win;
1312 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1318 char sbuf[sizeof stext];
1321 unsigned int len, offset;
1324 /* main event loop, also reads status text from stdin */
1326 xfd = ConnectionNumber(dpy);
1329 len = sizeof stext - 1;
1330 sbuf[len] = stext[len] = '\0'; /* 0-terminator is never touched */
1334 FD_SET(STDIN_FILENO, &rd);
1336 if(select(xfd + 1, &rd, NULL, NULL, NULL) == -1) {
1339 eprint("select failed\n");
1341 if(FD_ISSET(STDIN_FILENO, &rd)) {
1342 switch((r = read(STDIN_FILENO, sbuf + offset, len - offset))) {
1344 strncpy(stext, strerror(errno), len);
1348 strncpy(stext, "EOF", 4);
1352 for(p = sbuf + offset; r > 0; p++, r--, offset++)
1353 if(*p == '\n' || *p == '\0') {
1355 strncpy(stext, sbuf, len);
1356 p += r - 1; /* p is sbuf + offset + r - 1 */
1357 for(r = 0; *(p - r) && *(p - r) != '\n'; r++);
1360 memmove(sbuf, p - r + 1, r);
1367 while(XPending(dpy)) {
1368 XNextEvent(dpy, &ev);
1369 if(handler[ev.type])
1370 (handler[ev.type])(&ev); /* call handler */
1377 unsigned int i, num;
1378 Window *wins, d1, d2;
1379 XWindowAttributes wa;
1382 if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1383 for(i = 0; i < num; i++) {
1384 if(!XGetWindowAttributes(dpy, wins[i], &wa)
1385 || wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1387 if(wa.map_state == IsViewable || getstate(wins[i]) == IconicState)
1388 manage(wins[i], &wa);
1390 for(i = 0; i < num; i++) { /* now the transients */
1391 if(!XGetWindowAttributes(dpy, wins[i], &wa))
1393 if(XGetTransientForHint(dpy, wins[i], &d1)
1394 && (wa.map_state == IsViewable || getstate(wins[i]) == IconicState))
1395 manage(wins[i], &wa);
1403 setclientstate(Client *c, long state) {
1404 long data[] = {state, None};
1406 XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1407 PropModeReplace, (unsigned char *)data, 2);
1411 setgeom(const char *arg) {
1414 for(i = 0; arg && i < LENGTH(geoms); i++)
1415 if(!strcmp(geoms[i].symbol, arg))
1417 if(i == LENGTH(geoms))
1426 setlayout(const char *arg) {
1427 static Layout *revert = 0;
1432 for(i = 0; i < LENGTH(layouts); i++)
1433 if(!strcmp(arg, layouts[i].symbol))
1435 if(i == LENGTH(layouts))
1437 if(revert && &layouts[i] == lt)
1452 XSetWindowAttributes wa;
1455 screen = DefaultScreen(dpy);
1456 root = RootWindow(dpy, screen);
1459 /* apply default geometry */
1462 sw = DisplayWidth(dpy, screen);
1463 sh = DisplayHeight(dpy, screen);
1464 bh = dc.font.height + 2;
1469 wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1470 wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1471 wmatom[WMName] = XInternAtom(dpy, "WM_NAME", False);
1472 wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1473 netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1474 netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1477 wa.cursor = cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1478 cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1479 cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1481 /* init appearance */
1482 dc.norm[ColBorder] = getcolor(NORMBORDERCOLOR);
1483 dc.norm[ColBG] = getcolor(NORMBGCOLOR);
1484 dc.norm[ColFG] = getcolor(NORMFGCOLOR);
1485 dc.sel[ColBorder] = getcolor(SELBORDERCOLOR);
1486 dc.sel[ColBG] = getcolor(SELBGCOLOR);
1487 dc.sel[ColFG] = getcolor(SELFGCOLOR);
1490 dc.drawable = XCreatePixmap(dpy, root, DisplayWidth(dpy, screen), bh, DefaultDepth(dpy, screen));
1491 dc.gc = XCreateGC(dpy, root, 0, 0);
1492 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
1494 XSetFont(dpy, dc.gc, dc.font.xfont->fid);
1497 seltags = emallocz(TAGSZ);
1498 prevtags = emallocz(TAGSZ);
1499 seltags[0] = prevtags[0] = True;
1505 for(blw = i = 0; i < LENGTH(layouts); i++) {
1506 w = textw(layouts[i].symbol);
1510 for(bgw = i = 0; i < LENGTH(geoms); i++) {
1511 w = textw(geoms[i].symbol);
1516 wa.override_redirect = 1;
1517 wa.background_pixmap = ParentRelative;
1518 wa.event_mask = ButtonPressMask|ExposureMask;
1520 barwin = XCreateWindow(dpy, root, bx, by, bw, bh, 0, DefaultDepth(dpy, screen),
1521 CopyFromParent, DefaultVisual(dpy, screen),
1522 CWOverrideRedirect|CWBackPixmap|CWEventMask, &wa);
1523 XDefineCursor(dpy, barwin, cursor[CurNormal]);
1524 XMapRaised(dpy, barwin);
1525 strcpy(stext, "dwm-"VERSION);
1528 /* EWMH support per view */
1529 XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1530 PropModeReplace, (unsigned char *) netatom, NetLast);
1532 /* select for events */
1533 wa.event_mask = SubstructureRedirectMask|SubstructureNotifyMask
1534 |EnterWindowMask|LeaveWindowMask|StructureNotifyMask;
1535 XChangeWindowAttributes(dpy, root, CWEventMask|CWCursor, &wa);
1536 XSelectInput(dpy, root, wa.event_mask);
1544 spawn(const char *arg) {
1545 static char *shell = NULL;
1547 if(!shell && !(shell = getenv("SHELL")))
1551 /* The double-fork construct avoids zombie processes and keeps the code
1552 * clean from stupid signal handlers. */
1556 close(ConnectionNumber(dpy));
1558 execl(shell, shell, "-c", arg, (char *)NULL);
1559 fprintf(stderr, "dwm: execl '%s -c %s'", shell, arg);
1568 tag(const char *arg) {
1573 for(i = 0; i < LENGTH(tags); i++)
1574 sel->tags[i] = (NULL == arg);
1575 sel->tags[idxoftag(arg)] = True;
1580 textnw(const char *text, unsigned int len) {
1584 XmbTextExtents(dc.font.set, text, len, NULL, &r);
1587 return XTextWidth(dc.font.xfont, text, len);
1591 textw(const char *text) {
1592 return textnw(text, strlen(text)) + dc.font.height;
1598 unsigned int i, n = counttiled();
1612 for(i = 0, c = nexttiled(c->next); c; c = nexttiled(c->next), i++) {
1613 if(i + 1 == n) /* remainder */
1614 tileresize(c, x, ty, (tx + tw) - x - 2 * c->bw, th - 2 * c->bw);
1616 tileresize(c, x, ty, w - 2 * c->bw, th - 2 * c->bw);
1618 x = c->x + c->w + 2 * c->bw;
1623 tilemaster(unsigned int n) {
1624 Client *c = nexttiled(clients);
1627 tileresize(c, mox, moy, mow - 2 * c->bw, moh - 2 * c->bw);
1629 tileresize(c, mx, my, mw - 2 * c->bw, mh - 2 * c->bw);
1634 tileresize(Client *c, int x, int y, int w, int h) {
1635 resize(c, x, y, w, h, RESIZEHINTS);
1636 if((RESIZEHINTS) && ((c->h < bh) || (c->h > h) || (c->w < bh) || (c->w > w)))
1637 /* client doesn't accept size constraints */
1638 resize(c, x, y, w, h, False);
1644 unsigned int i, n = counttiled();
1658 for(i = 0, c = nexttiled(c->next); c; c = nexttiled(c->next), i++) {
1659 if(i + 1 == n) /* remainder */
1660 tileresize(c, tx, y, tw - 2 * c->bw, (ty + th) - y - 2 * c->bw);
1662 tileresize(c, tx, y, tw - 2 * c->bw, h - 2 * c->bw);
1664 y = c->y + c->h + 2 * c->bw;
1669 togglefloating(const char *arg) {
1672 sel->isfloating = !sel->isfloating;
1674 resize(sel, sel->x, sel->y, sel->w, sel->h, True);
1679 toggletag(const char *arg) {
1685 sel->tags[i] = !sel->tags[i];
1686 for(j = 0; j < LENGTH(tags) && !sel->tags[j]; j++);
1687 if(j == LENGTH(tags))
1688 sel->tags[i] = True; /* at least one tag must be enabled */
1693 toggleview(const char *arg) {
1697 seltags[i] = !seltags[i];
1698 for(j = 0; j < LENGTH(tags) && !seltags[j]; j++);
1699 if(j == LENGTH(tags))
1700 seltags[i] = True; /* at least one tag must be viewed */
1708 XMoveWindow(dpy, c->win, c->x, c->y);
1709 c->isbanned = False;
1713 unmanage(Client *c) {
1716 wc.border_width = c->oldbw;
1717 /* The server grab construct avoids race conditions. */
1719 XSetErrorHandler(xerrordummy);
1720 XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
1725 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1726 setclientstate(c, WithdrawnState);
1730 XSetErrorHandler(xerror);
1736 unmapnotify(XEvent *e) {
1738 XUnmapEvent *ev = &e->xunmap;
1740 if((c = getclient(ev->window)))
1745 updatebarpos(void) {
1747 if(dc.drawable != 0)
1748 XFreePixmap(dpy, dc.drawable);
1749 dc.drawable = XCreatePixmap(dpy, root, bw, bh, DefaultDepth(dpy, screen));
1750 XMoveResizeWindow(dpy, barwin, bx, by, bw, bh);
1754 updatesizehints(Client *c) {
1758 if(!XGetWMNormalHints(dpy, c->win, &size, &msize) || !size.flags)
1760 c->flags = size.flags;
1761 if(c->flags & PBaseSize) {
1762 c->basew = size.base_width;
1763 c->baseh = size.base_height;
1765 else if(c->flags & PMinSize) {
1766 c->basew = size.min_width;
1767 c->baseh = size.min_height;
1770 c->basew = c->baseh = 0;
1771 if(c->flags & PResizeInc) {
1772 c->incw = size.width_inc;
1773 c->inch = size.height_inc;
1776 c->incw = c->inch = 0;
1777 if(c->flags & PMaxSize) {
1778 c->maxw = size.max_width;
1779 c->maxh = size.max_height;
1782 c->maxw = c->maxh = 0;
1783 if(c->flags & PMinSize) {
1784 c->minw = size.min_width;
1785 c->minh = size.min_height;
1787 else if(c->flags & PBaseSize) {
1788 c->minw = size.base_width;
1789 c->minh = size.base_height;
1792 c->minw = c->minh = 0;
1793 if(c->flags & PAspect) {
1794 c->minax = size.min_aspect.x;
1795 c->maxax = size.max_aspect.x;
1796 c->minay = size.min_aspect.y;
1797 c->maxay = size.max_aspect.y;
1800 c->minax = c->maxax = c->minay = c->maxay = 0;
1801 c->isfixed = (c->maxw && c->minw && c->maxh && c->minh
1802 && c->maxw == c->minw && c->maxh == c->minh);
1806 updatetitle(Client *c) {
1807 if(!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
1808 gettextprop(c->win, wmatom[WMName], c->name, sizeof c->name);
1812 updatewmhints(Client *c) {
1815 if((wmh = XGetWMHints(dpy, c->win))) {
1817 sel->isurgent = False;
1819 c->isurgent = (wmh->flags & XUrgencyHint) ? True : False;
1826 view(const char *arg) {
1829 for(i = 0; i < LENGTH(tags); i++)
1830 tmp[i] = (NULL == arg);
1831 tmp[idxoftag(arg)] = True;
1833 if(memcmp(seltags, tmp, TAGSZ) != 0) {
1834 memcpy(prevtags, seltags, TAGSZ);
1835 memcpy(seltags, tmp, TAGSZ);
1841 viewprevtag(const char *arg) {
1843 memcpy(tmp, seltags, TAGSZ);
1844 memcpy(seltags, prevtags, TAGSZ);
1845 memcpy(prevtags, tmp, TAGSZ);
1849 /* There's no way to check accesses to destroyed windows, thus those cases are
1850 * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
1851 * default error handler, which may call exit. */
1853 xerror(Display *dpy, XErrorEvent *ee) {
1854 if(ee->error_code == BadWindow
1855 || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1856 || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1857 || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1858 || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1859 || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1860 || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1861 || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1863 fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1864 ee->request_code, ee->error_code);
1865 return xerrorxlib(dpy, ee); /* may call exit */
1869 xerrordummy(Display *dpy, XErrorEvent *ee) {
1873 /* Startup Error handler to check if another window manager
1874 * is already running. */
1876 xerrorstart(Display *dpy, XErrorEvent *ee) {
1882 zoom(const char *arg) {
1885 if(!sel || lt->isfloating || sel->isfloating)
1887 if(c == nexttiled(clients))
1888 if(!(c = nexttiled(c->next)))
1897 main(int argc, char *argv[]) {
1898 if(argc == 2 && !strcmp("-v", argv[1]))
1899 eprint("dwm-"VERSION", © 2006-2008 dwm engineers, see LICENSE for details\n");
1901 eprint("usage: dwm [-v]\n");
1903 setlocale(LC_CTYPE, "");
1904 if(!(dpy = XOpenDisplay(0)))
1905 eprint("dwm: cannot open display\n");