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 resize(Client *c, int x, int y, int w, int h, Bool sizehints);
165 void resizemouse(Client *c);
169 void setclientstate(Client *c, long state);
170 void setlayout(const char *arg);
171 void setmwfact(const char *arg);
173 void spawn(const char *arg);
174 void tag(const char *arg);
175 unsigned int textnw(const char *text, unsigned int len);
176 unsigned int textw(const char *text);
178 void togglebar(const char *arg);
179 void togglefloating(const char *arg);
180 void togglemax(const char *arg);
181 void toggletag(const char *arg);
182 void toggleview(const char *arg);
183 void unban(Client *c);
184 void unmanage(Client *c);
185 void unmapnotify(XEvent *e);
186 void updatebarpos(void);
187 void updatesizehints(Client *c);
188 void updatetitle(Client *c);
189 void view(const char *arg);
190 void viewprevtag(const char *arg); /* views previous selected tags */
191 int xerror(Display *dpy, XErrorEvent *ee);
192 int xerrordummy(Display *dsply, XErrorEvent *ee);
193 int xerrorstart(Display *dsply, XErrorEvent *ee);
194 void zoom(const char *arg);
199 int screen, sx, sy, sw, sh, wax, way, waw, wah;
200 int (*xerrorxlib)(Display *, XErrorEvent *);
201 unsigned int bh, bpos;
202 unsigned int blw = 0;
203 unsigned int numlockmask = 0;
204 void (*handler[LASTEvent]) (XEvent *) = {
205 [ButtonPress] = buttonpress,
206 [ConfigureRequest] = configurerequest,
207 [ConfigureNotify] = configurenotify,
208 [DestroyNotify] = destroynotify,
209 [EnterNotify] = enternotify,
212 [KeyPress] = keypress,
213 [LeaveNotify] = leavenotify,
214 [MappingNotify] = mappingnotify,
215 [MapRequest] = maprequest,
216 [PropertyNotify] = propertynotify,
217 [UnmapNotify] = unmapnotify
219 Atom wmatom[WMLast], netatom[NetLast];
220 Bool domwfact = True;
222 Bool otherwm, readin;
224 Bool selscreen = True;
225 Client *clients = NULL;
227 Client *stack = NULL;
228 Cursor cursor[CurLast];
231 Layout *layout = NULL;
235 /* configuration, allows nested code to access above variables */
238 Bool prevtags[LENGTH(tags)];
240 /* function implementations */
242 applyrules(Client *c) {
243 static char buf[512];
246 Bool matched = False;
247 XClassHint ch = { 0 };
250 XGetClassHint(dpy, c->win, &ch);
251 snprintf(buf, sizeof buf, "%s:%s:%s",
252 ch.res_class ? ch.res_class : "",
253 ch.res_name ? ch.res_name : "", c->name);
254 for(i = 0; i < LENGTH(rules); i++)
255 if(regs[i].propregex && !regexec(regs[i].propregex, buf, 1, &tmp, 0)) {
256 c->isfloating = rules[i].isfloating;
257 for(j = 0; regs[i].tagregex && j < LENGTH(tags); j++) {
258 if(!regexec(regs[i].tagregex, tags[j], 1, &tmp, 0)) {
269 memcpy(c->tags, seltags, sizeof seltags);
276 for(c = clients; c; c = c->next)
295 attachstack(Client *c) {
304 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
309 buttonpress(XEvent *e) {
312 XButtonPressedEvent *ev = &e->xbutton;
314 if(ev->window == barwin) {
316 for(i = 0; i < LENGTH(tags); i++) {
319 if(ev->button == Button1) {
320 if(ev->state & MODKEY)
325 else if(ev->button == Button3) {
326 if(ev->state & MODKEY)
334 if((ev->x < x + blw) && ev->button == Button1)
337 else if((c = getclient(ev->window))) {
339 if(CLEANMASK(ev->state) != MODKEY)
341 if(ev->button == Button1) {
342 if((layout->arrange == floating) || c->isfloating)
345 togglefloating(NULL);
348 else if(ev->button == Button2) {
349 if((floating != layout->arrange) && c->isfloating)
350 togglefloating(NULL);
354 else if(ev->button == Button3 && !c->isfixed) {
355 if((floating == layout->arrange) || c->isfloating)
358 togglefloating(NULL);
367 XSetErrorHandler(xerrorstart);
369 /* this causes an error if some other window manager is running */
370 XSelectInput(dpy, root, SubstructureRedirectMask);
373 eprint("dwm: another window manager is already running\n");
375 XSetErrorHandler(NULL);
376 xerrorxlib = XSetErrorHandler(xerror);
388 XFreeFontSet(dpy, dc.font.set);
390 XFreeFont(dpy, dc.font.xfont);
391 XUngrabKey(dpy, AnyKey, AnyModifier, root);
392 XFreePixmap(dpy, dc.drawable);
394 XDestroyWindow(dpy, barwin);
395 XFreeCursor(dpy, cursor[CurNormal]);
396 XFreeCursor(dpy, cursor[CurResize]);
397 XFreeCursor(dpy, cursor[CurMove]);
398 XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime);
409 regs = emallocz(LENGTH(rules) * sizeof(Regs));
410 for(i = 0; i < LENGTH(rules); i++) {
412 reg = emallocz(sizeof(regex_t));
413 if(regcomp(reg, rules[i].prop, REG_EXTENDED))
416 regs[i].propregex = reg;
419 reg = emallocz(sizeof(regex_t));
420 if(regcomp(reg, rules[i].tags, REG_EXTENDED))
423 regs[i].tagregex = reg;
429 configure(Client *c) {
432 ce.type = ConfigureNotify;
440 ce.border_width = c->border;
442 ce.override_redirect = False;
443 XSendEvent(dpy, c->win, False, StructureNotifyMask, (XEvent *)&ce);
447 configurenotify(XEvent *e) {
448 XConfigureEvent *ev = &e->xconfigure;
450 if(ev->window == root && (ev->width != sw || ev->height != sh)) {
453 XFreePixmap(dpy, dc.drawable);
454 dc.drawable = XCreatePixmap(dpy, root, sw, bh, DefaultDepth(dpy, screen));
455 XResizeWindow(dpy, barwin, sw, bh);
462 configurerequest(XEvent *e) {
464 XConfigureRequestEvent *ev = &e->xconfigurerequest;
467 if((c = getclient(ev->window))) {
469 if(ev->value_mask & CWBorderWidth)
470 c->border = ev->border_width;
471 if(c->isfixed || c->isfloating || (floating == layout->arrange)) {
472 if(ev->value_mask & CWX)
474 if(ev->value_mask & CWY)
476 if(ev->value_mask & CWWidth)
478 if(ev->value_mask & CWHeight)
480 if((c->x + c->w) > sw && c->isfloating)
481 c->x = sw / 2 - c->w / 2; /* center in x direction */
482 if((c->y + c->h) > sh && c->isfloating)
483 c->y = sh / 2 - c->h / 2; /* center in y direction */
484 if((ev->value_mask & (CWX | CWY))
485 && !(ev->value_mask & (CWWidth | CWHeight)))
488 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h);
496 wc.width = ev->width;
497 wc.height = ev->height;
498 wc.border_width = ev->border_width;
499 wc.sibling = ev->above;
500 wc.stack_mode = ev->detail;
501 XConfigureWindow(dpy, ev->window, ev->value_mask, &wc);
507 destroynotify(XEvent *e) {
509 XDestroyWindowEvent *ev = &e->xdestroywindow;
511 if((c = getclient(ev->window)))
518 c->prev->next = c->next;
520 c->next->prev = c->prev;
523 c->next = c->prev = NULL;
527 detachstack(Client *c) {
530 for(tc=&stack; *tc && *tc != c; tc=&(*tc)->snext);
539 for(i = 0; i < LENGTH(tags); i++) {
540 dc.w = textw(tags[i]);
542 drawtext(tags[i], dc.sel);
543 drawsquare(sel && sel->tags[i], isoccupied(i), dc.sel);
546 drawtext(tags[i], dc.norm);
547 drawsquare(sel && sel->tags[i], isoccupied(i), dc.norm);
552 drawtext(layout->symbol, dc.norm);
560 drawtext(stext, dc.norm);
561 if((dc.w = dc.x - x) > bh) {
564 drawtext(sel->name, dc.sel);
565 drawsquare(sel->ismax, sel->isfloating, dc.sel);
568 drawtext(NULL, dc.norm);
570 XCopyArea(dpy, dc.drawable, barwin, dc.gc, 0, 0, sw, bh, 0, 0);
575 drawsquare(Bool filled, Bool empty, unsigned long col[ColLast]) {
578 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
580 gcv.foreground = col[ColFG];
581 XChangeGC(dpy, dc.gc, GCForeground, &gcv);
582 x = (dc.font.ascent + dc.font.descent + 2) / 4;
586 r.width = r.height = x + 1;
587 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
590 r.width = r.height = x;
591 XDrawRectangles(dpy, dc.drawable, dc.gc, &r, 1);
596 drawtext(const char *text, unsigned long col[ColLast]) {
598 static char buf[256];
599 unsigned int len, olen;
600 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
602 XSetForeground(dpy, dc.gc, col[ColBG]);
603 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
607 olen = len = strlen(text);
608 if(len >= sizeof buf)
609 len = sizeof buf - 1;
610 memcpy(buf, text, len);
612 h = dc.font.ascent + dc.font.descent;
613 y = dc.y + (dc.h / 2) - (h / 2) + dc.font.ascent;
615 /* shorten text if necessary */
616 while(len && (w = textnw(buf, len)) > dc.w - h)
627 return; /* too long */
628 XSetForeground(dpy, dc.gc, col[ColFG]);
630 XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
632 XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
636 emallocz(unsigned int size) {
637 void *res = calloc(1, size);
640 eprint("fatal: could not malloc() %u bytes\n", size);
645 enternotify(XEvent *e) {
647 XCrossingEvent *ev = &e->xcrossing;
649 if(ev->mode != NotifyNormal || ev->detail == NotifyInferior)
651 if((c = getclient(ev->window)))
653 else if(ev->window == root) {
660 eprint(const char *errstr, ...) {
663 va_start(ap, errstr);
664 vfprintf(stderr, errstr, ap);
671 XExposeEvent *ev = &e->xexpose;
674 if(ev->window == barwin)
680 floating(void) { /* default floating layout */
683 domwfact = dozoom = False;
684 for(c = clients; c; c = c->next)
686 resize(c, c->x, c->y, c->w, c->h, True);
691 if((!c && selscreen) || (c && !isvisible(c)))
692 for(c = stack; c && !isvisible(c); c = c->snext);
693 if(sel && sel != c) {
694 grabbuttons(sel, False);
695 XSetWindowBorder(dpy, sel->win, dc.norm[ColBorder]);
700 grabbuttons(c, True);
707 XSetWindowBorder(dpy, c->win, dc.sel[ColBorder]);
708 XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
711 XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
715 focusin(XEvent *e) { /* there are some broken focus acquiring clients */
716 XFocusChangeEvent *ev = &e->xfocus;
718 if(sel && ev->window != sel->win)
719 XSetInputFocus(dpy, sel->win, RevertToPointerRoot, CurrentTime);
723 focusnext(const char *arg) {
728 for(c = sel->next; c && !isvisible(c); c = c->next);
730 for(c = clients; c && !isvisible(c); c = c->next);
738 focusprev(const char *arg) {
743 for(c = sel->prev; c && !isvisible(c); c = c->prev);
745 for(c = clients; c && c->next; c = c->next);
746 for(; c && !isvisible(c); c = c->prev);
755 getclient(Window w) {
758 for(c = clients; c && c->win != w; c = c->next);
763 getcolor(const char *colstr) {
764 Colormap cmap = DefaultColormap(dpy, screen);
767 if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
768 eprint("error, cannot allocate color '%s'\n", colstr);
776 unsigned char *p = NULL;
777 unsigned long n, extra;
780 status = XGetWindowProperty(dpy, w, wmatom[WMState], 0L, 2L, False, wmatom[WMState],
781 &real, &format, &n, &extra, (unsigned char **)&p);
782 if(status != Success)
791 gettextprop(Window w, Atom atom, char *text, unsigned int size) {
796 if(!text || size == 0)
799 XGetTextProperty(dpy, w, &name, atom);
802 if(name.encoding == XA_STRING)
803 strncpy(text, (char *)name.value, size - 1);
805 if(XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success
807 strncpy(text, *list, size - 1);
808 XFreeStringList(list);
811 text[size - 1] = '\0';
817 grabbuttons(Client *c, Bool focused) {
818 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
821 XGrabButton(dpy, Button1, MODKEY, c->win, False, BUTTONMASK,
822 GrabModeAsync, GrabModeSync, None, None);
823 XGrabButton(dpy, Button1, MODKEY | LockMask, c->win, False, BUTTONMASK,
824 GrabModeAsync, GrabModeSync, None, None);
825 XGrabButton(dpy, Button1, MODKEY | numlockmask, c->win, False, BUTTONMASK,
826 GrabModeAsync, GrabModeSync, None, None);
827 XGrabButton(dpy, Button1, MODKEY | numlockmask | LockMask, c->win, False, BUTTONMASK,
828 GrabModeAsync, GrabModeSync, None, None);
830 XGrabButton(dpy, Button2, MODKEY, c->win, False, BUTTONMASK,
831 GrabModeAsync, GrabModeSync, None, None);
832 XGrabButton(dpy, Button2, MODKEY | LockMask, c->win, False, BUTTONMASK,
833 GrabModeAsync, GrabModeSync, None, None);
834 XGrabButton(dpy, Button2, MODKEY | numlockmask, c->win, False, BUTTONMASK,
835 GrabModeAsync, GrabModeSync, None, None);
836 XGrabButton(dpy, Button2, MODKEY | numlockmask | LockMask, c->win, False, BUTTONMASK,
837 GrabModeAsync, GrabModeSync, None, None);
839 XGrabButton(dpy, Button3, MODKEY, c->win, False, BUTTONMASK,
840 GrabModeAsync, GrabModeSync, None, None);
841 XGrabButton(dpy, Button3, MODKEY | LockMask, c->win, False, BUTTONMASK,
842 GrabModeAsync, GrabModeSync, None, None);
843 XGrabButton(dpy, Button3, MODKEY | numlockmask, c->win, False, BUTTONMASK,
844 GrabModeAsync, GrabModeSync, None, None);
845 XGrabButton(dpy, Button3, MODKEY | numlockmask | LockMask, c->win, False, BUTTONMASK,
846 GrabModeAsync, GrabModeSync, None, None);
849 XGrabButton(dpy, AnyButton, AnyModifier, c->win, False, BUTTONMASK,
850 GrabModeAsync, GrabModeSync, None, None);
858 XUngrabKey(dpy, AnyKey, AnyModifier, root);
859 for(i = 0; i < LENGTH(keys); i++) {
860 code = XKeysymToKeycode(dpy, keys[i].keysym);
861 XGrabKey(dpy, code, keys[i].mod, root, True,
862 GrabModeAsync, GrabModeAsync);
863 XGrabKey(dpy, code, keys[i].mod | LockMask, root, True,
864 GrabModeAsync, GrabModeAsync);
865 XGrabKey(dpy, code, keys[i].mod | numlockmask, root, True,
866 GrabModeAsync, GrabModeAsync);
867 XGrabKey(dpy, code, keys[i].mod | numlockmask | LockMask, root, True,
868 GrabModeAsync, GrabModeAsync);
873 idxoftag(const char *tag) {
876 for(i = 0; (i < LENGTH(tags)) && (tags[i] != tag); i++);
877 return (i < LENGTH(tags)) ? i : 0;
881 initfont(const char *fontstr) {
882 char *def, **missing;
887 XFreeFontSet(dpy, dc.font.set);
888 dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
891 fprintf(stderr, "dwm: missing fontset: %s\n", missing[n]);
892 XFreeStringList(missing);
895 XFontSetExtents *font_extents;
896 XFontStruct **xfonts;
898 dc.font.ascent = dc.font.descent = 0;
899 font_extents = XExtentsOfFontSet(dc.font.set);
900 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
901 for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
902 if(dc.font.ascent < (*xfonts)->ascent)
903 dc.font.ascent = (*xfonts)->ascent;
904 if(dc.font.descent < (*xfonts)->descent)
905 dc.font.descent = (*xfonts)->descent;
911 XFreeFont(dpy, dc.font.xfont);
912 dc.font.xfont = NULL;
913 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr))
914 && !(dc.font.xfont = XLoadQueryFont(dpy, "fixed")))
915 eprint("error, cannot load font: '%s'\n", fontstr);
916 dc.font.ascent = dc.font.xfont->ascent;
917 dc.font.descent = dc.font.xfont->descent;
919 dc.font.height = dc.font.ascent + dc.font.descent;
923 isoccupied(unsigned int t) {
926 for(c = clients; c; c = c->next)
933 isprotodel(Client *c) {
938 if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
939 for(i = 0; !ret && i < n; i++)
940 if(protocols[i] == wmatom[WMDelete])
948 isvisible(Client *c) {
951 for(i = 0; i < LENGTH(tags); i++)
952 if(c->tags[i] && seltags[i])
958 keypress(XEvent *e) {
964 keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
965 for(i = 0; i < LENGTH(keys); i++)
966 if(keysym == keys[i].keysym
967 && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state))
970 keys[i].func(keys[i].arg);
975 killclient(const char *arg) {
980 if(isprotodel(sel)) {
981 ev.type = ClientMessage;
982 ev.xclient.window = sel->win;
983 ev.xclient.message_type = wmatom[WMProtocols];
984 ev.xclient.format = 32;
985 ev.xclient.data.l[0] = wmatom[WMDelete];
986 ev.xclient.data.l[1] = CurrentTime;
987 XSendEvent(dpy, sel->win, False, NoEventMask, &ev);
990 XKillClient(dpy, sel->win);
994 leavenotify(XEvent *e) {
995 XCrossingEvent *ev = &e->xcrossing;
997 if((ev->window == root) && !ev->same_screen) {
1004 manage(Window w, XWindowAttributes *wa) {
1005 Client *c, *t = NULL;
1010 c = emallocz(sizeof(Client));
1011 c->tags = emallocz(sizeof seltags);
1017 c->oldborder = wa->border_width;
1018 if(c->w == sw && c->h == sh) {
1021 c->border = wa->border_width;
1024 if(c->x + c->w + 2 * c->border > wax + waw)
1025 c->x = wax + waw - c->w - 2 * c->border;
1026 if(c->y + c->h + 2 * c->border > way + wah)
1027 c->y = way + wah - c->h - 2 * c->border;
1032 c->border = BORDERPX;
1034 wc.border_width = c->border;
1035 XConfigureWindow(dpy, w, CWBorderWidth, &wc);
1036 XSetWindowBorder(dpy, w, dc.norm[ColBorder]);
1037 configure(c); /* propagates border_width, if size doesn't change */
1039 XSelectInput(dpy, w, EnterWindowMask | FocusChangeMask | PropertyChangeMask | StructureNotifyMask);
1040 grabbuttons(c, False);
1042 if((rettrans = XGetTransientForHint(dpy, w, &trans) == Success))
1043 for(t = clients; t && t->win != trans; t = t->next);
1045 memcpy(c->tags, t->tags, sizeof seltags);
1048 c->isfloating = (rettrans == Success) || c->isfixed;
1051 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h); /* some windows require this */
1053 XMapWindow(dpy, c->win);
1054 setclientstate(c, NormalState);
1059 mappingnotify(XEvent *e) {
1060 XMappingEvent *ev = &e->xmapping;
1062 XRefreshKeyboardMapping(ev);
1063 if(ev->request == MappingKeyboard)
1068 maprequest(XEvent *e) {
1069 static XWindowAttributes wa;
1070 XMapRequestEvent *ev = &e->xmaprequest;
1072 if(!XGetWindowAttributes(dpy, ev->window, &wa))
1074 if(wa.override_redirect)
1076 if(!getclient(ev->window))
1077 manage(ev->window, &wa);
1081 movemouse(Client *c) {
1082 int x1, y1, ocx, ocy, di, nx, ny;
1089 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1090 None, cursor[CurMove], CurrentTime) != GrabSuccess)
1093 XQueryPointer(dpy, root, &dummy, &dummy, &x1, &y1, &di, &di, &dui);
1095 XMaskEvent(dpy, MOUSEMASK | ExposureMask | SubstructureRedirectMask, &ev);
1098 XUngrabPointer(dpy, CurrentTime);
1100 case ConfigureRequest:
1103 handler[ev.type](&ev);
1107 nx = ocx + (ev.xmotion.x - x1);
1108 ny = ocy + (ev.xmotion.y - y1);
1109 if(abs(wax + nx) < SNAP)
1111 else if(abs((wax + waw) - (nx + c->w + 2 * c->border)) < SNAP)
1112 nx = wax + waw - c->w - 2 * c->border;
1113 if(abs(way - ny) < SNAP)
1115 else if(abs((way + wah) - (ny + c->h + 2 * c->border)) < SNAP)
1116 ny = way + wah - c->h - 2 * c->border;
1117 resize(c, nx, ny, c->w, c->h, False);
1124 nexttiled(Client *c) {
1125 for(; c && (c->isfloating || !isvisible(c)); c = c->next);
1130 propertynotify(XEvent *e) {
1133 XPropertyEvent *ev = &e->xproperty;
1135 if(ev->state == PropertyDelete)
1136 return; /* ignore */
1137 if((c = getclient(ev->window))) {
1140 case XA_WM_TRANSIENT_FOR:
1141 XGetTransientForHint(dpy, c->win, &trans);
1142 if(!c->isfloating && (c->isfloating = (getclient(trans) != NULL)))
1145 case XA_WM_NORMAL_HINTS:
1149 if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
1158 quit(const char *arg) {
1159 readin = running = False;
1164 resize(Client *c, int x, int y, int w, int h, Bool sizehints) {
1168 /* set minimum possible */
1174 /* temporarily remove base dimensions */
1178 /* adjust for aspect limits */
1179 if (c->minay > 0 && c->maxay > 0 && c->minax > 0 && c->maxax > 0) {
1180 if (w * c->maxay > h * c->maxax)
1181 w = h * c->maxax / c->maxay;
1182 else if (w * c->minay < h * c->minax)
1183 h = w * c->minay / c->minax;
1186 /* adjust for increment value */
1192 /* restore base dimensions */
1196 if(c->minw > 0 && w < c->minw)
1198 if(c->minh > 0 && h < c->minh)
1200 if(c->maxw > 0 && w > c->maxw)
1202 if(c->maxh > 0 && h > c->maxh)
1205 if(w <= 0 || h <= 0)
1207 /* offscreen appearance fixes */
1209 x = sw - w - 2 * c->border;
1211 y = sh - h - 2 * c->border;
1212 if(x + w + 2 * c->border < sx)
1214 if(y + h + 2 * c->border < sy)
1216 if(c->x != x || c->y != y || c->w != w || c->h != h) {
1219 c->w = wc.width = w;
1220 c->h = wc.height = h;
1221 wc.border_width = c->border;
1222 XConfigureWindow(dpy, c->win, CWX | CWY | CWWidth | CWHeight | CWBorderWidth, &wc);
1229 resizemouse(Client *c) {
1236 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1237 None, cursor[CurResize], CurrentTime) != GrabSuccess)
1240 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->border - 1, c->h + c->border - 1);
1242 XMaskEvent(dpy, MOUSEMASK | ExposureMask | SubstructureRedirectMask , &ev);
1245 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0,
1246 c->w + c->border - 1, c->h + c->border - 1);
1247 XUngrabPointer(dpy, CurrentTime);
1248 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1250 case ConfigureRequest:
1253 handler[ev.type](&ev);
1257 if((nw = ev.xmotion.x - ocx - 2 * c->border + 1) <= 0)
1259 if((nh = ev.xmotion.y - ocy - 2 * c->border + 1) <= 0)
1261 resize(c, c->x, c->y, nw, nh, True);
1276 if(sel->isfloating || (layout->arrange == floating))
1277 XRaiseWindow(dpy, sel->win);
1278 if(layout->arrange != floating) {
1279 wc.stack_mode = Below;
1280 wc.sibling = barwin;
1281 if(!sel->isfloating) {
1282 XConfigureWindow(dpy, sel->win, CWSibling | CWStackMode, &wc);
1283 wc.sibling = sel->win;
1285 for(c = nexttiled(clients); c; c = nexttiled(c->next)) {
1288 XConfigureWindow(dpy, c->win, CWSibling | CWStackMode, &wc);
1289 wc.sibling = c->win;
1293 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1299 char buf[sizeof stext];
1302 unsigned int len, offset;
1305 /* main event loop, also reads status text from stdin */
1307 xfd = ConnectionNumber(dpy);
1310 len = sizeof stext - 1;
1311 buf[len] = stext[len] = '\0'; /* 0-terminator is never touched */
1315 FD_SET(STDIN_FILENO, &rd);
1317 if(select(xfd + 1, &rd, NULL, NULL, NULL) == -1) {
1320 eprint("select failed\n");
1322 if(FD_ISSET(STDIN_FILENO, &rd)) {
1323 switch((r = read(STDIN_FILENO, buf + offset, len - offset))) {
1325 strncpy(stext, strerror(errno), len);
1329 strncpy(stext, "EOF", 4);
1333 for(p = buf + offset; r > 0; p++, r--, offset++)
1334 if(*p == '\n' || *p == '\0') {
1336 strncpy(stext, buf, len);
1337 p += r - 1; /* p is buf + offset + r - 1 */
1338 for(r = 0; *(p - r) && *(p - r) != '\n'; r++);
1341 memmove(buf, p - r + 1, r);
1348 while(XPending(dpy)) {
1349 XNextEvent(dpy, &ev);
1350 if(handler[ev.type])
1351 (handler[ev.type])(&ev); /* call handler */
1358 unsigned int i, num;
1359 Window *wins, d1, d2;
1360 XWindowAttributes wa;
1363 if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1364 for(i = 0; i < num; i++) {
1365 if(!XGetWindowAttributes(dpy, wins[i], &wa)
1366 || wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1368 if(wa.map_state == IsViewable || getstate(wins[i]) == IconicState)
1369 manage(wins[i], &wa);
1371 for(i = 0; i < num; i++) { /* now the transients */
1372 if(!XGetWindowAttributes(dpy, wins[i], &wa))
1374 if(XGetTransientForHint(dpy, wins[i], &d1)
1375 && (wa.map_state == IsViewable || getstate(wins[i]) == IconicState))
1376 manage(wins[i], &wa);
1384 setclientstate(Client *c, long state) {
1385 long data[] = {state, None};
1387 XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1388 PropModeReplace, (unsigned char *)data, 2);
1392 setlayout(const char *arg) {
1396 if(++layout == &layouts[LENGTH(layouts)])
1397 layout = &layouts[0];
1400 for(i = 0; i < LENGTH(layouts); i++)
1401 if(!strcmp(arg, layouts[i].symbol))
1403 if(i == LENGTH(layouts))
1405 layout = &layouts[i];
1414 setmwfact(const char *arg) {
1419 /* arg handling, manipulate mwfact */
1422 else if(sscanf(arg, "%lf", &delta) == 1) {
1423 if(arg[0] == '+' || arg[0] == '-')
1429 else if(mwfact > 0.9)
1438 unsigned int i, j, mask;
1440 XModifierKeymap *modmap;
1441 XSetWindowAttributes wa;
1444 wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1445 wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1446 wmatom[WMName] = XInternAtom(dpy, "WM_NAME", False);
1447 wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1448 netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1449 netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1450 XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1451 PropModeReplace, (unsigned char *) netatom, NetLast);
1454 cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1455 cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1456 cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1460 sw = DisplayWidth(dpy, screen);
1461 sh = DisplayHeight(dpy, screen);
1463 /* init modifier map */
1464 modmap = XGetModifierMapping(dpy);
1465 for(i = 0; i < 8; i++)
1466 for(j = 0; j < modmap->max_keypermod; j++) {
1467 if(modmap->modifiermap[i * modmap->max_keypermod + j]
1468 == XKeysymToKeycode(dpy, XK_Num_Lock))
1469 numlockmask = (1 << i);
1471 XFreeModifiermap(modmap);
1473 /* select for events */
1474 wa.event_mask = SubstructureRedirectMask | SubstructureNotifyMask
1475 | EnterWindowMask | LeaveWindowMask | StructureNotifyMask;
1476 wa.cursor = cursor[CurNormal];
1477 XChangeWindowAttributes(dpy, root, CWEventMask | CWCursor, &wa);
1478 XSelectInput(dpy, root, wa.event_mask);
1484 memcpy(prevtags, seltags, sizeof seltags);
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);
1495 dc.h = bh = dc.font.height + 2;
1499 layout = &layouts[0];
1500 for(blw = i = 0; i < LENGTH(layouts); i++) {
1501 j = textw(layouts[i].symbol);
1508 wa.override_redirect = 1;
1509 wa.background_pixmap = ParentRelative;
1510 wa.event_mask = ButtonPressMask | ExposureMask;
1511 barwin = XCreateWindow(dpy, root, sx, sy, sw, bh, 0,
1512 DefaultDepth(dpy, screen), CopyFromParent, DefaultVisual(dpy, screen),
1513 CWOverrideRedirect | CWBackPixmap | CWEventMask, &wa);
1514 XDefineCursor(dpy, barwin, cursor[CurNormal]);
1516 XMapRaised(dpy, barwin);
1517 strcpy(stext, "dwm-"VERSION);
1518 dc.drawable = XCreatePixmap(dpy, root, sw, bh, DefaultDepth(dpy, screen));
1519 dc.gc = XCreateGC(dpy, root, 0, 0);
1520 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
1522 XSetFont(dpy, dc.gc, dc.font.xfont->fid);
1524 /* multihead support */
1525 selscreen = XQueryPointer(dpy, root, &w, &w, &d, &d, &d, &d, &mask);
1530 spawn(const char *arg) {
1531 static char *shell = NULL;
1533 if(!shell && !(shell = getenv("SHELL")))
1537 /* The double-fork construct avoids zombie processes and keeps the code
1538 * clean from stupid signal handlers. */
1542 close(ConnectionNumber(dpy));
1544 execl(shell, shell, "-c", arg, (char *)NULL);
1545 fprintf(stderr, "dwm: execl '%s -c %s'", shell, arg);
1554 tag(const char *arg) {
1559 for(i = 0; i < LENGTH(tags); i++)
1560 sel->tags[i] = (NULL == arg);
1561 sel->tags[idxoftag(arg)] = True;
1566 textnw(const char *text, unsigned int len) {
1570 XmbTextExtents(dc.font.set, text, len, NULL, &r);
1573 return XTextWidth(dc.font.xfont, text, len);
1577 textw(const char *text) {
1578 return textnw(text, strlen(text)) + dc.font.height;
1583 unsigned int i, n, nx, ny, nw, nh, mw, th;
1586 domwfact = dozoom = True;
1587 for(n = 0, c = nexttiled(clients); c; c = nexttiled(c->next))
1591 mw = (n == 1) ? waw : mwfact * waw;
1592 th = (n > 1) ? wah / (n - 1) : 0;
1593 if(n > 1 && th < bh)
1598 nw = 0; /* gcc stupidity requires this */
1599 for(i = 0, c = mc = nexttiled(clients); c; c = nexttiled(c->next), i++) {
1601 if(i == 0) { /* master */
1602 nw = mw - 2 * c->border;
1603 nh = wah - 2 * c->border;
1605 else { /* tile window */
1608 nx += mc->w + 2 * mc->border;
1609 nw = waw - nx - 2 * c->border;
1611 if(i + 1 == n) /* remainder */
1612 nh = (way + wah) - ny - 2 * c->border;
1614 nh = th - 2 * c->border;
1616 resize(c, nx, ny, nw, nh, RESIZEHINTS);
1617 if((RESIZEHINTS) && ((c->h < bh) || (c->h > nh) || (c->w < bh) || (c->w > nw)))
1618 /* client doesn't accept size constraints */
1619 resize(c, nx, ny, nw, nh, False);
1620 if(n > 1 && th != wah)
1621 ny = c->y + c->h + 2 * c->border;
1626 togglebar(const char *arg) {
1628 bpos = (BARPOS == BarOff) ? BarTop : BARPOS;
1636 togglefloating(const char *arg) {
1639 sel->isfloating = !sel->isfloating;
1641 resize(sel, sel->x, sel->y, sel->w, sel->h, True);
1646 togglemax(const char *arg) {
1649 if(!sel || sel->isfixed)
1651 if((sel->ismax = !sel->ismax)) {
1652 if((layout->arrange == floating) || sel->isfloating)
1653 sel->wasfloating = True;
1655 togglefloating(NULL);
1656 sel->wasfloating = False;
1662 resize(sel, wax, way, waw - 2 * sel->border, wah - 2 * sel->border, True);
1665 resize(sel, sel->rx, sel->ry, sel->rw, sel->rh, True);
1666 if(!sel->wasfloating)
1667 togglefloating(NULL);
1670 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1674 toggletag(const char *arg) {
1680 sel->tags[i] = !sel->tags[i];
1681 for(j = 0; j < LENGTH(tags) && !sel->tags[j]; j++);
1682 if(j == LENGTH(tags))
1683 sel->tags[i] = True; /* at least one tag must be enabled */
1688 toggleview(const char *arg) {
1692 seltags[i] = !seltags[i];
1693 for(j = 0; j < LENGTH(tags) && !seltags[j]; j++);
1694 if(j == LENGTH(tags))
1695 seltags[i] = True; /* at least one tag must be viewed */
1703 XMoveWindow(dpy, c->win, c->x, c->y);
1704 c->isbanned = False;
1708 unmanage(Client *c) {
1711 wc.border_width = c->oldborder;
1712 /* The server grab construct avoids race conditions. */
1714 XSetErrorHandler(xerrordummy);
1715 XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
1720 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1721 setclientstate(c, WithdrawnState);
1725 XSetErrorHandler(xerror);
1731 unmapnotify(XEvent *e) {
1733 XUnmapEvent *ev = &e->xunmap;
1735 if((c = getclient(ev->window)))
1740 updatebarpos(void) {
1751 XMoveWindow(dpy, barwin, sx, sy);
1755 XMoveWindow(dpy, barwin, sx, sy + wah);
1758 XMoveWindow(dpy, barwin, sx, sy - bh);
1762 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1766 updatesizehints(Client *c) {
1770 if(!XGetWMNormalHints(dpy, c->win, &size, &msize) || !size.flags)
1772 c->flags = size.flags;
1773 if(c->flags & PBaseSize) {
1774 c->basew = size.base_width;
1775 c->baseh = size.base_height;
1777 else if(c->flags & PMinSize) {
1778 c->basew = size.min_width;
1779 c->baseh = size.min_height;
1782 c->basew = c->baseh = 0;
1783 if(c->flags & PResizeInc) {
1784 c->incw = size.width_inc;
1785 c->inch = size.height_inc;
1788 c->incw = c->inch = 0;
1789 if(c->flags & PMaxSize) {
1790 c->maxw = size.max_width;
1791 c->maxh = size.max_height;
1794 c->maxw = c->maxh = 0;
1795 if(c->flags & PMinSize) {
1796 c->minw = size.min_width;
1797 c->minh = size.min_height;
1799 else if(c->flags & PBaseSize) {
1800 c->minw = size.base_width;
1801 c->minh = size.base_height;
1804 c->minw = c->minh = 0;
1805 if(c->flags & PAspect) {
1806 c->minax = size.min_aspect.x;
1807 c->maxax = size.max_aspect.x;
1808 c->minay = size.min_aspect.y;
1809 c->maxay = size.max_aspect.y;
1812 c->minax = c->maxax = c->minay = c->maxay = 0;
1813 c->isfixed = (c->maxw && c->minw && c->maxh && c->minh
1814 && c->maxw == c->minw && c->maxh == c->minh);
1818 updatetitle(Client *c) {
1819 if(!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
1820 gettextprop(c->win, wmatom[WMName], c->name, sizeof c->name);
1823 /* There's no way to check accesses to destroyed windows, thus those cases are
1824 * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
1825 * default error handler, which may call exit. */
1827 xerror(Display *dpy, XErrorEvent *ee) {
1828 if(ee->error_code == BadWindow
1829 || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1830 || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1831 || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1832 || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1833 || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1834 || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1835 || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1837 fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1838 ee->request_code, ee->error_code);
1839 return xerrorxlib(dpy, ee); /* may call exit */
1843 xerrordummy(Display *dsply, XErrorEvent *ee) {
1847 /* Startup Error handler to check if another window manager
1848 * is already running. */
1850 xerrorstart(Display *dsply, XErrorEvent *ee) {
1856 view(const char *arg) {
1859 memcpy(prevtags, seltags, sizeof seltags);
1860 for(i = 0; i < LENGTH(tags); i++)
1861 seltags[i] = (NULL == arg);
1862 seltags[idxoftag(arg)] = True;
1867 viewprevtag(const char *arg) {
1868 static Bool tmp[LENGTH(tags)];
1870 memcpy(tmp, seltags, sizeof seltags);
1871 memcpy(seltags, prevtags, sizeof seltags);
1872 memcpy(prevtags, tmp, sizeof seltags);
1877 zoom(const char *arg) {
1880 if(!sel || !dozoom || sel->isfloating)
1882 if((c = sel) == nexttiled(clients))
1883 if(!(c = nexttiled(c->next)))
1892 main(int argc, char *argv[]) {
1893 if(argc == 2 && !strcmp("-v", argv[1]))
1894 eprint("dwm-"VERSION", © 2006-2007 Anselm R. Garbe, Sander van Dijk, "
1895 "Jukka Salmi, Premysl Hruby, Szabolcs Nagy\n");
1897 eprint("usage: dwm [-v]\n");
1899 setlocale(LC_CTYPE, "");
1900 if(!(dpy = XOpenDisplay(0)))
1901 eprint("dwm: cannot open display\n");
1902 screen = DefaultScreen(dpy);
1903 root = RootWindow(dpy, screen);