1 /* See LICENSE file for copyright and license details.
3 * dynamic window manager is designed like any other X client as well. It is
4 * driven through handling X events. In contrast to other X clients, a window
5 * manager selects for SubstructureRedirectMask on the root window, to receive
6 * events about window (dis-)appearance. Only one X connection at a time is
7 * allowed to select for this event mask.
9 * Calls to fetch an X event from the event queue are blocking. Due reading
10 * status text from standard input, a select()-driven main loop has been
11 * implemented which selects for reads on the X connection and STDIN_FILENO to
12 * handle all data smoothly. The event handlers of dwm are organized in an
13 * array which is accessed whenever a new event has been fetched. This allows
14 * event dispatching in O(1) time.
16 * Each child of the root window is called a client, except windows which have
17 * set the override_redirect flag. Clients are organized in a global
18 * doubly-linked client list, the focus history is remembered through a global
19 * stack list. Each client contains an array of Bools of the same size as the
20 * global tags array to indicate the tags of a client.
22 * Keys and tagging rules are organized as arrays and defined in config.h.
24 * To understand everything else, start reading main().
33 #include <sys/select.h>
34 #include <sys/types.h>
37 #include <X11/cursorfont.h>
38 #include <X11/keysym.h>
39 #include <X11/Xatom.h>
41 #include <X11/Xproto.h>
42 #include <X11/Xutil.h>
45 #define BUTTONMASK (ButtonPressMask | ButtonReleaseMask)
46 #define CLEANMASK(mask) (mask & ~(numlockmask | LockMask))
47 #define MOUSEMASK (BUTTONMASK | PointerMotionMask)
48 #define LENGTH(x) (sizeof x / sizeof x[0])
52 enum { BarTop, BarBot, BarOff }; /* bar position */
53 enum { CurNormal, CurResize, CurMove, CurLast }; /* cursor */
54 enum { ColBorder, ColFG, ColBG, ColLast }; /* color */
55 enum { NetSupported, NetWMName, NetLast }; /* EWMH atoms */
56 enum { WMProtocols, WMDelete, WMName, WMState, WMLast };/* default atoms */
59 typedef struct Client Client;
63 int rx, ry, rw, rh; /* revert geometry */
64 int basew, baseh, incw, inch, maxw, maxh, minw, minh;
65 int minax, maxax, minay, maxay;
67 unsigned int border, oldborder;
68 Bool isbanned, isfixed, ismax, isfloating, wasfloating;
78 unsigned long norm[ColLast];
79 unsigned long sel[ColLast];
89 } DC; /* draw context */
94 void (*func)(const char *arg);
100 void (*arrange)(void);
114 /* function declarations */
115 void applyrules(Client *c);
117 void attach(Client *c);
118 void attachstack(Client *c);
120 void buttonpress(XEvent *e);
121 void checkotherwm(void);
123 void compileregs(void);
124 void configure(Client *c);
125 void configurenotify(XEvent *e);
126 void configurerequest(XEvent *e);
127 void destroynotify(XEvent *e);
128 void detach(Client *c);
129 void detachstack(Client *c);
131 void drawsquare(Bool filled, Bool empty, unsigned long col[ColLast]);
132 void drawtext(const char *text, unsigned long col[ColLast]);
133 void *emallocz(unsigned int size);
134 void enternotify(XEvent *e);
135 void eprint(const char *errstr, ...);
136 void expose(XEvent *e);
137 void floating(void); /* default floating layout */
138 void focus(Client *c);
139 void focusnext(const char *arg);
140 void focusprev(const char *arg);
141 Client *getclient(Window w);
142 unsigned long getcolor(const char *colstr);
143 long getstate(Window w);
144 Bool gettextprop(Window w, Atom atom, char *text, unsigned int size);
145 void grabbuttons(Client *c, Bool focused);
146 unsigned int idxoftag(const char *tag);
147 void initfont(const char *fontstr);
148 Bool isoccupied(unsigned int t);
149 Bool isprotodel(Client *c);
150 Bool isvisible(Client *c);
151 void keypress(XEvent *e);
152 void killclient(const char *arg);
153 void leavenotify(XEvent *e);
154 void manage(Window w, XWindowAttributes *wa);
155 void mappingnotify(XEvent *e);
156 void maprequest(XEvent *e);
157 void movemouse(Client *c);
158 Client *nexttiled(Client *c);
159 void propertynotify(XEvent *e);
160 void quit(const char *arg);
161 void resize(Client *c, int x, int y, int w, int h, Bool sizehints);
162 void resizemouse(Client *c);
166 void setclientstate(Client *c, long state);
167 void setlayout(const char *arg);
168 void setmwfact(const char *arg);
170 void spawn(const char *arg);
171 void tag(const char *arg);
172 unsigned int textnw(const char *text, unsigned int len);
173 unsigned int textw(const char *text);
175 void togglebar(const char *arg);
176 void togglefloating(const char *arg);
177 void togglemax(const char *arg);
178 void toggletag(const char *arg);
179 void toggleview(const char *arg);
180 void unban(Client *c);
181 void unmanage(Client *c);
182 void unmapnotify(XEvent *e);
183 void updatebarpos(void);
184 void updatesizehints(Client *c);
185 void updatetitle(Client *c);
186 void view(const char *arg);
187 void viewprevtag(const char *arg); /* views previous selected tags */
188 int xerror(Display *dpy, XErrorEvent *ee);
189 int xerrordummy(Display *dsply, XErrorEvent *ee);
190 int xerrorstart(Display *dsply, XErrorEvent *ee);
191 void zoom(const char *arg);
196 int screen, sx, sy, sw, sh, wax, way, waw, wah;
197 int (*xerrorxlib)(Display *, XErrorEvent *);
198 unsigned int bh, bpos;
199 unsigned int blw = 0;
200 unsigned int numlockmask = 0;
201 void (*handler[LASTEvent]) (XEvent *) = {
202 [ButtonPress] = buttonpress,
203 [ConfigureRequest] = configurerequest,
204 [ConfigureNotify] = configurenotify,
205 [DestroyNotify] = destroynotify,
206 [EnterNotify] = enternotify,
207 [LeaveNotify] = leavenotify,
209 [KeyPress] = keypress,
210 [MappingNotify] = mappingnotify,
211 [MapRequest] = maprequest,
212 [PropertyNotify] = propertynotify,
213 [UnmapNotify] = unmapnotify
215 Atom wmatom[WMLast], netatom[NetLast];
216 Bool domwfact = True;
218 Bool otherwm, readin;
220 Bool selscreen = True;
221 Client *clients = NULL;
223 Client *stack = NULL;
224 Cursor cursor[CurLast];
227 Layout *layout = NULL;
231 /* configuration, allows nested code to access above variables */
234 Bool prevtags[LENGTH(tags)] = {[0] = True};
236 /* function implementations */
238 applyrules(Client *c) {
239 static char buf[512];
242 Bool matched = False;
243 XClassHint ch = { 0 };
246 XGetClassHint(dpy, c->win, &ch);
247 snprintf(buf, sizeof buf, "%s:%s:%s",
248 ch.res_class ? ch.res_class : "",
249 ch.res_name ? ch.res_name : "", c->name);
250 for(i = 0; i < LENGTH(rules); i++)
251 if(regs[i].propregex && !regexec(regs[i].propregex, buf, 1, &tmp, 0)) {
252 c->isfloating = rules[i].isfloating;
253 for(j = 0; regs[i].tagregex && j < LENGTH(tags); j++) {
254 if(!regexec(regs[i].tagregex, tags[j], 1, &tmp, 0)) {
265 memcpy(c->tags, seltags, sizeof seltags);
272 for(c = clients; c; c = c->next)
291 attachstack(Client *c) {
300 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
305 buttonpress(XEvent *e) {
308 XButtonPressedEvent *ev = &e->xbutton;
310 if(ev->window == barwin) {
312 for(i = 0; i < LENGTH(tags); i++) {
315 if(ev->button == Button1) {
316 if(ev->state & MODKEY)
321 else if(ev->button == Button3) {
322 if(ev->state & MODKEY)
330 if((ev->x < x + blw) && ev->button == Button1)
333 else if((c = getclient(ev->window))) {
335 if(CLEANMASK(ev->state) != MODKEY)
337 if(ev->button == Button1) {
338 if((layout->arrange == floating) || c->isfloating)
341 togglefloating(NULL);
344 else if(ev->button == Button2) {
345 if((floating != layout->arrange) && c->isfloating)
346 togglefloating(NULL);
350 else if(ev->button == Button3 && !c->isfixed) {
351 if((floating == layout->arrange) || c->isfloating)
354 togglefloating(NULL);
363 XSetErrorHandler(xerrorstart);
365 /* this causes an error if some other window manager is running */
366 XSelectInput(dpy, root, SubstructureRedirectMask);
369 eprint("dwm: another window manager is already running\n");
371 XSetErrorHandler(NULL);
372 xerrorxlib = XSetErrorHandler(xerror);
384 XFreeFontSet(dpy, dc.font.set);
386 XFreeFont(dpy, dc.font.xfont);
387 XUngrabKey(dpy, AnyKey, AnyModifier, root);
388 XFreePixmap(dpy, dc.drawable);
390 XDestroyWindow(dpy, barwin);
391 XFreeCursor(dpy, cursor[CurNormal]);
392 XFreeCursor(dpy, cursor[CurResize]);
393 XFreeCursor(dpy, cursor[CurMove]);
394 XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime);
405 regs = emallocz(LENGTH(rules) * sizeof(Regs));
406 for(i = 0; i < LENGTH(rules); i++) {
408 reg = emallocz(sizeof(regex_t));
409 if(regcomp(reg, rules[i].prop, REG_EXTENDED))
412 regs[i].propregex = reg;
415 reg = emallocz(sizeof(regex_t));
416 if(regcomp(reg, rules[i].tags, REG_EXTENDED))
419 regs[i].tagregex = reg;
425 configure(Client *c) {
428 ce.type = ConfigureNotify;
436 ce.border_width = c->border;
438 ce.override_redirect = False;
439 XSendEvent(dpy, c->win, False, StructureNotifyMask, (XEvent *)&ce);
443 configurenotify(XEvent *e) {
444 XConfigureEvent *ev = &e->xconfigure;
446 if(ev->window == root && (ev->width != sw || ev->height != sh)) {
449 XFreePixmap(dpy, dc.drawable);
450 dc.drawable = XCreatePixmap(dpy, root, sw, bh, DefaultDepth(dpy, screen));
451 XResizeWindow(dpy, barwin, sw, bh);
458 configurerequest(XEvent *e) {
460 XConfigureRequestEvent *ev = &e->xconfigurerequest;
463 if((c = getclient(ev->window))) {
465 if(ev->value_mask & CWBorderWidth)
466 c->border = ev->border_width;
467 if(c->isfixed || c->isfloating || (floating == layout->arrange)) {
468 if(ev->value_mask & CWX)
470 if(ev->value_mask & CWY)
472 if(ev->value_mask & CWWidth)
474 if(ev->value_mask & CWHeight)
476 if((c->x + c->w) > sw && c->isfloating)
477 c->x = sw / 2 - c->w / 2; /* center in x direction */
478 if((c->y + c->h) > sh && c->isfloating)
479 c->y = sh / 2 - c->h / 2; /* center in y direction */
480 if((ev->value_mask & (CWX | CWY))
481 && !(ev->value_mask & (CWWidth | CWHeight)))
484 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h);
492 wc.width = ev->width;
493 wc.height = ev->height;
494 wc.border_width = ev->border_width;
495 wc.sibling = ev->above;
496 wc.stack_mode = ev->detail;
497 XConfigureWindow(dpy, ev->window, ev->value_mask, &wc);
503 destroynotify(XEvent *e) {
505 XDestroyWindowEvent *ev = &e->xdestroywindow;
507 if((c = getclient(ev->window)))
514 c->prev->next = c->next;
516 c->next->prev = c->prev;
519 c->next = c->prev = NULL;
523 detachstack(Client *c) {
526 for(tc=&stack; *tc && *tc != c; tc=&(*tc)->snext);
535 for(i = 0; i < LENGTH(tags); i++) {
536 dc.w = textw(tags[i]);
538 drawtext(tags[i], dc.sel);
539 drawsquare(sel && sel->tags[i], isoccupied(i), dc.sel);
542 drawtext(tags[i], dc.norm);
543 drawsquare(sel && sel->tags[i], isoccupied(i), dc.norm);
548 drawtext(layout->symbol, dc.norm);
556 drawtext(stext, dc.norm);
557 if((dc.w = dc.x - x) > bh) {
560 drawtext(sel->name, dc.sel);
561 drawsquare(sel->ismax, sel->isfloating, dc.sel);
564 drawtext(NULL, dc.norm);
566 XCopyArea(dpy, dc.drawable, barwin, dc.gc, 0, 0, sw, bh, 0, 0);
571 drawsquare(Bool filled, Bool empty, unsigned long col[ColLast]) {
574 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
576 gcv.foreground = col[ColFG];
577 XChangeGC(dpy, dc.gc, GCForeground, &gcv);
578 x = (dc.font.ascent + dc.font.descent + 2) / 4;
582 r.width = r.height = x + 1;
583 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
586 r.width = r.height = x;
587 XDrawRectangles(dpy, dc.drawable, dc.gc, &r, 1);
592 drawtext(const char *text, unsigned long col[ColLast]) {
594 static char buf[256];
595 unsigned int len, olen;
596 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
598 XSetForeground(dpy, dc.gc, col[ColBG]);
599 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
603 olen = len = strlen(text);
604 if(len >= sizeof buf)
605 len = sizeof buf - 1;
606 memcpy(buf, text, len);
608 h = dc.font.ascent + dc.font.descent;
609 y = dc.y + (dc.h / 2) - (h / 2) + dc.font.ascent;
611 /* shorten text if necessary */
612 while(len && (w = textnw(buf, len)) > dc.w - h)
623 return; /* too long */
624 XSetForeground(dpy, dc.gc, col[ColFG]);
626 XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
628 XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
632 emallocz(unsigned int size) {
633 void *res = calloc(1, size);
636 eprint("fatal: could not malloc() %u bytes\n", size);
641 enternotify(XEvent *e) {
643 XCrossingEvent *ev = &e->xcrossing;
645 if(ev->mode != NotifyNormal || ev->detail == NotifyInferior)
647 if((c = getclient(ev->window)))
649 else if(ev->window == root) {
656 eprint(const char *errstr, ...) {
659 va_start(ap, errstr);
660 vfprintf(stderr, errstr, ap);
667 XExposeEvent *ev = &e->xexpose;
670 if(ev->window == barwin)
676 floating(void) { /* default floating layout */
679 domwfact = dozoom = False;
680 for(c = clients; c; c = c->next)
682 resize(c, c->x, c->y, c->w, c->h, True);
687 if((!c && selscreen) || (c && !isvisible(c)))
688 for(c = stack; c && !isvisible(c); c = c->snext);
689 if(sel && sel != c) {
690 grabbuttons(sel, False);
691 XSetWindowBorder(dpy, sel->win, dc.norm[ColBorder]);
696 grabbuttons(c, True);
703 XSetWindowBorder(dpy, c->win, dc.sel[ColBorder]);
704 XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
707 XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
711 focusnext(const char *arg) {
716 for(c = sel->next; c && !isvisible(c); c = c->next);
718 for(c = clients; c && !isvisible(c); c = c->next);
726 focusprev(const char *arg) {
731 for(c = sel->prev; c && !isvisible(c); c = c->prev);
733 for(c = clients; c && c->next; c = c->next);
734 for(; c && !isvisible(c); c = c->prev);
743 getclient(Window w) {
746 for(c = clients; c && c->win != w; c = c->next);
751 getcolor(const char *colstr) {
752 Colormap cmap = DefaultColormap(dpy, screen);
755 if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
756 eprint("error, cannot allocate color '%s'\n", colstr);
764 unsigned char *p = NULL;
765 unsigned long n, extra;
768 status = XGetWindowProperty(dpy, w, wmatom[WMState], 0L, 2L, False, wmatom[WMState],
769 &real, &format, &n, &extra, (unsigned char **)&p);
770 if(status != Success)
779 gettextprop(Window w, Atom atom, char *text, unsigned int size) {
784 if(!text || size == 0)
787 XGetTextProperty(dpy, w, &name, atom);
790 if(name.encoding == XA_STRING)
791 strncpy(text, (char *)name.value, size - 1);
793 if(XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success
795 strncpy(text, *list, size - 1);
796 XFreeStringList(list);
799 text[size - 1] = '\0';
805 grabbuttons(Client *c, Bool focused) {
806 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
809 XGrabButton(dpy, Button1, MODKEY, c->win, False, BUTTONMASK,
810 GrabModeAsync, GrabModeSync, None, None);
811 XGrabButton(dpy, Button1, MODKEY | LockMask, c->win, False, BUTTONMASK,
812 GrabModeAsync, GrabModeSync, None, None);
813 XGrabButton(dpy, Button1, MODKEY | numlockmask, c->win, False, BUTTONMASK,
814 GrabModeAsync, GrabModeSync, None, None);
815 XGrabButton(dpy, Button1, MODKEY | numlockmask | LockMask, c->win, False, BUTTONMASK,
816 GrabModeAsync, GrabModeSync, None, None);
818 XGrabButton(dpy, Button2, MODKEY, c->win, False, BUTTONMASK,
819 GrabModeAsync, GrabModeSync, None, None);
820 XGrabButton(dpy, Button2, MODKEY | LockMask, c->win, False, BUTTONMASK,
821 GrabModeAsync, GrabModeSync, None, None);
822 XGrabButton(dpy, Button2, MODKEY | numlockmask, c->win, False, BUTTONMASK,
823 GrabModeAsync, GrabModeSync, None, None);
824 XGrabButton(dpy, Button2, MODKEY | numlockmask | LockMask, c->win, False, BUTTONMASK,
825 GrabModeAsync, GrabModeSync, None, None);
827 XGrabButton(dpy, Button3, MODKEY, c->win, False, BUTTONMASK,
828 GrabModeAsync, GrabModeSync, None, None);
829 XGrabButton(dpy, Button3, MODKEY | LockMask, c->win, False, BUTTONMASK,
830 GrabModeAsync, GrabModeSync, None, None);
831 XGrabButton(dpy, Button3, MODKEY | numlockmask, c->win, False, BUTTONMASK,
832 GrabModeAsync, GrabModeSync, None, None);
833 XGrabButton(dpy, Button3, MODKEY | numlockmask | LockMask, c->win, False, BUTTONMASK,
834 GrabModeAsync, GrabModeSync, None, None);
837 XGrabButton(dpy, AnyButton, AnyModifier, c->win, False, BUTTONMASK,
838 GrabModeAsync, GrabModeSync, None, None);
842 idxoftag(const char *tag) {
845 for(i = 0; (i < LENGTH(tags)) && (tags[i] != tag); i++);
846 return (i < LENGTH(tags)) ? i : 0;
850 initfont(const char *fontstr) {
851 char *def, **missing;
856 XFreeFontSet(dpy, dc.font.set);
857 dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
860 fprintf(stderr, "dwm: missing fontset: %s\n", missing[n]);
861 XFreeStringList(missing);
864 XFontSetExtents *font_extents;
865 XFontStruct **xfonts;
867 dc.font.ascent = dc.font.descent = 0;
868 font_extents = XExtentsOfFontSet(dc.font.set);
869 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
870 for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
871 if(dc.font.ascent < (*xfonts)->ascent)
872 dc.font.ascent = (*xfonts)->ascent;
873 if(dc.font.descent < (*xfonts)->descent)
874 dc.font.descent = (*xfonts)->descent;
880 XFreeFont(dpy, dc.font.xfont);
881 dc.font.xfont = NULL;
882 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr))
883 && !(dc.font.xfont = XLoadQueryFont(dpy, "fixed")))
884 eprint("error, cannot load font: '%s'\n", fontstr);
885 dc.font.ascent = dc.font.xfont->ascent;
886 dc.font.descent = dc.font.xfont->descent;
888 dc.font.height = dc.font.ascent + dc.font.descent;
892 isoccupied(unsigned int t) {
895 for(c = clients; c; c = c->next)
902 isprotodel(Client *c) {
907 if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
908 for(i = 0; !ret && i < n; i++)
909 if(protocols[i] == wmatom[WMDelete])
917 isvisible(Client *c) {
920 for(i = 0; i < LENGTH(tags); i++)
921 if(c->tags[i] && seltags[i])
927 keypress(XEvent *e) {
934 if(!e) { /* grabkeys */
935 XUngrabKey(dpy, AnyKey, AnyModifier, root);
936 for(i = 0; i < LENGTH(keys); i++) {
937 code = XKeysymToKeycode(dpy, keys[i].keysym);
938 XGrabKey(dpy, code, keys[i].mod, root, True,
939 GrabModeAsync, GrabModeAsync);
940 XGrabKey(dpy, code, keys[i].mod | LockMask, root, True,
941 GrabModeAsync, GrabModeAsync);
942 XGrabKey(dpy, code, keys[i].mod | numlockmask, root, True,
943 GrabModeAsync, GrabModeAsync);
944 XGrabKey(dpy, code, keys[i].mod | numlockmask | LockMask, root, True,
945 GrabModeAsync, GrabModeAsync);
950 keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
951 for(i = 0; i < LENGTH(keys); i++)
952 if(keysym == keys[i].keysym
953 && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state))
956 keys[i].func(keys[i].arg);
961 killclient(const char *arg) {
966 if(isprotodel(sel)) {
967 ev.type = ClientMessage;
968 ev.xclient.window = sel->win;
969 ev.xclient.message_type = wmatom[WMProtocols];
970 ev.xclient.format = 32;
971 ev.xclient.data.l[0] = wmatom[WMDelete];
972 ev.xclient.data.l[1] = CurrentTime;
973 XSendEvent(dpy, sel->win, False, NoEventMask, &ev);
976 XKillClient(dpy, sel->win);
980 leavenotify(XEvent *e) {
981 XCrossingEvent *ev = &e->xcrossing;
983 if((ev->window == root) && !ev->same_screen) {
990 manage(Window w, XWindowAttributes *wa) {
991 Client *c, *t = NULL;
996 c = emallocz(sizeof(Client));
997 c->tags = emallocz(sizeof seltags);
1003 c->oldborder = wa->border_width;
1004 if(c->w == sw && c->h == sh) {
1007 c->border = wa->border_width;
1010 if(c->x + c->w + 2 * c->border > wax + waw)
1011 c->x = wax + waw - c->w - 2 * c->border;
1012 if(c->y + c->h + 2 * c->border > way + wah)
1013 c->y = way + wah - c->h - 2 * c->border;
1018 c->border = BORDERPX;
1020 wc.border_width = c->border;
1021 XConfigureWindow(dpy, w, CWBorderWidth, &wc);
1022 XSetWindowBorder(dpy, w, dc.norm[ColBorder]);
1023 configure(c); /* propagates border_width, if size doesn't change */
1025 XSelectInput(dpy, w,
1026 StructureNotifyMask | PropertyChangeMask | EnterWindowMask);
1027 grabbuttons(c, False);
1029 if((rettrans = XGetTransientForHint(dpy, w, &trans) == Success))
1030 for(t = clients; t && t->win != trans; t = t->next);
1032 memcpy(c->tags, t->tags, sizeof seltags);
1035 c->isfloating = (rettrans == Success) || c->isfixed;
1038 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h); /* some windows require this */
1040 XMapWindow(dpy, c->win);
1041 setclientstate(c, NormalState);
1046 mappingnotify(XEvent *e) {
1047 XMappingEvent *ev = &e->xmapping;
1049 XRefreshKeyboardMapping(ev);
1050 if(ev->request == MappingKeyboard)
1055 maprequest(XEvent *e) {
1056 static XWindowAttributes wa;
1057 XMapRequestEvent *ev = &e->xmaprequest;
1059 if(!XGetWindowAttributes(dpy, ev->window, &wa))
1061 if(wa.override_redirect)
1063 if(!getclient(ev->window))
1064 manage(ev->window, &wa);
1068 movemouse(Client *c) {
1069 int x1, y1, ocx, ocy, di, nx, ny;
1076 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1077 None, cursor[CurMove], CurrentTime) != GrabSuccess)
1080 XQueryPointer(dpy, root, &dummy, &dummy, &x1, &y1, &di, &di, &dui);
1082 XMaskEvent(dpy, MOUSEMASK | ExposureMask | SubstructureRedirectMask, &ev);
1085 XUngrabPointer(dpy, CurrentTime);
1087 case ConfigureRequest:
1090 handler[ev.type](&ev);
1094 nx = ocx + (ev.xmotion.x - x1);
1095 ny = ocy + (ev.xmotion.y - y1);
1096 if(abs(wax + nx) < SNAP)
1098 else if(abs((wax + waw) - (nx + c->w + 2 * c->border)) < SNAP)
1099 nx = wax + waw - c->w - 2 * c->border;
1100 if(abs(way - ny) < SNAP)
1102 else if(abs((way + wah) - (ny + c->h + 2 * c->border)) < SNAP)
1103 ny = way + wah - c->h - 2 * c->border;
1104 resize(c, nx, ny, c->w, c->h, False);
1111 nexttiled(Client *c) {
1112 for(; c && (c->isfloating || !isvisible(c)); c = c->next);
1117 propertynotify(XEvent *e) {
1120 XPropertyEvent *ev = &e->xproperty;
1122 if(ev->state == PropertyDelete)
1123 return; /* ignore */
1124 if((c = getclient(ev->window))) {
1127 case XA_WM_TRANSIENT_FOR:
1128 XGetTransientForHint(dpy, c->win, &trans);
1129 if(!c->isfloating && (c->isfloating = (getclient(trans) != NULL)))
1132 case XA_WM_NORMAL_HINTS:
1136 if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
1145 quit(const char *arg) {
1146 readin = running = False;
1151 resize(Client *c, int x, int y, int w, int h, Bool sizehints) {
1155 /* set minimum possible */
1161 /* temporarily remove base dimensions */
1165 /* adjust for aspect limits */
1166 if (c->minay > 0 && c->maxay > 0 && c->minax > 0 && c->maxax > 0) {
1167 if (w * c->maxay > h * c->maxax)
1168 w = h * c->maxax / c->maxay;
1169 else if (w * c->minay < h * c->minax)
1170 h = w * c->minay / c->minax;
1173 /* adjust for increment value */
1179 /* restore base dimensions */
1183 if(c->minw > 0 && w < c->minw)
1185 if(c->minh > 0 && h < c->minh)
1187 if(c->maxw > 0 && w > c->maxw)
1189 if(c->maxh > 0 && h > c->maxh)
1192 if(w <= 0 || h <= 0)
1194 /* offscreen appearance fixes */
1196 x = sw - w - 2 * c->border;
1198 y = sh - h - 2 * c->border;
1199 if(x + w + 2 * c->border < sx)
1201 if(y + h + 2 * c->border < sy)
1203 if(c->x != x || c->y != y || c->w != w || c->h != h) {
1206 c->w = wc.width = w;
1207 c->h = wc.height = h;
1208 wc.border_width = c->border;
1209 XConfigureWindow(dpy, c->win, CWX | CWY | CWWidth | CWHeight | CWBorderWidth, &wc);
1216 resizemouse(Client *c) {
1223 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1224 None, cursor[CurResize], CurrentTime) != GrabSuccess)
1227 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->border - 1, c->h + c->border - 1);
1229 XMaskEvent(dpy, MOUSEMASK | ExposureMask | SubstructureRedirectMask , &ev);
1232 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0,
1233 c->w + c->border - 1, c->h + c->border - 1);
1234 XUngrabPointer(dpy, CurrentTime);
1235 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1237 case ConfigureRequest:
1240 handler[ev.type](&ev);
1244 if((nw = ev.xmotion.x - ocx - 2 * c->border + 1) <= 0)
1246 if((nh = ev.xmotion.y - ocy - 2 * c->border + 1) <= 0)
1248 resize(c, c->x, c->y, nw, nh, True);
1263 if(sel->isfloating || (layout->arrange == floating))
1264 XRaiseWindow(dpy, sel->win);
1265 if(layout->arrange != floating) {
1266 wc.stack_mode = Below;
1267 wc.sibling = barwin;
1268 if(!sel->isfloating) {
1269 XConfigureWindow(dpy, sel->win, CWSibling | CWStackMode, &wc);
1270 wc.sibling = sel->win;
1272 for(c = nexttiled(clients); c; c = nexttiled(c->next)) {
1275 XConfigureWindow(dpy, c->win, CWSibling | CWStackMode, &wc);
1276 wc.sibling = c->win;
1280 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1288 unsigned int len, offset;
1291 /* main event loop, also reads status text from stdin */
1293 xfd = ConnectionNumber(dpy);
1296 len = sizeof stext - 1;
1297 stext[len] = '\0'; /* 0-terminator is never touched */
1301 FD_SET(STDIN_FILENO, &rd);
1303 if(select(xfd + 1, &rd, NULL, NULL, NULL) == -1) {
1306 eprint("select failed\n");
1308 if(FD_ISSET(STDIN_FILENO, &rd)) {
1309 switch((r = read(STDIN_FILENO, stext + offset, len - offset))) {
1311 strncpy(stext, strerror(errno), len);
1315 strncpy(stext, "EOF", 4);
1319 stext[offset + r] = '\0';
1320 for(p = stext; *p && *p != '\n'; p++);
1326 offset = (offset + r < len - 1) ? offset + r : 0;
1330 while(XPending(dpy)) {
1331 XNextEvent(dpy, &ev);
1332 if(handler[ev.type])
1333 (handler[ev.type])(&ev); /* call handler */
1340 unsigned int i, num;
1341 Window *wins, d1, d2;
1342 XWindowAttributes wa;
1345 if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1346 for(i = 0; i < num; i++) {
1347 if(!XGetWindowAttributes(dpy, wins[i], &wa)
1348 || wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1350 if(wa.map_state == IsViewable || getstate(wins[i]) == IconicState)
1351 manage(wins[i], &wa);
1353 for(i = 0; i < num; i++) { /* now the transients */
1354 if(!XGetWindowAttributes(dpy, wins[i], &wa))
1356 if(XGetTransientForHint(dpy, wins[i], &d1)
1357 && (wa.map_state == IsViewable || getstate(wins[i]) == IconicState))
1358 manage(wins[i], &wa);
1366 setclientstate(Client *c, long state) {
1367 long data[] = {state, None};
1369 XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1370 PropModeReplace, (unsigned char *)data, 2);
1374 setlayout(const char *arg) {
1378 if(++layout == &layouts[LENGTH(layouts)])
1379 layout = &layouts[0];
1382 for(i = 0; i < LENGTH(layouts); i++)
1383 if(!strcmp(arg, layouts[i].symbol))
1385 if(i == LENGTH(layouts))
1387 layout = &layouts[i];
1396 setmwfact(const char *arg) {
1401 /* arg handling, manipulate mwfact */
1404 else if(sscanf(arg, "%lf", &delta) == 1) {
1405 if(arg[0] == '+' || arg[0] == '-')
1411 else if(mwfact > 0.9)
1420 unsigned int i, j, mask;
1422 XModifierKeymap *modmap;
1423 XSetWindowAttributes wa;
1426 wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1427 wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1428 wmatom[WMName] = XInternAtom(dpy, "WM_NAME", False);
1429 wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1430 netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1431 netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1432 XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1433 PropModeReplace, (unsigned char *) netatom, NetLast);
1436 cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1437 cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1438 cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1442 sw = DisplayWidth(dpy, screen);
1443 sh = DisplayHeight(dpy, screen);
1445 /* init modifier map */
1446 modmap = XGetModifierMapping(dpy);
1447 for(i = 0; i < 8; i++)
1448 for(j = 0; j < modmap->max_keypermod; j++) {
1449 if(modmap->modifiermap[i * modmap->max_keypermod + j]
1450 == XKeysymToKeycode(dpy, XK_Num_Lock))
1451 numlockmask = (1 << i);
1453 XFreeModifiermap(modmap);
1455 /* select for events */
1456 wa.event_mask = SubstructureRedirectMask | SubstructureNotifyMask
1457 | EnterWindowMask | LeaveWindowMask | StructureNotifyMask;
1458 wa.cursor = cursor[CurNormal];
1459 XChangeWindowAttributes(dpy, root, CWEventMask | CWCursor, &wa);
1460 XSelectInput(dpy, root, wa.event_mask);
1468 /* init appearance */
1469 dc.norm[ColBorder] = getcolor(NORMBORDERCOLOR);
1470 dc.norm[ColBG] = getcolor(NORMBGCOLOR);
1471 dc.norm[ColFG] = getcolor(NORMFGCOLOR);
1472 dc.sel[ColBorder] = getcolor(SELBORDERCOLOR);
1473 dc.sel[ColBG] = getcolor(SELBGCOLOR);
1474 dc.sel[ColFG] = getcolor(SELFGCOLOR);
1476 dc.h = bh = dc.font.height + 2;
1480 layout = &layouts[0];
1481 for(blw = i = 0; i < LENGTH(layouts); i++) {
1482 j = textw(layouts[i].symbol);
1489 wa.override_redirect = 1;
1490 wa.background_pixmap = ParentRelative;
1491 wa.event_mask = ButtonPressMask | ExposureMask;
1492 barwin = XCreateWindow(dpy, root, sx, sy, sw, bh, 0,
1493 DefaultDepth(dpy, screen), CopyFromParent, DefaultVisual(dpy, screen),
1494 CWOverrideRedirect | CWBackPixmap | CWEventMask, &wa);
1495 XDefineCursor(dpy, barwin, cursor[CurNormal]);
1497 XMapRaised(dpy, barwin);
1498 strcpy(stext, "dwm-"VERSION);
1499 dc.drawable = XCreatePixmap(dpy, root, sw, bh, DefaultDepth(dpy, screen));
1500 dc.gc = XCreateGC(dpy, root, 0, 0);
1501 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
1503 XSetFont(dpy, dc.gc, dc.font.xfont->fid);
1505 /* multihead support */
1506 selscreen = XQueryPointer(dpy, root, &w, &w, &d, &d, &d, &d, &mask);
1510 spawn(const char *arg) {
1511 static char *shell = NULL;
1513 if(!shell && !(shell = getenv("SHELL")))
1517 /* The double-fork construct avoids zombie processes and keeps the code
1518 * clean from stupid signal handlers. */
1522 close(ConnectionNumber(dpy));
1524 execl(shell, shell, "-c", arg, (char *)NULL);
1525 fprintf(stderr, "dwm: execl '%s -c %s'", shell, arg);
1534 tag(const char *arg) {
1539 for(i = 0; i < LENGTH(tags); i++)
1540 sel->tags[i] = (NULL == arg);
1541 sel->tags[idxoftag(arg)] = True;
1546 textnw(const char *text, unsigned int len) {
1550 XmbTextExtents(dc.font.set, text, len, NULL, &r);
1553 return XTextWidth(dc.font.xfont, text, len);
1557 textw(const char *text) {
1558 return textnw(text, strlen(text)) + dc.font.height;
1563 unsigned int i, n, nx, ny, nw, nh, mw, th;
1566 domwfact = dozoom = True;
1567 for(n = 0, c = nexttiled(clients); c; c = nexttiled(c->next))
1571 mw = (n == 1) ? waw : mwfact * waw;
1572 th = (n > 1) ? wah / (n - 1) : 0;
1573 if(n > 1 && th < bh)
1578 nw = 0; /* gcc stupidity requires this */
1579 for(i = 0, c = mc = nexttiled(clients); c; c = nexttiled(c->next), i++) {
1581 if(i == 0) { /* master */
1582 nw = mw - 2 * c->border;
1583 nh = wah - 2 * c->border;
1585 else { /* tile window */
1588 nx += mc->w + 2 * mc->border;
1589 nw = waw - nx - 2 * c->border;
1591 if(i + 1 == n) /* remainder */
1592 nh = (way + wah) - ny - 2 * c->border;
1594 nh = th - 2 * c->border;
1596 resize(c, nx, ny, nw, nh, RESIZEHINTS);
1597 if((RESIZEHINTS) && ((c->h < bh) || (c->h > nh) || (c->w < bh) || (c->w > nw)))
1598 /* client doesn't accept size constraints */
1599 resize(c, nx, ny, nw, nh, False);
1600 if(n > 1 && th != wah)
1601 ny = c->y + c->h + 2 * c->border;
1606 togglebar(const char *arg) {
1608 bpos = (BARPOS == BarOff) ? BarTop : BARPOS;
1616 togglefloating(const char *arg) {
1619 sel->isfloating = !sel->isfloating;
1621 resize(sel, sel->x, sel->y, sel->w, sel->h, True);
1626 togglemax(const char *arg) {
1629 if(!sel || sel->isfixed)
1631 if((sel->ismax = !sel->ismax)) {
1632 if((layout->arrange == floating) || sel->isfloating)
1633 sel->wasfloating = True;
1635 togglefloating(NULL);
1636 sel->wasfloating = False;
1642 resize(sel, wax, way, waw - 2 * sel->border, wah - 2 * sel->border, True);
1645 resize(sel, sel->rx, sel->ry, sel->rw, sel->rh, True);
1646 if(!sel->wasfloating)
1647 togglefloating(NULL);
1650 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1654 toggletag(const char *arg) {
1660 sel->tags[i] = !sel->tags[i];
1661 for(j = 0; j < LENGTH(tags) && !sel->tags[j]; j++);
1662 if(j == LENGTH(tags))
1663 sel->tags[i] = True; /* at least one tag must be enabled */
1668 toggleview(const char *arg) {
1672 seltags[i] = !seltags[i];
1673 for(j = 0; j < LENGTH(tags) && !seltags[j]; j++);
1674 if(j == LENGTH(tags))
1675 seltags[i] = True; /* at least one tag must be viewed */
1683 XMoveWindow(dpy, c->win, c->x, c->y);
1684 c->isbanned = False;
1688 unmanage(Client *c) {
1691 wc.border_width = c->oldborder;
1692 /* The server grab construct avoids race conditions. */
1694 XSetErrorHandler(xerrordummy);
1695 XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
1700 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1701 setclientstate(c, WithdrawnState);
1705 XSetErrorHandler(xerror);
1711 unmapnotify(XEvent *e) {
1713 XUnmapEvent *ev = &e->xunmap;
1715 if((c = getclient(ev->window)))
1720 updatebarpos(void) {
1731 XMoveWindow(dpy, barwin, sx, sy);
1735 XMoveWindow(dpy, barwin, sx, sy + wah);
1738 XMoveWindow(dpy, barwin, sx, sy - bh);
1742 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1746 updatesizehints(Client *c) {
1750 if(!XGetWMNormalHints(dpy, c->win, &size, &msize) || !size.flags)
1752 c->flags = size.flags;
1753 if(c->flags & PBaseSize) {
1754 c->basew = size.base_width;
1755 c->baseh = size.base_height;
1757 else if(c->flags & PMinSize) {
1758 c->basew = size.min_width;
1759 c->baseh = size.min_height;
1762 c->basew = c->baseh = 0;
1763 if(c->flags & PResizeInc) {
1764 c->incw = size.width_inc;
1765 c->inch = size.height_inc;
1768 c->incw = c->inch = 0;
1769 if(c->flags & PMaxSize) {
1770 c->maxw = size.max_width;
1771 c->maxh = size.max_height;
1774 c->maxw = c->maxh = 0;
1775 if(c->flags & PMinSize) {
1776 c->minw = size.min_width;
1777 c->minh = size.min_height;
1779 else if(c->flags & PBaseSize) {
1780 c->minw = size.base_width;
1781 c->minh = size.base_height;
1784 c->minw = c->minh = 0;
1785 if(c->flags & PAspect) {
1786 c->minax = size.min_aspect.x;
1787 c->maxax = size.max_aspect.x;
1788 c->minay = size.min_aspect.y;
1789 c->maxay = size.max_aspect.y;
1792 c->minax = c->maxax = c->minay = c->maxay = 0;
1793 c->isfixed = (c->maxw && c->minw && c->maxh && c->minh
1794 && c->maxw == c->minw && c->maxh == c->minh);
1798 updatetitle(Client *c) {
1799 if(!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
1800 gettextprop(c->win, wmatom[WMName], c->name, sizeof c->name);
1803 /* There's no way to check accesses to destroyed windows, thus those cases are
1804 * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
1805 * default error handler, which may call exit. */
1807 xerror(Display *dpy, XErrorEvent *ee) {
1808 if(ee->error_code == BadWindow
1809 || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1810 || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1811 || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1812 || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1813 || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1814 || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1815 || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1817 fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1818 ee->request_code, ee->error_code);
1819 return xerrorxlib(dpy, ee); /* may call exit */
1823 xerrordummy(Display *dsply, XErrorEvent *ee) {
1827 /* Startup Error handler to check if another window manager
1828 * is already running. */
1830 xerrorstart(Display *dsply, XErrorEvent *ee) {
1836 view(const char *arg) {
1839 memcpy(prevtags, seltags, sizeof seltags);
1840 for(i = 0; i < LENGTH(tags); i++)
1841 seltags[i] = (NULL == arg);
1842 seltags[idxoftag(arg)] = True;
1847 viewprevtag(const char *arg) {
1848 static Bool tmptags[sizeof tags / sizeof tags[0]];
1850 memcpy(tmptags, seltags, sizeof seltags);
1851 memcpy(seltags, prevtags, sizeof seltags);
1852 memcpy(prevtags, tmptags, sizeof seltags);
1857 zoom(const char *arg) {
1860 if(!sel || !dozoom || sel->isfloating)
1862 if((c = sel) == nexttiled(clients))
1863 if(!(c = nexttiled(c->next)))
1872 main(int argc, char *argv[]) {
1873 if(argc == 2 && !strcmp("-v", argv[1]))
1874 eprint("dwm-"VERSION", © 2006-2007 Anselm R. Garbe, Sander van Dijk, "
1875 "Jukka Salmi, Premysl Hruby, Szabolcs Nagy\n");
1877 eprint("usage: dwm [-v]\n");
1879 setlocale(LC_CTYPE, "");
1880 if(!(dpy = XOpenDisplay(0)))
1881 eprint("dwm: cannot open display\n");
1882 screen = DefaultScreen(dpy);
1883 root = RootWindow(dpy, screen);