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);
522 drawtext(geom->symbol, dc.norm, False);
525 for(c = stack; c && !isvisible(c); c = c->snext);
526 for(i = 0; i < LENGTH(tags); i++) {
527 dc.w = textw(tags[i]);
529 drawtext(tags[i], dc.sel, isurgent(i));
530 drawsquare(c && c->tags[i], isoccupied(i), isurgent(i), dc.sel);
533 drawtext(tags[i], dc.norm, isurgent(i));
534 drawsquare(c && c->tags[i], isoccupied(i), isurgent(i), dc.norm);
540 drawtext(lt->symbol, dc.norm, False);
551 drawtext(stext, dc.norm, False);
552 if((dc.w = dc.x - x) > bh) {
555 drawtext(c->name, dc.sel, False);
556 drawsquare(False, c->isfloating, False, dc.sel);
559 drawtext(NULL, dc.norm, False);
561 XCopyArea(dpy, dc.drawable, barwin, dc.gc, 0, 0, bw, bh, 0, 0);
566 drawsquare(Bool filled, Bool empty, Bool invert, unsigned long col[ColLast]) {
569 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
571 gcv.foreground = col[invert ? ColBG : ColFG];
572 XChangeGC(dpy, dc.gc, GCForeground, &gcv);
573 x = (dc.font.ascent + dc.font.descent + 2) / 4;
577 r.width = r.height = x + 1;
578 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
581 r.width = r.height = x;
582 XDrawRectangles(dpy, dc.drawable, dc.gc, &r, 1);
587 drawtext(const char *text, unsigned long col[ColLast], Bool invert) {
589 unsigned int len, olen;
590 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
592 XSetForeground(dpy, dc.gc, col[invert ? ColFG : ColBG]);
593 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
597 olen = len = strlen(text);
598 if(len >= sizeof buf)
599 len = sizeof buf - 1;
600 memcpy(buf, text, len);
602 h = dc.font.ascent + dc.font.descent;
603 y = dc.y + (dc.h / 2) - (h / 2) + dc.font.ascent;
605 /* shorten text if necessary */
606 while(len && (w = textnw(buf, len)) > dc.w - h)
617 return; /* too long */
618 XSetForeground(dpy, dc.gc, col[invert ? ColBG : ColFG]);
620 XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
622 XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
626 emallocz(unsigned int size) {
627 void *res = calloc(1, size);
630 eprint("fatal: could not malloc() %u bytes\n", size);
635 enternotify(XEvent *e) {
637 XCrossingEvent *ev = &e->xcrossing;
639 if((ev->mode != NotifyNormal || ev->detail == NotifyInferior) && ev->window != root)
641 if((c = getclient(ev->window)))
648 eprint(const char *errstr, ...) {
651 va_start(ap, errstr);
652 vfprintf(stderr, errstr, ap);
659 XExposeEvent *ev = &e->xexpose;
661 if(ev->count == 0 && (ev->window == barwin))
666 floating(void) { /* default floating layout */
669 for(c = clients; c; c = c->next)
671 resize(c, c->x, c->y, c->w, c->h, True);
676 if(!c || (c && !isvisible(c)))
677 for(c = stack; c && !isvisible(c); c = c->snext);
678 if(sel && sel != c) {
679 grabbuttons(sel, False);
680 XSetWindowBorder(dpy, sel->win, dc.norm[ColBorder]);
685 grabbuttons(c, True);
689 XSetWindowBorder(dpy, c->win, dc.sel[ColBorder]);
690 XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
693 XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
698 focusin(XEvent *e) { /* there are some broken focus acquiring clients */
699 XFocusChangeEvent *ev = &e->xfocus;
701 if(sel && ev->window != sel->win)
702 XSetInputFocus(dpy, sel->win, RevertToPointerRoot, CurrentTime);
706 focusnext(const char *arg) {
711 for(c = sel->next; c && !isvisible(c); c = c->next);
713 for(c = clients; c && !isvisible(c); c = c->next);
721 focusprev(const char *arg) {
726 for(c = sel->prev; c && !isvisible(c); c = c->prev);
728 for(c = clients; c && c->next; c = c->next);
729 for(; c && !isvisible(c); c = c->prev);
738 getclient(Window w) {
741 for(c = clients; c && c->win != w; c = c->next);
746 getcolor(const char *colstr) {
747 Colormap cmap = DefaultColormap(dpy, screen);
750 if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
751 eprint("error, cannot allocate color '%s'\n", colstr);
759 unsigned char *p = NULL;
760 unsigned long n, extra;
763 status = XGetWindowProperty(dpy, w, wmatom[WMState], 0L, 2L, False, wmatom[WMState],
764 &real, &format, &n, &extra, (unsigned char **)&p);
765 if(status != Success)
774 gettextprop(Window w, Atom atom, char *text, unsigned int size) {
779 if(!text || size == 0)
782 XGetTextProperty(dpy, w, &name, atom);
785 if(name.encoding == XA_STRING)
786 strncpy(text, (char *)name.value, size - 1);
788 if(XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success
790 strncpy(text, *list, size - 1);
791 XFreeStringList(list);
794 text[size - 1] = '\0';
800 grabbuttons(Client *c, Bool focused) {
801 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
804 XGrabButton(dpy, Button1, MODKEY, c->win, False, BUTTONMASK,
805 GrabModeAsync, GrabModeSync, None, None);
806 XGrabButton(dpy, Button1, MODKEY|LockMask, c->win, False, BUTTONMASK,
807 GrabModeAsync, GrabModeSync, None, None);
808 XGrabButton(dpy, Button1, MODKEY|numlockmask, c->win, False, BUTTONMASK,
809 GrabModeAsync, GrabModeSync, None, None);
810 XGrabButton(dpy, Button1, MODKEY|numlockmask|LockMask, c->win, False, BUTTONMASK,
811 GrabModeAsync, GrabModeSync, None, None);
813 XGrabButton(dpy, Button2, MODKEY, c->win, False, BUTTONMASK,
814 GrabModeAsync, GrabModeSync, None, None);
815 XGrabButton(dpy, Button2, MODKEY|LockMask, c->win, False, BUTTONMASK,
816 GrabModeAsync, GrabModeSync, None, None);
817 XGrabButton(dpy, Button2, MODKEY|numlockmask, c->win, False, BUTTONMASK,
818 GrabModeAsync, GrabModeSync, None, None);
819 XGrabButton(dpy, Button2, MODKEY|numlockmask|LockMask, c->win, False, BUTTONMASK,
820 GrabModeAsync, GrabModeSync, None, None);
822 XGrabButton(dpy, Button3, MODKEY, c->win, False, BUTTONMASK,
823 GrabModeAsync, GrabModeSync, None, None);
824 XGrabButton(dpy, Button3, MODKEY|LockMask, c->win, False, BUTTONMASK,
825 GrabModeAsync, GrabModeSync, None, None);
826 XGrabButton(dpy, Button3, MODKEY|numlockmask, c->win, False, BUTTONMASK,
827 GrabModeAsync, GrabModeSync, None, None);
828 XGrabButton(dpy, Button3, MODKEY|numlockmask|LockMask, c->win, False, BUTTONMASK,
829 GrabModeAsync, GrabModeSync, None, None);
832 XGrabButton(dpy, AnyButton, AnyModifier, c->win, False, BUTTONMASK,
833 GrabModeAsync, GrabModeSync, None, None);
840 XModifierKeymap *modmap;
842 /* init modifier map */
843 modmap = XGetModifierMapping(dpy);
844 for(i = 0; i < 8; i++)
845 for(j = 0; j < modmap->max_keypermod; j++) {
846 if(modmap->modifiermap[i * modmap->max_keypermod + j] == XKeysymToKeycode(dpy, XK_Num_Lock))
847 numlockmask = (1 << i);
849 XFreeModifiermap(modmap);
851 XUngrabKey(dpy, AnyKey, AnyModifier, root);
852 for(i = 0; i < LENGTH(keys); i++) {
853 code = XKeysymToKeycode(dpy, keys[i].keysym);
854 XGrabKey(dpy, code, keys[i].mod, root, True,
855 GrabModeAsync, GrabModeAsync);
856 XGrabKey(dpy, code, keys[i].mod|LockMask, root, True,
857 GrabModeAsync, GrabModeAsync);
858 XGrabKey(dpy, code, keys[i].mod|numlockmask, root, True,
859 GrabModeAsync, GrabModeAsync);
860 XGrabKey(dpy, code, keys[i].mod|numlockmask|LockMask, root, True,
861 GrabModeAsync, GrabModeAsync);
866 idxoftag(const char *t) {
869 for(i = 0; (i < LENGTH(tags)) && t && strcmp(tags[i], t); i++);
870 return (i < LENGTH(tags)) ? i : 0;
874 initfont(const char *fontstr) {
875 char *def, **missing;
880 XFreeFontSet(dpy, dc.font.set);
881 dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
884 fprintf(stderr, "dwm: missing fontset: %s\n", missing[n]);
885 XFreeStringList(missing);
888 XFontSetExtents *font_extents;
889 XFontStruct **xfonts;
891 dc.font.ascent = dc.font.descent = 0;
892 font_extents = XExtentsOfFontSet(dc.font.set);
893 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
894 for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
895 if(dc.font.ascent < (*xfonts)->ascent)
896 dc.font.ascent = (*xfonts)->ascent;
897 if(dc.font.descent < (*xfonts)->descent)
898 dc.font.descent = (*xfonts)->descent;
904 XFreeFont(dpy, dc.font.xfont);
905 dc.font.xfont = NULL;
906 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr))
907 && !(dc.font.xfont = XLoadQueryFont(dpy, "fixed")))
908 eprint("error, cannot load font: '%s'\n", fontstr);
909 dc.font.ascent = dc.font.xfont->ascent;
910 dc.font.descent = dc.font.xfont->descent;
912 dc.font.height = dc.font.ascent + dc.font.descent;
916 isoccupied(unsigned int t) {
919 for(c = clients; c; c = c->next)
926 isprotodel(Client *c) {
931 if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
932 for(i = 0; !ret && i < n; i++)
933 if(protocols[i] == wmatom[WMDelete])
941 isurgent(unsigned int t) {
944 for(c = clients; c; c = c->next)
945 if(c->isurgent && c->tags[t])
951 isvisible(Client *c) {
954 for(i = 0; i < LENGTH(tags); i++)
955 if(c->tags[i] && seltags[i])
961 keypress(XEvent *e) {
967 keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
968 for(i = 0; i < LENGTH(keys); i++)
969 if(keysym == keys[i].keysym
970 && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state))
973 keys[i].func(keys[i].arg);
978 killclient(const char *arg) {
983 if(isprotodel(sel)) {
984 ev.type = ClientMessage;
985 ev.xclient.window = sel->win;
986 ev.xclient.message_type = wmatom[WMProtocols];
987 ev.xclient.format = 32;
988 ev.xclient.data.l[0] = wmatom[WMDelete];
989 ev.xclient.data.l[1] = CurrentTime;
990 XSendEvent(dpy, sel->win, False, NoEventMask, &ev);
993 XKillClient(dpy, sel->win);
997 manage(Window w, XWindowAttributes *wa) {
998 Client *c, *t = NULL;
1003 c = emallocz(sizeof(Client));
1004 c->tags = emallocz(TAGSZ);
1012 c->oldbw = wa->border_width;
1013 if(c->w == sw && c->h == sh) {
1016 c->bw = wa->border_width;
1019 if(c->x + c->w + 2 * c->bw > wx + ww)
1020 c->x = wx + ww - c->w - 2 * c->bw;
1021 if(c->y + c->h + 2 * c->bw > wy + wh)
1022 c->y = wy + wh - c->h - 2 * c->bw;
1030 wc.border_width = c->bw;
1031 XConfigureWindow(dpy, w, CWBorderWidth, &wc);
1032 XSetWindowBorder(dpy, w, dc.norm[ColBorder]);
1033 configure(c); /* propagates border_width, if size doesn't change */
1035 XSelectInput(dpy, w, EnterWindowMask|FocusChangeMask|PropertyChangeMask|StructureNotifyMask);
1036 grabbuttons(c, False);
1038 if((rettrans = XGetTransientForHint(dpy, w, &trans) == Success))
1039 for(t = clients; t && t->win != trans; t = t->next);
1041 memcpy(c->tags, t->tags, TAGSZ);
1045 c->isfloating = (rettrans == Success) || c->isfixed;
1048 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h); /* some windows require this */
1050 XMapWindow(dpy, c->win);
1051 setclientstate(c, NormalState);
1056 mappingnotify(XEvent *e) {
1057 XMappingEvent *ev = &e->xmapping;
1059 XRefreshKeyboardMapping(ev);
1060 if(ev->request == MappingKeyboard)
1065 maprequest(XEvent *e) {
1066 static XWindowAttributes wa;
1067 XMapRequestEvent *ev = &e->xmaprequest;
1069 if(!XGetWindowAttributes(dpy, ev->window, &wa))
1071 if(wa.override_redirect)
1073 if(!getclient(ev->window))
1074 manage(ev->window, &wa);
1081 for(c = clients; c; c = c->next)
1083 resize(c, mox, moy, mow - 2 * c->bw, moh - 2 * c->bw, RESIZEHINTS);
1087 movemouse(Client *c) {
1088 int x1, y1, ocx, ocy, di, nx, ny;
1095 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1096 None, cursor[CurMove], CurrentTime) != GrabSuccess)
1098 XQueryPointer(dpy, root, &dummy, &dummy, &x1, &y1, &di, &di, &dui);
1100 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
1103 XUngrabPointer(dpy, CurrentTime);
1105 case ConfigureRequest:
1108 handler[ev.type](&ev);
1112 nx = ocx + (ev.xmotion.x - x1);
1113 ny = ocy + (ev.xmotion.y - y1);
1114 if(abs(wx - nx) < SNAP)
1116 else if(abs((wx + ww) - (nx + c->w + 2 * c->bw)) < SNAP)
1117 nx = wx + ww - c->w - 2 * c->bw;
1118 if(abs(wy - ny) < SNAP)
1120 else if(abs((wy + wh) - (ny + c->h + 2 * c->bw)) < SNAP)
1121 ny = wy + wh - c->h - 2 * c->bw;
1122 if(!c->isfloating && !lt->isfloating && (abs(nx - c->x) > SNAP || abs(ny - c->y) > SNAP))
1123 togglefloating(NULL);
1124 if((lt->isfloating) || c->isfloating)
1125 resize(c, nx, ny, c->w, c->h, False);
1132 nexttiled(Client *c) {
1133 for(; c && (c->isfloating || !isvisible(c)); c = c->next);
1138 propertynotify(XEvent *e) {
1141 XPropertyEvent *ev = &e->xproperty;
1143 if(ev->state == PropertyDelete)
1144 return; /* ignore */
1145 if((c = getclient(ev->window))) {
1148 case XA_WM_TRANSIENT_FOR:
1149 XGetTransientForHint(dpy, c->win, &trans);
1150 if(!c->isfloating && (c->isfloating = (getclient(trans) != NULL)))
1153 case XA_WM_NORMAL_HINTS:
1161 if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
1170 quit(const char *arg) {
1171 readin = running = False;
1175 reapply(const char *arg) {
1176 static Bool zerotags[LENGTH(tags)] = { 0 };
1179 for(c = clients; c; c = c->next) {
1180 memcpy(c->tags, zerotags, sizeof zerotags);
1187 resize(Client *c, int x, int y, int w, int h, Bool sizehints) {
1191 /* set minimum possible */
1197 /* temporarily remove base dimensions */
1201 /* adjust for aspect limits */
1202 if (c->minay > 0 && c->maxay > 0 && c->minax > 0 && c->maxax > 0) {
1203 if (w * c->maxay > h * c->maxax)
1204 w = h * c->maxax / c->maxay;
1205 else if (w * c->minay < h * c->minax)
1206 h = w * c->minay / c->minax;
1209 /* adjust for increment value */
1215 /* restore base dimensions */
1219 if(c->minw > 0 && w < c->minw)
1221 if(c->minh > 0 && h < c->minh)
1223 if(c->maxw > 0 && w > c->maxw)
1225 if(c->maxh > 0 && h > c->maxh)
1228 if(w <= 0 || h <= 0)
1231 x = sw - w - 2 * c->bw;
1233 y = sh - h - 2 * c->bw;
1234 if(x + w + 2 * c->bw < sx)
1236 if(y + h + 2 * c->bw < sy)
1238 if(c->x != x || c->y != y || c->w != w || c->h != h) {
1241 c->w = wc.width = w;
1242 c->h = wc.height = h;
1243 wc.border_width = c->bw;
1244 XConfigureWindow(dpy, c->win,
1245 CWX|CWY|CWWidth|CWHeight|CWBorderWidth, &wc);
1252 resizemouse(Client *c) {
1259 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1260 None, cursor[CurResize], CurrentTime) != GrabSuccess)
1262 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->bw - 1, c->h + c->bw - 1);
1264 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask , &ev);
1267 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0,
1268 c->w + c->bw - 1, c->h + c->bw - 1);
1269 XUngrabPointer(dpy, CurrentTime);
1270 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1272 case ConfigureRequest:
1275 handler[ev.type](&ev);
1279 if((nw = ev.xmotion.x - ocx - 2 * c->bw + 1) <= 0)
1281 if((nh = ev.xmotion.y - ocy - 2 * c->bw + 1) <= 0)
1283 if(!c->isfloating && !lt->isfloating && (abs(nw - c->w) > SNAP || abs(nh - c->h) > SNAP))
1284 togglefloating(NULL);
1285 if((lt->isfloating) || c->isfloating)
1286 resize(c, c->x, c->y, nw, nh, True);
1301 if(sel->isfloating || lt->isfloating)
1302 XRaiseWindow(dpy, sel->win);
1303 if(!lt->isfloating) {
1304 wc.stack_mode = Below;
1305 wc.sibling = barwin;
1306 if(!sel->isfloating) {
1307 XConfigureWindow(dpy, sel->win, CWSibling|CWStackMode, &wc);
1308 wc.sibling = sel->win;
1310 for(c = nexttiled(clients); c; c = nexttiled(c->next)) {
1313 XConfigureWindow(dpy, c->win, CWSibling|CWStackMode, &wc);
1314 wc.sibling = c->win;
1318 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1324 char sbuf[sizeof stext];
1327 unsigned int len, offset;
1330 /* main event loop, also reads status text from stdin */
1332 xfd = ConnectionNumber(dpy);
1335 len = sizeof stext - 1;
1336 sbuf[len] = stext[len] = '\0'; /* 0-terminator is never touched */
1340 FD_SET(STDIN_FILENO, &rd);
1342 if(select(xfd + 1, &rd, NULL, NULL, NULL) == -1) {
1345 eprint("select failed\n");
1347 if(FD_ISSET(STDIN_FILENO, &rd)) {
1348 switch((r = read(STDIN_FILENO, sbuf + offset, len - offset))) {
1350 strncpy(stext, strerror(errno), len);
1354 strncpy(stext, "EOF", 4);
1358 for(p = sbuf + offset; r > 0; p++, r--, offset++)
1359 if(*p == '\n' || *p == '\0') {
1361 strncpy(stext, sbuf, len);
1362 p += r - 1; /* p is sbuf + offset + r - 1 */
1363 for(r = 0; *(p - r) && *(p - r) != '\n'; r++);
1366 memmove(sbuf, p - r + 1, r);
1373 while(XPending(dpy)) {
1374 XNextEvent(dpy, &ev);
1375 if(handler[ev.type])
1376 (handler[ev.type])(&ev); /* call handler */
1383 unsigned int i, num;
1384 Window *wins, d1, d2;
1385 XWindowAttributes wa;
1388 if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1389 for(i = 0; i < num; i++) {
1390 if(!XGetWindowAttributes(dpy, wins[i], &wa)
1391 || wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1393 if(wa.map_state == IsViewable || getstate(wins[i]) == IconicState)
1394 manage(wins[i], &wa);
1396 for(i = 0; i < num; i++) { /* now the transients */
1397 if(!XGetWindowAttributes(dpy, wins[i], &wa))
1399 if(XGetTransientForHint(dpy, wins[i], &d1)
1400 && (wa.map_state == IsViewable || getstate(wins[i]) == IconicState))
1401 manage(wins[i], &wa);
1409 setclientstate(Client *c, long state) {
1410 long data[] = {state, None};
1412 XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1413 PropModeReplace, (unsigned char *)data, 2);
1417 setgeom(const char *arg) {
1420 for(i = 0; arg && i < LENGTH(geoms); i++)
1421 if(!strcmp(geoms[i].symbol, arg))
1423 if(i == LENGTH(geoms))
1432 setlayout(const char *arg) {
1433 static Layout *revert = 0;
1438 for(i = 0; i < LENGTH(layouts); i++)
1439 if(!strcmp(arg, layouts[i].symbol))
1441 if(i == LENGTH(layouts))
1443 if(revert && &layouts[i] == lt)
1458 XSetWindowAttributes wa;
1461 screen = DefaultScreen(dpy);
1462 root = RootWindow(dpy, screen);
1465 /* apply default geometry */
1468 sw = DisplayWidth(dpy, screen);
1469 sh = DisplayHeight(dpy, screen);
1470 bh = dc.font.height + 2;
1475 wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1476 wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1477 wmatom[WMName] = XInternAtom(dpy, "WM_NAME", False);
1478 wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1479 netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1480 netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1483 wa.cursor = cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1484 cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1485 cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1487 /* init appearance */
1488 dc.norm[ColBorder] = getcolor(NORMBORDERCOLOR);
1489 dc.norm[ColBG] = getcolor(NORMBGCOLOR);
1490 dc.norm[ColFG] = getcolor(NORMFGCOLOR);
1491 dc.sel[ColBorder] = getcolor(SELBORDERCOLOR);
1492 dc.sel[ColBG] = getcolor(SELBGCOLOR);
1493 dc.sel[ColFG] = getcolor(SELFGCOLOR);
1496 dc.drawable = XCreatePixmap(dpy, root, DisplayWidth(dpy, screen), bh, DefaultDepth(dpy, screen));
1497 dc.gc = XCreateGC(dpy, root, 0, 0);
1498 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
1500 XSetFont(dpy, dc.gc, dc.font.xfont->fid);
1503 seltags = emallocz(TAGSZ);
1504 prevtags = emallocz(TAGSZ);
1505 seltags[0] = prevtags[0] = True;
1511 for(blw = i = 0; LENGTH(layouts) > 1 && i < LENGTH(layouts); i++) {
1512 w = textw(layouts[i].symbol);
1516 for(bgw = i = 0; LENGTH(geoms) > 1 && i < LENGTH(geoms); i++) {
1517 w = textw(geoms[i].symbol);
1522 wa.override_redirect = 1;
1523 wa.background_pixmap = ParentRelative;
1524 wa.event_mask = ButtonPressMask|ExposureMask;
1526 barwin = XCreateWindow(dpy, root, bx, by, bw, bh, 0, DefaultDepth(dpy, screen),
1527 CopyFromParent, DefaultVisual(dpy, screen),
1528 CWOverrideRedirect|CWBackPixmap|CWEventMask, &wa);
1529 XDefineCursor(dpy, barwin, cursor[CurNormal]);
1530 XMapRaised(dpy, barwin);
1531 strcpy(stext, "dwm-"VERSION);
1534 /* EWMH support per view */
1535 XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1536 PropModeReplace, (unsigned char *) netatom, NetLast);
1538 /* select for events */
1539 wa.event_mask = SubstructureRedirectMask|SubstructureNotifyMask
1540 |EnterWindowMask|LeaveWindowMask|StructureNotifyMask;
1541 XChangeWindowAttributes(dpy, root, CWEventMask|CWCursor, &wa);
1542 XSelectInput(dpy, root, wa.event_mask);
1550 spawn(const char *arg) {
1551 static char *shell = NULL;
1553 if(!shell && !(shell = getenv("SHELL")))
1557 /* The double-fork construct avoids zombie processes and keeps the code
1558 * clean from stupid signal handlers. */
1562 close(ConnectionNumber(dpy));
1564 execl(shell, shell, "-c", arg, (char *)NULL);
1565 fprintf(stderr, "dwm: execl '%s -c %s'", shell, arg);
1574 tag(const char *arg) {
1579 for(i = 0; i < LENGTH(tags); i++)
1580 sel->tags[i] = (NULL == arg);
1581 sel->tags[idxoftag(arg)] = True;
1586 textnw(const char *text, unsigned int len) {
1590 XmbTextExtents(dc.font.set, text, len, NULL, &r);
1593 return XTextWidth(dc.font.xfont, text, len);
1597 textw(const char *text) {
1598 return textnw(text, strlen(text)) + dc.font.height;
1604 unsigned int i, n = counttiled();
1618 for(i = 0, c = nexttiled(c->next); c; c = nexttiled(c->next), i++) {
1619 if(i + 1 == n) /* remainder */
1620 tileresize(c, x, ty, (tx + tw) - x - 2 * c->bw, th - 2 * c->bw);
1622 tileresize(c, x, ty, w - 2 * c->bw, th - 2 * c->bw);
1624 x = c->x + c->w + 2 * c->bw;
1629 tilemaster(unsigned int n) {
1630 Client *c = nexttiled(clients);
1633 tileresize(c, mox, moy, mow - 2 * c->bw, moh - 2 * c->bw);
1635 tileresize(c, mx, my, mw - 2 * c->bw, mh - 2 * c->bw);
1640 tileresize(Client *c, int x, int y, int w, int h) {
1641 resize(c, x, y, w, h, RESIZEHINTS);
1642 if((RESIZEHINTS) && ((c->h < bh) || (c->h > h) || (c->w < bh) || (c->w > w)))
1643 /* client doesn't accept size constraints */
1644 resize(c, x, y, w, h, False);
1650 unsigned int i, n = counttiled();
1664 for(i = 0, c = nexttiled(c->next); c; c = nexttiled(c->next), i++) {
1665 if(i + 1 == n) /* remainder */
1666 tileresize(c, tx, y, tw - 2 * c->bw, (ty + th) - y - 2 * c->bw);
1668 tileresize(c, tx, y, tw - 2 * c->bw, h - 2 * c->bw);
1670 y = c->y + c->h + 2 * c->bw;
1675 togglefloating(const char *arg) {
1678 sel->isfloating = !sel->isfloating;
1680 resize(sel, sel->x, sel->y, sel->w, sel->h, True);
1685 toggletag(const char *arg) {
1691 sel->tags[i] = !sel->tags[i];
1692 for(j = 0; j < LENGTH(tags) && !sel->tags[j]; j++);
1693 if(j == LENGTH(tags))
1694 sel->tags[i] = True; /* at least one tag must be enabled */
1699 toggleview(const char *arg) {
1703 seltags[i] = !seltags[i];
1704 for(j = 0; j < LENGTH(tags) && !seltags[j]; j++);
1705 if(j == LENGTH(tags))
1706 seltags[i] = True; /* at least one tag must be viewed */
1714 XMoveWindow(dpy, c->win, c->x, c->y);
1715 c->isbanned = False;
1719 unmanage(Client *c) {
1722 wc.border_width = c->oldbw;
1723 /* The server grab construct avoids race conditions. */
1725 XSetErrorHandler(xerrordummy);
1726 XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
1731 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1732 setclientstate(c, WithdrawnState);
1736 XSetErrorHandler(xerror);
1742 unmapnotify(XEvent *e) {
1744 XUnmapEvent *ev = &e->xunmap;
1746 if((c = getclient(ev->window)))
1751 updatebarpos(void) {
1753 if(dc.drawable != 0)
1754 XFreePixmap(dpy, dc.drawable);
1755 dc.drawable = XCreatePixmap(dpy, root, bw, bh, DefaultDepth(dpy, screen));
1756 XMoveResizeWindow(dpy, barwin, bx, by, bw, bh);
1760 updatesizehints(Client *c) {
1764 if(!XGetWMNormalHints(dpy, c->win, &size, &msize) || !size.flags)
1766 c->flags = size.flags;
1767 if(c->flags & PBaseSize) {
1768 c->basew = size.base_width;
1769 c->baseh = size.base_height;
1771 else if(c->flags & PMinSize) {
1772 c->basew = size.min_width;
1773 c->baseh = size.min_height;
1776 c->basew = c->baseh = 0;
1777 if(c->flags & PResizeInc) {
1778 c->incw = size.width_inc;
1779 c->inch = size.height_inc;
1782 c->incw = c->inch = 0;
1783 if(c->flags & PMaxSize) {
1784 c->maxw = size.max_width;
1785 c->maxh = size.max_height;
1788 c->maxw = c->maxh = 0;
1789 if(c->flags & PMinSize) {
1790 c->minw = size.min_width;
1791 c->minh = size.min_height;
1793 else if(c->flags & PBaseSize) {
1794 c->minw = size.base_width;
1795 c->minh = size.base_height;
1798 c->minw = c->minh = 0;
1799 if(c->flags & PAspect) {
1800 c->minax = size.min_aspect.x;
1801 c->maxax = size.max_aspect.x;
1802 c->minay = size.min_aspect.y;
1803 c->maxay = size.max_aspect.y;
1806 c->minax = c->maxax = c->minay = c->maxay = 0;
1807 c->isfixed = (c->maxw && c->minw && c->maxh && c->minh
1808 && c->maxw == c->minw && c->maxh == c->minh);
1812 updatetitle(Client *c) {
1813 if(!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
1814 gettextprop(c->win, wmatom[WMName], c->name, sizeof c->name);
1818 updatewmhints(Client *c) {
1821 if((wmh = XGetWMHints(dpy, c->win))) {
1823 sel->isurgent = False;
1825 c->isurgent = (wmh->flags & XUrgencyHint) ? True : False;
1832 view(const char *arg) {
1835 for(i = 0; i < LENGTH(tags); i++)
1836 tmp[i] = (NULL == arg);
1837 tmp[idxoftag(arg)] = True;
1839 if(memcmp(seltags, tmp, TAGSZ) != 0) {
1840 memcpy(prevtags, seltags, TAGSZ);
1841 memcpy(seltags, tmp, TAGSZ);
1847 viewprevtag(const char *arg) {
1849 memcpy(tmp, seltags, TAGSZ);
1850 memcpy(seltags, prevtags, TAGSZ);
1851 memcpy(prevtags, tmp, TAGSZ);
1855 /* There's no way to check accesses to destroyed windows, thus those cases are
1856 * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
1857 * default error handler, which may call exit. */
1859 xerror(Display *dpy, XErrorEvent *ee) {
1860 if(ee->error_code == BadWindow
1861 || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1862 || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1863 || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1864 || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1865 || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1866 || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1867 || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1869 fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1870 ee->request_code, ee->error_code);
1871 return xerrorxlib(dpy, ee); /* may call exit */
1875 xerrordummy(Display *dpy, XErrorEvent *ee) {
1879 /* Startup Error handler to check if another window manager
1880 * is already running. */
1882 xerrorstart(Display *dpy, XErrorEvent *ee) {
1888 zoom(const char *arg) {
1891 if(!sel || lt->isfloating || sel->isfloating)
1893 if(c == nexttiled(clients))
1894 if(!(c = nexttiled(c->next)))
1903 main(int argc, char *argv[]) {
1904 if(argc == 2 && !strcmp("-v", argv[1]))
1905 eprint("dwm-"VERSION", © 2006-2008 dwm engineers, see LICENSE for details\n");
1907 eprint("usage: dwm [-v]\n");
1909 setlocale(LC_CTYPE, "");
1910 if(!(dpy = XOpenDisplay(0)))
1911 eprint("dwm: cannot open display\n");