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 LENGTH(x) (sizeof x / sizeof x[0])
49 #define MOUSEMASK (BUTTONMASK | PointerMotionMask)
53 enum { BarTop, BarBot, BarOff }; /* bar position */
54 enum { CurNormal, CurResize, CurMove, CurLast }; /* cursor */
55 enum { ColBorder, ColFG, ColBG, ColLast }; /* color */
56 enum { NetSupported, NetWMName, NetLast }; /* EWMH atoms */
57 enum { WMProtocols, WMDelete, WMName, WMState, WMLast };/* default atoms */
60 typedef struct Client Client;
64 int rx, ry, rw, rh; /* revert geometry */
65 int basew, baseh, incw, inch, maxw, maxh, minw, minh;
66 int minax, maxax, minay, maxay;
68 unsigned int border, oldborder;
69 Bool isbanned, isfixed, ismax, isfloating, wasfloating;
79 unsigned long norm[ColLast];
80 unsigned long sel[ColLast];
90 } DC; /* draw context */
95 void (*func)(const char *arg);
101 void (*arrange)(void);
115 /* function declarations */
116 void applyrules(Client *c);
118 void attach(Client *c);
119 void attachstack(Client *c);
121 void buttonpress(XEvent *e);
122 void checkotherwm(void);
124 void compileregs(void);
125 void configure(Client *c);
126 void configurenotify(XEvent *e);
127 void configurerequest(XEvent *e);
128 void destroynotify(XEvent *e);
129 void detach(Client *c);
130 void detachstack(Client *c);
132 void drawsquare(Bool filled, Bool empty, unsigned long col[ColLast]);
133 void drawtext(const char *text, unsigned long col[ColLast]);
134 void *emallocz(unsigned int size);
135 void enternotify(XEvent *e);
136 void eprint(const char *errstr, ...);
137 void expose(XEvent *e);
138 void floating(void); /* default floating layout */
139 void focus(Client *c);
140 void focusin(XEvent *e);
141 void focusnext(const char *arg);
142 void focusprev(const char *arg);
143 Client *getclient(Window w);
144 unsigned long getcolor(const char *colstr);
145 long getstate(Window w);
146 Bool gettextprop(Window w, Atom atom, char *text, unsigned int size);
147 void grabbuttons(Client *c, Bool focused);
149 unsigned int idxoftag(const char *tag);
150 void initfont(const char *fontstr);
151 Bool isoccupied(unsigned int t);
152 Bool isprotodel(Client *c);
153 Bool isvisible(Client *c);
154 void keypress(XEvent *e);
155 void killclient(const char *arg);
156 void leavenotify(XEvent *e);
157 void manage(Window w, XWindowAttributes *wa);
158 void mappingnotify(XEvent *e);
159 void maprequest(XEvent *e);
160 void movemouse(Client *c);
161 Client *nexttiled(Client *c);
162 void propertynotify(XEvent *e);
163 void quit(const char *arg);
164 void reapply(const char *arg);
165 void resize(Client *c, int x, int y, int w, int h, Bool sizehints);
166 void resizemouse(Client *c);
170 void setclientstate(Client *c, long state);
171 void setlayout(const char *arg);
172 void setmwfact(const char *arg);
174 void spawn(const char *arg);
175 void tag(const char *arg);
176 unsigned int textnw(const char *text, unsigned int len);
177 unsigned int textw(const char *text);
179 void togglebar(const char *arg);
180 void togglefloating(const char *arg);
181 void togglemax(const char *arg);
182 void toggletag(const char *arg);
183 void toggleview(const char *arg);
184 void unban(Client *c);
185 void unmanage(Client *c);
186 void unmapnotify(XEvent *e);
187 void updatebarpos(void);
188 void updatesizehints(Client *c);
189 void updatetitle(Client *c);
190 void view(const char *arg);
191 void viewprevtag(const char *arg); /* views previous selected tags */
192 int xerror(Display *dpy, XErrorEvent *ee);
193 int xerrordummy(Display *dsply, XErrorEvent *ee);
194 int xerrorstart(Display *dsply, XErrorEvent *ee);
195 void zoom(const char *arg);
200 int screen, sx, sy, sw, sh, wax, way, waw, wah;
201 int (*xerrorxlib)(Display *, XErrorEvent *);
202 unsigned int bh, bpos;
203 unsigned int blw = 0;
204 unsigned int numlockmask = 0;
205 void (*handler[LASTEvent]) (XEvent *) = {
206 [ButtonPress] = buttonpress,
207 [ConfigureRequest] = configurerequest,
208 [ConfigureNotify] = configurenotify,
209 [DestroyNotify] = destroynotify,
210 [EnterNotify] = enternotify,
213 [KeyPress] = keypress,
214 [LeaveNotify] = leavenotify,
215 [MappingNotify] = mappingnotify,
216 [MapRequest] = maprequest,
217 [PropertyNotify] = propertynotify,
218 [UnmapNotify] = unmapnotify
220 Atom wmatom[WMLast], netatom[NetLast];
221 Bool domwfact = True;
223 Bool otherwm, readin;
225 Bool selscreen = True;
226 Client *clients = NULL;
228 Client *stack = NULL;
229 Cursor cursor[CurLast];
232 Layout *layout = NULL;
236 /* configuration, allows nested code to access above variables */
239 Bool prevtags[LENGTH(tags)];
241 /* function implementations */
243 applyrules(Client *c) {
244 static char buf[512];
247 Bool matched = False;
248 XClassHint ch = { 0 };
251 XGetClassHint(dpy, c->win, &ch);
252 snprintf(buf, sizeof buf, "%s:%s:%s",
253 ch.res_class ? ch.res_class : "",
254 ch.res_name ? ch.res_name : "", c->name);
255 for(i = 0; i < LENGTH(rules); i++)
256 if(regs[i].propregex && !regexec(regs[i].propregex, buf, 1, &tmp, 0)) {
257 c->isfloating = rules[i].isfloating;
258 for(j = 0; regs[i].tagregex && j < LENGTH(tags); j++) {
259 if(!regexec(regs[i].tagregex, tags[j], 1, &tmp, 0)) {
270 memcpy(c->tags, seltags, sizeof seltags);
277 for(c = clients; c; c = c->next)
296 attachstack(Client *c) {
305 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
310 buttonpress(XEvent *e) {
313 XButtonPressedEvent *ev = &e->xbutton;
315 if(ev->window == barwin) {
317 for(i = 0; i < LENGTH(tags); i++) {
320 if(ev->button == Button1) {
321 if(ev->state & MODKEY)
326 else if(ev->button == Button3) {
327 if(ev->state & MODKEY)
335 if((ev->x < x + blw) && ev->button == Button1)
338 else if((c = getclient(ev->window))) {
340 if(CLEANMASK(ev->state) != MODKEY)
342 if(ev->button == Button1) {
343 if((layout->arrange == floating) || c->isfloating)
346 togglefloating(NULL);
349 else if(ev->button == Button2) {
350 if((floating != layout->arrange) && c->isfloating)
351 togglefloating(NULL);
355 else if(ev->button == Button3 && !c->isfixed) {
356 if((floating == layout->arrange) || c->isfloating)
359 togglefloating(NULL);
368 XSetErrorHandler(xerrorstart);
370 /* this causes an error if some other window manager is running */
371 XSelectInput(dpy, root, SubstructureRedirectMask);
374 eprint("dwm: another window manager is already running\n");
376 XSetErrorHandler(NULL);
377 xerrorxlib = XSetErrorHandler(xerror);
389 XFreeFontSet(dpy, dc.font.set);
391 XFreeFont(dpy, dc.font.xfont);
392 XUngrabKey(dpy, AnyKey, AnyModifier, root);
393 XFreePixmap(dpy, dc.drawable);
395 XDestroyWindow(dpy, barwin);
396 XFreeCursor(dpy, cursor[CurNormal]);
397 XFreeCursor(dpy, cursor[CurResize]);
398 XFreeCursor(dpy, cursor[CurMove]);
399 XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime);
410 regs = emallocz(LENGTH(rules) * sizeof(Regs));
411 for(i = 0; i < LENGTH(rules); i++) {
413 reg = emallocz(sizeof(regex_t));
414 if(regcomp(reg, rules[i].prop, REG_EXTENDED))
417 regs[i].propregex = reg;
420 reg = emallocz(sizeof(regex_t));
421 if(regcomp(reg, rules[i].tags, REG_EXTENDED))
424 regs[i].tagregex = reg;
430 configure(Client *c) {
433 ce.type = ConfigureNotify;
441 ce.border_width = c->border;
443 ce.override_redirect = False;
444 XSendEvent(dpy, c->win, False, StructureNotifyMask, (XEvent *)&ce);
448 configurenotify(XEvent *e) {
449 XConfigureEvent *ev = &e->xconfigure;
451 if(ev->window == root && (ev->width != sw || ev->height != sh)) {
454 XFreePixmap(dpy, dc.drawable);
455 dc.drawable = XCreatePixmap(dpy, root, sw, bh, DefaultDepth(dpy, screen));
456 XResizeWindow(dpy, barwin, sw, bh);
463 configurerequest(XEvent *e) {
465 XConfigureRequestEvent *ev = &e->xconfigurerequest;
468 if((c = getclient(ev->window))) {
470 if(ev->value_mask & CWBorderWidth)
471 c->border = ev->border_width;
472 if(c->isfixed || c->isfloating || (floating == layout->arrange)) {
473 if(ev->value_mask & CWX)
475 if(ev->value_mask & CWY)
477 if(ev->value_mask & CWWidth)
479 if(ev->value_mask & CWHeight)
481 if((c->x + c->w) > sw && c->isfloating)
482 c->x = sw / 2 - c->w / 2; /* center in x direction */
483 if((c->y + c->h) > sh && c->isfloating)
484 c->y = sh / 2 - c->h / 2; /* center in y direction */
485 if((ev->value_mask & (CWX | CWY))
486 && !(ev->value_mask & (CWWidth | CWHeight)))
489 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h);
497 wc.width = ev->width;
498 wc.height = ev->height;
499 wc.border_width = ev->border_width;
500 wc.sibling = ev->above;
501 wc.stack_mode = ev->detail;
502 XConfigureWindow(dpy, ev->window, ev->value_mask, &wc);
508 destroynotify(XEvent *e) {
510 XDestroyWindowEvent *ev = &e->xdestroywindow;
512 if((c = getclient(ev->window)))
519 c->prev->next = c->next;
521 c->next->prev = c->prev;
524 c->next = c->prev = NULL;
528 detachstack(Client *c) {
531 for(tc=&stack; *tc && *tc != c; tc=&(*tc)->snext);
540 for(i = 0; i < LENGTH(tags); i++) {
541 dc.w = textw(tags[i]);
543 drawtext(tags[i], dc.sel);
544 drawsquare(sel && sel->tags[i], isoccupied(i), dc.sel);
547 drawtext(tags[i], dc.norm);
548 drawsquare(sel && sel->tags[i], isoccupied(i), dc.norm);
553 drawtext(layout->symbol, dc.norm);
561 drawtext(stext, dc.norm);
562 if((dc.w = dc.x - x) > bh) {
565 drawtext(sel->name, dc.sel);
566 drawsquare(sel->ismax, sel->isfloating, dc.sel);
569 drawtext(NULL, dc.norm);
571 XCopyArea(dpy, dc.drawable, barwin, dc.gc, 0, 0, sw, bh, 0, 0);
576 drawsquare(Bool filled, Bool empty, unsigned long col[ColLast]) {
579 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
581 gcv.foreground = col[ColFG];
582 XChangeGC(dpy, dc.gc, GCForeground, &gcv);
583 x = (dc.font.ascent + dc.font.descent + 2) / 4;
587 r.width = r.height = x + 1;
588 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
591 r.width = r.height = x;
592 XDrawRectangles(dpy, dc.drawable, dc.gc, &r, 1);
597 drawtext(const char *text, unsigned long col[ColLast]) {
599 static char buf[256];
600 unsigned int len, olen;
601 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
603 XSetForeground(dpy, dc.gc, col[ColBG]);
604 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
608 olen = len = strlen(text);
609 if(len >= sizeof buf)
610 len = sizeof buf - 1;
611 memcpy(buf, text, len);
613 h = dc.font.ascent + dc.font.descent;
614 y = dc.y + (dc.h / 2) - (h / 2) + dc.font.ascent;
616 /* shorten text if necessary */
617 while(len && (w = textnw(buf, len)) > dc.w - h)
628 return; /* too long */
629 XSetForeground(dpy, dc.gc, col[ColFG]);
631 XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
633 XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
637 emallocz(unsigned int size) {
638 void *res = calloc(1, size);
641 eprint("fatal: could not malloc() %u bytes\n", size);
646 enternotify(XEvent *e) {
648 XCrossingEvent *ev = &e->xcrossing;
650 if(ev->mode != NotifyNormal || ev->detail == NotifyInferior)
652 if((c = getclient(ev->window)))
654 else if(ev->window == root) {
661 eprint(const char *errstr, ...) {
664 va_start(ap, errstr);
665 vfprintf(stderr, errstr, ap);
672 XExposeEvent *ev = &e->xexpose;
675 if(ev->window == barwin)
681 floating(void) { /* default floating layout */
684 domwfact = dozoom = False;
685 for(c = clients; c; c = c->next)
687 resize(c, c->x, c->y, c->w, c->h, True);
692 if((!c && selscreen) || (c && !isvisible(c)))
693 for(c = stack; c && !isvisible(c); c = c->snext);
694 if(sel && sel != c) {
695 grabbuttons(sel, False);
696 XSetWindowBorder(dpy, sel->win, dc.norm[ColBorder]);
701 grabbuttons(c, True);
708 XSetWindowBorder(dpy, c->win, dc.sel[ColBorder]);
709 XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
712 XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
716 focusin(XEvent *e) { /* there are some broken focus acquiring clients */
717 XFocusChangeEvent *ev = &e->xfocus;
719 if(sel && ev->window != sel->win)
720 XSetInputFocus(dpy, sel->win, RevertToPointerRoot, CurrentTime);
724 focusnext(const char *arg) {
729 for(c = sel->next; c && !isvisible(c); c = c->next);
731 for(c = clients; c && !isvisible(c); c = c->next);
739 focusprev(const char *arg) {
744 for(c = sel->prev; c && !isvisible(c); c = c->prev);
746 for(c = clients; c && c->next; c = c->next);
747 for(; c && !isvisible(c); c = c->prev);
756 getclient(Window w) {
759 for(c = clients; c && c->win != w; c = c->next);
764 getcolor(const char *colstr) {
765 Colormap cmap = DefaultColormap(dpy, screen);
768 if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
769 eprint("error, cannot allocate color '%s'\n", colstr);
777 unsigned char *p = NULL;
778 unsigned long n, extra;
781 status = XGetWindowProperty(dpy, w, wmatom[WMState], 0L, 2L, False, wmatom[WMState],
782 &real, &format, &n, &extra, (unsigned char **)&p);
783 if(status != Success)
792 gettextprop(Window w, Atom atom, char *text, unsigned int size) {
797 if(!text || size == 0)
800 XGetTextProperty(dpy, w, &name, atom);
803 if(name.encoding == XA_STRING)
804 strncpy(text, (char *)name.value, size - 1);
806 if(XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success
808 strncpy(text, *list, size - 1);
809 XFreeStringList(list);
812 text[size - 1] = '\0';
818 grabbuttons(Client *c, Bool focused) {
819 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
822 XGrabButton(dpy, Button1, MODKEY, c->win, False, BUTTONMASK,
823 GrabModeAsync, GrabModeSync, None, None);
824 XGrabButton(dpy, Button1, MODKEY | LockMask, c->win, False, BUTTONMASK,
825 GrabModeAsync, GrabModeSync, None, None);
826 XGrabButton(dpy, Button1, MODKEY | numlockmask, c->win, False, BUTTONMASK,
827 GrabModeAsync, GrabModeSync, None, None);
828 XGrabButton(dpy, Button1, MODKEY | numlockmask | LockMask, c->win, False, BUTTONMASK,
829 GrabModeAsync, GrabModeSync, None, None);
831 XGrabButton(dpy, Button2, MODKEY, c->win, False, BUTTONMASK,
832 GrabModeAsync, GrabModeSync, None, None);
833 XGrabButton(dpy, Button2, MODKEY | LockMask, c->win, False, BUTTONMASK,
834 GrabModeAsync, GrabModeSync, None, None);
835 XGrabButton(dpy, Button2, MODKEY | numlockmask, c->win, False, BUTTONMASK,
836 GrabModeAsync, GrabModeSync, None, None);
837 XGrabButton(dpy, Button2, MODKEY | numlockmask | LockMask, c->win, False, BUTTONMASK,
838 GrabModeAsync, GrabModeSync, None, None);
840 XGrabButton(dpy, Button3, MODKEY, c->win, False, BUTTONMASK,
841 GrabModeAsync, GrabModeSync, None, None);
842 XGrabButton(dpy, Button3, MODKEY | LockMask, c->win, False, BUTTONMASK,
843 GrabModeAsync, GrabModeSync, None, None);
844 XGrabButton(dpy, Button3, MODKEY | numlockmask, c->win, False, BUTTONMASK,
845 GrabModeAsync, GrabModeSync, None, None);
846 XGrabButton(dpy, Button3, MODKEY | numlockmask | LockMask, c->win, False, BUTTONMASK,
847 GrabModeAsync, GrabModeSync, None, None);
850 XGrabButton(dpy, AnyButton, AnyModifier, c->win, False, BUTTONMASK,
851 GrabModeAsync, GrabModeSync, None, None);
859 XUngrabKey(dpy, AnyKey, AnyModifier, root);
860 for(i = 0; i < LENGTH(keys); i++) {
861 code = XKeysymToKeycode(dpy, keys[i].keysym);
862 XGrabKey(dpy, code, keys[i].mod, root, True,
863 GrabModeAsync, GrabModeAsync);
864 XGrabKey(dpy, code, keys[i].mod | LockMask, root, True,
865 GrabModeAsync, GrabModeAsync);
866 XGrabKey(dpy, code, keys[i].mod | numlockmask, root, True,
867 GrabModeAsync, GrabModeAsync);
868 XGrabKey(dpy, code, keys[i].mod | numlockmask | LockMask, root, True,
869 GrabModeAsync, GrabModeAsync);
874 idxoftag(const char *tag) {
877 for(i = 0; (i < LENGTH(tags)) && (tags[i] != tag); i++);
878 return (i < LENGTH(tags)) ? i : 0;
882 initfont(const char *fontstr) {
883 char *def, **missing;
888 XFreeFontSet(dpy, dc.font.set);
889 dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
892 fprintf(stderr, "dwm: missing fontset: %s\n", missing[n]);
893 XFreeStringList(missing);
896 XFontSetExtents *font_extents;
897 XFontStruct **xfonts;
899 dc.font.ascent = dc.font.descent = 0;
900 font_extents = XExtentsOfFontSet(dc.font.set);
901 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
902 for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
903 if(dc.font.ascent < (*xfonts)->ascent)
904 dc.font.ascent = (*xfonts)->ascent;
905 if(dc.font.descent < (*xfonts)->descent)
906 dc.font.descent = (*xfonts)->descent;
912 XFreeFont(dpy, dc.font.xfont);
913 dc.font.xfont = NULL;
914 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr))
915 && !(dc.font.xfont = XLoadQueryFont(dpy, "fixed")))
916 eprint("error, cannot load font: '%s'\n", fontstr);
917 dc.font.ascent = dc.font.xfont->ascent;
918 dc.font.descent = dc.font.xfont->descent;
920 dc.font.height = dc.font.ascent + dc.font.descent;
924 isoccupied(unsigned int t) {
927 for(c = clients; c; c = c->next)
934 isprotodel(Client *c) {
939 if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
940 for(i = 0; !ret && i < n; i++)
941 if(protocols[i] == wmatom[WMDelete])
949 isvisible(Client *c) {
952 for(i = 0; i < LENGTH(tags); i++)
953 if(c->tags[i] && seltags[i])
959 keypress(XEvent *e) {
965 keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
966 for(i = 0; i < LENGTH(keys); i++)
967 if(keysym == keys[i].keysym
968 && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state))
971 keys[i].func(keys[i].arg);
976 killclient(const char *arg) {
981 if(isprotodel(sel)) {
982 ev.type = ClientMessage;
983 ev.xclient.window = sel->win;
984 ev.xclient.message_type = wmatom[WMProtocols];
985 ev.xclient.format = 32;
986 ev.xclient.data.l[0] = wmatom[WMDelete];
987 ev.xclient.data.l[1] = CurrentTime;
988 XSendEvent(dpy, sel->win, False, NoEventMask, &ev);
991 XKillClient(dpy, sel->win);
995 leavenotify(XEvent *e) {
996 XCrossingEvent *ev = &e->xcrossing;
998 if((ev->window == root) && !ev->same_screen) {
1005 manage(Window w, XWindowAttributes *wa) {
1006 Client *c, *t = NULL;
1011 c = emallocz(sizeof(Client));
1012 c->tags = emallocz(sizeof seltags);
1018 c->oldborder = wa->border_width;
1019 if(c->w == sw && c->h == sh) {
1022 c->border = wa->border_width;
1025 if(c->x + c->w + 2 * c->border > wax + waw)
1026 c->x = wax + waw - c->w - 2 * c->border;
1027 if(c->y + c->h + 2 * c->border > way + wah)
1028 c->y = way + wah - c->h - 2 * c->border;
1033 c->border = BORDERPX;
1035 wc.border_width = c->border;
1036 XConfigureWindow(dpy, w, CWBorderWidth, &wc);
1037 XSetWindowBorder(dpy, w, dc.norm[ColBorder]);
1038 configure(c); /* propagates border_width, if size doesn't change */
1040 XSelectInput(dpy, w, EnterWindowMask | FocusChangeMask | PropertyChangeMask | StructureNotifyMask);
1041 grabbuttons(c, False);
1043 if((rettrans = XGetTransientForHint(dpy, w, &trans) == Success))
1044 for(t = clients; t && t->win != trans; t = t->next);
1046 memcpy(c->tags, t->tags, sizeof seltags);
1049 c->isfloating = (rettrans == Success) || c->isfixed;
1052 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h); /* some windows require this */
1054 XMapWindow(dpy, c->win);
1055 setclientstate(c, NormalState);
1060 mappingnotify(XEvent *e) {
1061 XMappingEvent *ev = &e->xmapping;
1063 XRefreshKeyboardMapping(ev);
1064 if(ev->request == MappingKeyboard)
1069 maprequest(XEvent *e) {
1070 static XWindowAttributes wa;
1071 XMapRequestEvent *ev = &e->xmaprequest;
1073 if(!XGetWindowAttributes(dpy, ev->window, &wa))
1075 if(wa.override_redirect)
1077 if(!getclient(ev->window))
1078 manage(ev->window, &wa);
1082 movemouse(Client *c) {
1083 int x1, y1, ocx, ocy, di, nx, ny;
1090 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1091 None, cursor[CurMove], CurrentTime) != GrabSuccess)
1094 XQueryPointer(dpy, root, &dummy, &dummy, &x1, &y1, &di, &di, &dui);
1096 XMaskEvent(dpy, MOUSEMASK | ExposureMask | SubstructureRedirectMask, &ev);
1099 XUngrabPointer(dpy, CurrentTime);
1101 case ConfigureRequest:
1104 handler[ev.type](&ev);
1108 nx = ocx + (ev.xmotion.x - x1);
1109 ny = ocy + (ev.xmotion.y - y1);
1110 if(abs(wax + nx) < SNAP)
1112 else if(abs((wax + waw) - (nx + c->w + 2 * c->border)) < SNAP)
1113 nx = wax + waw - c->w - 2 * c->border;
1114 if(abs(way - ny) < SNAP)
1116 else if(abs((way + wah) - (ny + c->h + 2 * c->border)) < SNAP)
1117 ny = way + wah - c->h - 2 * c->border;
1118 resize(c, nx, ny, c->w, c->h, False);
1125 nexttiled(Client *c) {
1126 for(; c && (c->isfloating || !isvisible(c)); c = c->next);
1131 propertynotify(XEvent *e) {
1134 XPropertyEvent *ev = &e->xproperty;
1136 if(ev->state == PropertyDelete)
1137 return; /* ignore */
1138 if((c = getclient(ev->window))) {
1141 case XA_WM_TRANSIENT_FOR:
1142 XGetTransientForHint(dpy, c->win, &trans);
1143 if(!c->isfloating && (c->isfloating = (getclient(trans) != NULL)))
1146 case XA_WM_NORMAL_HINTS:
1150 if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
1159 quit(const char *arg) {
1160 readin = running = False;
1164 reapply(const char *arg) {
1165 static Bool zerotags[LENGTH(tags)] = { 0 };
1168 for(c = clients; c; c = c->next) {
1169 memcpy(c->tags, zerotags, sizeof zerotags);
1176 resize(Client *c, int x, int y, int w, int h, Bool sizehints) {
1180 /* set minimum possible */
1186 /* temporarily remove base dimensions */
1190 /* adjust for aspect limits */
1191 if (c->minay > 0 && c->maxay > 0 && c->minax > 0 && c->maxax > 0) {
1192 if (w * c->maxay > h * c->maxax)
1193 w = h * c->maxax / c->maxay;
1194 else if (w * c->minay < h * c->minax)
1195 h = w * c->minay / c->minax;
1198 /* adjust for increment value */
1204 /* restore base dimensions */
1208 if(c->minw > 0 && w < c->minw)
1210 if(c->minh > 0 && h < c->minh)
1212 if(c->maxw > 0 && w > c->maxw)
1214 if(c->maxh > 0 && h > c->maxh)
1217 if(w <= 0 || h <= 0)
1219 /* offscreen appearance fixes */
1221 x = sw - w - 2 * c->border;
1223 y = sh - h - 2 * c->border;
1224 if(x + w + 2 * c->border < sx)
1226 if(y + h + 2 * c->border < sy)
1228 if(c->x != x || c->y != y || c->w != w || c->h != h) {
1231 c->w = wc.width = w;
1232 c->h = wc.height = h;
1233 wc.border_width = c->border;
1234 XConfigureWindow(dpy, c->win, CWX | CWY | CWWidth | CWHeight | CWBorderWidth, &wc);
1241 resizemouse(Client *c) {
1248 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1249 None, cursor[CurResize], CurrentTime) != GrabSuccess)
1252 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->border - 1, c->h + c->border - 1);
1254 XMaskEvent(dpy, MOUSEMASK | ExposureMask | SubstructureRedirectMask , &ev);
1257 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0,
1258 c->w + c->border - 1, c->h + c->border - 1);
1259 XUngrabPointer(dpy, CurrentTime);
1260 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1262 case ConfigureRequest:
1265 handler[ev.type](&ev);
1269 if((nw = ev.xmotion.x - ocx - 2 * c->border + 1) <= 0)
1271 if((nh = ev.xmotion.y - ocy - 2 * c->border + 1) <= 0)
1273 resize(c, c->x, c->y, nw, nh, True);
1288 if(sel->isfloating || (layout->arrange == floating))
1289 XRaiseWindow(dpy, sel->win);
1290 if(layout->arrange != floating) {
1291 wc.stack_mode = Below;
1292 wc.sibling = barwin;
1293 if(!sel->isfloating) {
1294 XConfigureWindow(dpy, sel->win, CWSibling | CWStackMode, &wc);
1295 wc.sibling = sel->win;
1297 for(c = nexttiled(clients); c; c = nexttiled(c->next)) {
1300 XConfigureWindow(dpy, c->win, CWSibling | CWStackMode, &wc);
1301 wc.sibling = c->win;
1305 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1311 char buf[sizeof stext];
1314 unsigned int len, offset;
1317 /* main event loop, also reads status text from stdin */
1319 xfd = ConnectionNumber(dpy);
1322 len = sizeof stext - 1;
1323 buf[len] = stext[len] = '\0'; /* 0-terminator is never touched */
1327 FD_SET(STDIN_FILENO, &rd);
1329 if(select(xfd + 1, &rd, NULL, NULL, NULL) == -1) {
1332 eprint("select failed\n");
1334 if(FD_ISSET(STDIN_FILENO, &rd)) {
1335 switch((r = read(STDIN_FILENO, buf + offset, len - offset))) {
1337 strncpy(stext, strerror(errno), len);
1341 strncpy(stext, "EOF", 4);
1345 for(p = buf + offset; r > 0; p++, r--, offset++)
1346 if(*p == '\n' || *p == '\0') {
1348 strncpy(stext, buf, len);
1349 p += r - 1; /* p is buf + offset + r - 1 */
1350 for(r = 0; *(p - r) && *(p - r) != '\n'; r++);
1353 memmove(buf, p - r + 1, r);
1360 while(XPending(dpy)) {
1361 XNextEvent(dpy, &ev);
1362 if(handler[ev.type])
1363 (handler[ev.type])(&ev); /* call handler */
1370 unsigned int i, num;
1371 Window *wins, d1, d2;
1372 XWindowAttributes wa;
1375 if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1376 for(i = 0; i < num; i++) {
1377 if(!XGetWindowAttributes(dpy, wins[i], &wa)
1378 || wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1380 if(wa.map_state == IsViewable || getstate(wins[i]) == IconicState)
1381 manage(wins[i], &wa);
1383 for(i = 0; i < num; i++) { /* now the transients */
1384 if(!XGetWindowAttributes(dpy, wins[i], &wa))
1386 if(XGetTransientForHint(dpy, wins[i], &d1)
1387 && (wa.map_state == IsViewable || getstate(wins[i]) == IconicState))
1388 manage(wins[i], &wa);
1396 setclientstate(Client *c, long state) {
1397 long data[] = {state, None};
1399 XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1400 PropModeReplace, (unsigned char *)data, 2);
1404 setlayout(const char *arg) {
1408 if(++layout == &layouts[LENGTH(layouts)])
1409 layout = &layouts[0];
1412 for(i = 0; i < LENGTH(layouts); i++)
1413 if(!strcmp(arg, layouts[i].symbol))
1415 if(i == LENGTH(layouts))
1417 layout = &layouts[i];
1426 setmwfact(const char *arg) {
1431 /* arg handling, manipulate mwfact */
1434 else if(sscanf(arg, "%lf", &delta) == 1) {
1435 if(arg[0] == '+' || arg[0] == '-')
1441 else if(mwfact > 0.9)
1450 unsigned int i, j, mask;
1452 XModifierKeymap *modmap;
1453 XSetWindowAttributes wa;
1456 wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1457 wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1458 wmatom[WMName] = XInternAtom(dpy, "WM_NAME", False);
1459 wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1460 netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1461 netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1462 XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1463 PropModeReplace, (unsigned char *) netatom, NetLast);
1466 cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1467 cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1468 cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1472 sw = DisplayWidth(dpy, screen);
1473 sh = DisplayHeight(dpy, screen);
1475 /* init modifier map */
1476 modmap = XGetModifierMapping(dpy);
1477 for(i = 0; i < 8; i++)
1478 for(j = 0; j < modmap->max_keypermod; j++) {
1479 if(modmap->modifiermap[i * modmap->max_keypermod + j]
1480 == XKeysymToKeycode(dpy, XK_Num_Lock))
1481 numlockmask = (1 << i);
1483 XFreeModifiermap(modmap);
1485 /* select for events */
1486 wa.event_mask = SubstructureRedirectMask | SubstructureNotifyMask
1487 | EnterWindowMask | LeaveWindowMask | StructureNotifyMask;
1488 wa.cursor = cursor[CurNormal];
1489 XChangeWindowAttributes(dpy, root, CWEventMask | CWCursor, &wa);
1490 XSelectInput(dpy, root, wa.event_mask);
1496 memcpy(prevtags, seltags, sizeof seltags);
1499 /* init appearance */
1500 dc.norm[ColBorder] = getcolor(NORMBORDERCOLOR);
1501 dc.norm[ColBG] = getcolor(NORMBGCOLOR);
1502 dc.norm[ColFG] = getcolor(NORMFGCOLOR);
1503 dc.sel[ColBorder] = getcolor(SELBORDERCOLOR);
1504 dc.sel[ColBG] = getcolor(SELBGCOLOR);
1505 dc.sel[ColFG] = getcolor(SELFGCOLOR);
1507 dc.h = bh = dc.font.height + 2;
1511 layout = &layouts[0];
1512 for(blw = i = 0; i < LENGTH(layouts); i++) {
1513 j = textw(layouts[i].symbol);
1520 wa.override_redirect = 1;
1521 wa.background_pixmap = ParentRelative;
1522 wa.event_mask = ButtonPressMask | ExposureMask;
1523 barwin = XCreateWindow(dpy, root, sx, sy, sw, bh, 0,
1524 DefaultDepth(dpy, screen), CopyFromParent, DefaultVisual(dpy, screen),
1525 CWOverrideRedirect | CWBackPixmap | CWEventMask, &wa);
1526 XDefineCursor(dpy, barwin, cursor[CurNormal]);
1528 XMapRaised(dpy, barwin);
1529 strcpy(stext, "dwm-"VERSION);
1530 dc.drawable = XCreatePixmap(dpy, root, sw, bh, DefaultDepth(dpy, screen));
1531 dc.gc = XCreateGC(dpy, root, 0, 0);
1532 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
1534 XSetFont(dpy, dc.gc, dc.font.xfont->fid);
1536 /* multihead support */
1537 selscreen = XQueryPointer(dpy, root, &w, &w, &d, &d, &d, &d, &mask);
1542 spawn(const char *arg) {
1543 static char *shell = NULL;
1545 if(!shell && !(shell = getenv("SHELL")))
1549 /* The double-fork construct avoids zombie processes and keeps the code
1550 * clean from stupid signal handlers. */
1554 close(ConnectionNumber(dpy));
1556 execl(shell, shell, "-c", arg, (char *)NULL);
1557 fprintf(stderr, "dwm: execl '%s -c %s'", shell, arg);
1566 tag(const char *arg) {
1571 for(i = 0; i < LENGTH(tags); i++)
1572 sel->tags[i] = (NULL == arg);
1573 sel->tags[idxoftag(arg)] = True;
1578 textnw(const char *text, unsigned int len) {
1582 XmbTextExtents(dc.font.set, text, len, NULL, &r);
1585 return XTextWidth(dc.font.xfont, text, len);
1589 textw(const char *text) {
1590 return textnw(text, strlen(text)) + dc.font.height;
1595 unsigned int i, n, nx, ny, nw, nh, mw, th;
1598 domwfact = dozoom = True;
1599 for(n = 0, c = nexttiled(clients); c; c = nexttiled(c->next))
1603 mw = (n == 1) ? waw : mwfact * waw;
1604 th = (n > 1) ? wah / (n - 1) : 0;
1605 if(n > 1 && th < bh)
1610 nw = 0; /* gcc stupidity requires this */
1611 for(i = 0, c = mc = nexttiled(clients); c; c = nexttiled(c->next), i++) {
1613 if(i == 0) { /* master */
1614 nw = mw - 2 * c->border;
1615 nh = wah - 2 * c->border;
1617 else { /* tile window */
1620 nx += mc->w + 2 * mc->border;
1621 nw = waw - nx - 2 * c->border;
1623 if(i + 1 == n) /* remainder */
1624 nh = (way + wah) - ny - 2 * c->border;
1626 nh = th - 2 * c->border;
1628 resize(c, nx, ny, nw, nh, RESIZEHINTS);
1629 if((RESIZEHINTS) && ((c->h < bh) || (c->h > nh) || (c->w < bh) || (c->w > nw)))
1630 /* client doesn't accept size constraints */
1631 resize(c, nx, ny, nw, nh, False);
1632 if(n > 1 && th != wah)
1633 ny = c->y + c->h + 2 * c->border;
1638 togglebar(const char *arg) {
1640 bpos = (BARPOS == BarOff) ? BarTop : BARPOS;
1648 togglefloating(const char *arg) {
1651 sel->isfloating = !sel->isfloating;
1653 resize(sel, sel->x, sel->y, sel->w, sel->h, True);
1658 togglemax(const char *arg) {
1661 if(!sel || sel->isfixed)
1663 if((sel->ismax = !sel->ismax)) {
1664 if((layout->arrange == floating) || sel->isfloating)
1665 sel->wasfloating = True;
1667 togglefloating(NULL);
1668 sel->wasfloating = False;
1674 resize(sel, wax, way, waw - 2 * sel->border, wah - 2 * sel->border, True);
1677 resize(sel, sel->rx, sel->ry, sel->rw, sel->rh, True);
1678 if(!sel->wasfloating)
1679 togglefloating(NULL);
1682 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1686 toggletag(const char *arg) {
1692 sel->tags[i] = !sel->tags[i];
1693 for(j = 0; j < LENGTH(tags) && !sel->tags[j]; j++);
1694 if(j == LENGTH(tags))
1695 sel->tags[i] = True; /* at least one tag must be enabled */
1700 toggleview(const char *arg) {
1704 seltags[i] = !seltags[i];
1705 for(j = 0; j < LENGTH(tags) && !seltags[j]; j++);
1706 if(j == LENGTH(tags))
1707 seltags[i] = True; /* at least one tag must be viewed */
1715 XMoveWindow(dpy, c->win, c->x, c->y);
1716 c->isbanned = False;
1720 unmanage(Client *c) {
1723 wc.border_width = c->oldborder;
1724 /* The server grab construct avoids race conditions. */
1726 XSetErrorHandler(xerrordummy);
1727 XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
1732 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1733 setclientstate(c, WithdrawnState);
1737 XSetErrorHandler(xerror);
1743 unmapnotify(XEvent *e) {
1745 XUnmapEvent *ev = &e->xunmap;
1747 if((c = getclient(ev->window)))
1752 updatebarpos(void) {
1763 XMoveWindow(dpy, barwin, sx, sy);
1767 XMoveWindow(dpy, barwin, sx, sy + wah);
1770 XMoveWindow(dpy, barwin, sx, sy - bh);
1774 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1778 updatesizehints(Client *c) {
1782 if(!XGetWMNormalHints(dpy, c->win, &size, &msize) || !size.flags)
1784 c->flags = size.flags;
1785 if(c->flags & PBaseSize) {
1786 c->basew = size.base_width;
1787 c->baseh = size.base_height;
1789 else if(c->flags & PMinSize) {
1790 c->basew = size.min_width;
1791 c->baseh = size.min_height;
1794 c->basew = c->baseh = 0;
1795 if(c->flags & PResizeInc) {
1796 c->incw = size.width_inc;
1797 c->inch = size.height_inc;
1800 c->incw = c->inch = 0;
1801 if(c->flags & PMaxSize) {
1802 c->maxw = size.max_width;
1803 c->maxh = size.max_height;
1806 c->maxw = c->maxh = 0;
1807 if(c->flags & PMinSize) {
1808 c->minw = size.min_width;
1809 c->minh = size.min_height;
1811 else if(c->flags & PBaseSize) {
1812 c->minw = size.base_width;
1813 c->minh = size.base_height;
1816 c->minw = c->minh = 0;
1817 if(c->flags & PAspect) {
1818 c->minax = size.min_aspect.x;
1819 c->maxax = size.max_aspect.x;
1820 c->minay = size.min_aspect.y;
1821 c->maxay = size.max_aspect.y;
1824 c->minax = c->maxax = c->minay = c->maxay = 0;
1825 c->isfixed = (c->maxw && c->minw && c->maxh && c->minh
1826 && c->maxw == c->minw && c->maxh == c->minh);
1830 updatetitle(Client *c) {
1831 if(!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
1832 gettextprop(c->win, wmatom[WMName], c->name, sizeof c->name);
1835 /* There's no way to check accesses to destroyed windows, thus those cases are
1836 * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
1837 * default error handler, which may call exit. */
1839 xerror(Display *dpy, XErrorEvent *ee) {
1840 if(ee->error_code == BadWindow
1841 || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1842 || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1843 || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1844 || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1845 || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1846 || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1847 || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1849 fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1850 ee->request_code, ee->error_code);
1851 return xerrorxlib(dpy, ee); /* may call exit */
1855 xerrordummy(Display *dsply, XErrorEvent *ee) {
1859 /* Startup Error handler to check if another window manager
1860 * is already running. */
1862 xerrorstart(Display *dsply, XErrorEvent *ee) {
1868 view(const char *arg) {
1871 memcpy(prevtags, seltags, sizeof seltags);
1872 for(i = 0; i < LENGTH(tags); i++)
1873 seltags[i] = (NULL == arg);
1874 seltags[idxoftag(arg)] = True;
1879 viewprevtag(const char *arg) {
1880 static Bool tmp[LENGTH(tags)];
1882 memcpy(tmp, seltags, sizeof seltags);
1883 memcpy(seltags, prevtags, sizeof seltags);
1884 memcpy(prevtags, tmp, sizeof seltags);
1889 zoom(const char *arg) {
1892 if(!sel || !dozoom || sel->isfloating)
1894 if((c = sel) == nexttiled(clients))
1895 if(!(c = nexttiled(c->next)))
1904 main(int argc, char *argv[]) {
1905 if(argc == 2 && !strcmp("-v", argv[1]))
1906 eprint("dwm-"VERSION", © 2006-2007 Anselm R. Garbe, Sander van Dijk, "
1907 "Jukka Salmi, Premysl Hruby, Szabolcs Nagy\n");
1909 eprint("usage: dwm [-v]\n");
1911 setlocale(LC_CTYPE, "");
1912 if(!(dpy = XOpenDisplay(0)))
1913 eprint("dwm: cannot open display\n");
1914 screen = DefaultScreen(dpy);
1915 root = RootWindow(dpy, screen);