1 /* See LICENSE file for copyright and license details.
3 * dynamic window manager is designed like any other X client as well. It is
4 * driven through handling X events. In contrast to other X clients, a window
5 * manager selects for SubstructureRedirectMask on the root window, to receive
6 * events about window (dis-)appearance. Only one X connection at a time is
7 * allowed to select for this event mask.
9 * Calls to fetch an X event from the event queue are blocking. Due reading
10 * status text from standard input, a select()-driven main loop has been
11 * implemented which selects for reads on the X connection and STDIN_FILENO to
12 * handle all data smoothly. The event handlers of dwm are organized in an
13 * array which is accessed whenever a new event has been fetched. This allows
14 * event dispatching in O(1) time.
16 * Each child of the root window is called a client, except windows which have
17 * set the override_redirect flag. Clients are organized in a global
18 * doubly-linked client list, the focus history is remembered through a global
19 * stack list. Each client contains an array of Bools of the same size as the
20 * global tags array to indicate the tags of a client.
22 * Keys and tagging rules are organized as arrays and defined in config.h.
24 * To understand everything else, start reading main().
33 #include <sys/select.h>
34 #include <sys/types.h>
36 #include <X11/cursorfont.h>
37 #include <X11/keysym.h>
38 #include <X11/Xatom.h>
40 #include <X11/Xproto.h>
41 #include <X11/Xutil.h>
44 #define MAX(a, b) ((a) > (b) ? (a) : (b))
45 #define MIN(a, b) ((a) < (b) ? (a) : (b))
46 #define BUTTONMASK (ButtonPressMask|ButtonReleaseMask)
47 #define CLEANMASK(mask) (mask & ~(numlockmask|LockMask))
48 #define LENGTH(x) (sizeof x / sizeof x[0])
50 #define MOUSEMASK (BUTTONMASK|PointerMotionMask)
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;
64 int basew, baseh, incw, inch, maxw, maxh, minw, minh;
65 int minax, maxax, minay, maxay;
67 unsigned int bw, oldbw;
68 Bool isbanned, isfixed, isfloating, isurgent;
78 unsigned long norm[ColLast];
79 unsigned long sel[ColLast];
89 } DC; /* draw context */
94 void (*func)(const char *arg);
100 void (*arrange)(void);
106 const char *instance;
112 /* function declarations */
113 void applyrules(Client *c);
115 void attach(Client *c);
116 void attachstack(Client *c);
118 void buttonpress(XEvent *e);
119 void checkotherwm(void);
121 void configure(Client *c);
122 void configurenotify(XEvent *e);
123 void configurerequest(XEvent *e);
124 unsigned int counttiled(void);
125 void destroynotify(XEvent *e);
126 void detach(Client *c);
127 void detachstack(Client *c);
129 void drawsquare(Bool filled, Bool empty, Bool invert, unsigned long col[ColLast]);
130 void drawtext(const char *text, unsigned long col[ColLast], Bool invert);
131 void *emallocz(unsigned int size);
132 void enternotify(XEvent *e);
133 void eprint(const char *errstr, ...);
134 void expose(XEvent *e);
135 void focus(Client *c);
136 void focusin(XEvent *e);
137 void focusnext(const char *arg);
138 void focusprev(const char *arg);
139 Client *getclient(Window w);
140 unsigned long getcolor(const char *colstr);
141 long getstate(Window w);
142 Bool gettextprop(Window w, Atom atom, char *text, unsigned int size);
143 void grabbuttons(Client *c, Bool focused);
145 unsigned int idxoftag(const char *t);
146 void initfont(const char *fontstr);
147 Bool isoccupied(unsigned int t);
148 Bool isprotodel(Client *c);
149 Bool isurgent(unsigned int t);
150 Bool isvisible(Client *c, Bool *cmp);
151 void keypress(XEvent *e);
152 void killclient(const char *arg);
153 void manage(Window w, XWindowAttributes *wa);
154 void mappingnotify(XEvent *e);
155 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 reapply(const char *arg);
162 void resize(Client *c, int x, int y, int w, int h, Bool sizehints);
163 void resizemouse(Client *c);
167 void setclientstate(Client *c, long state);
168 void setlayout(const char *arg);
169 void setmfact(const char *arg);
171 void spawn(const char *arg);
172 void tag(const char *arg);
173 unsigned int textnw(const char *text, unsigned int len);
174 unsigned int textw(const char *text);
176 void tilehstack(unsigned int n);
177 Client *tilemaster(unsigned int n);
178 void tileresize(Client *c, int x, int y, int w, int h);
180 void tilevstack(unsigned int n);
181 void togglefloating(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 updatebar(void);
188 void updategeom(void);
189 void updatesizehints(Client *c);
190 void updatetitle(Client *c);
191 void updatewmhints(Client *c);
192 void view(const char *arg);
193 void viewprevtag(const char *arg); /* views previous selected tags */
194 int xerror(Display *dpy, XErrorEvent *ee);
195 int xerrordummy(Display *dpy, XErrorEvent *ee);
196 int xerrorstart(Display *dpy, XErrorEvent *ee);
197 void zoom(const char *arg);
201 int screen, sx, sy, sw, sh;
202 int (*xerrorxlib)(Display *, XErrorEvent *);
203 int bx, by, bw, bh, blw, mx, my, mw, mh, tx, ty, tw, th, wx, wy, ww, wh;
206 unsigned int numlockmask = 0;
207 void (*handler[LASTEvent]) (XEvent *) = {
208 [ButtonPress] = buttonpress,
209 [ConfigureRequest] = configurerequest,
210 [ConfigureNotify] = configurenotify,
211 [DestroyNotify] = destroynotify,
212 [EnterNotify] = enternotify,
215 [KeyPress] = keypress,
216 [MappingNotify] = mappingnotify,
217 [MapRequest] = maprequest,
218 [PropertyNotify] = propertynotify,
219 [UnmapNotify] = unmapnotify
221 Atom wmatom[WMLast], netatom[NetLast];
222 Bool otherwm, readin;
225 Client *clients = NULL;
227 Client *stack = NULL;
228 Cursor cursor[CurLast];
232 Layout *lt = layouts;
235 /* configuration, allows nested code to access above variables */
237 #define TAGSZ (LENGTH(tags) * sizeof(Bool))
239 /* function implementations */
242 applyrules(Client *c) {
244 Bool matched = False;
246 XClassHint ch = { 0 };
249 XGetClassHint(dpy, c->win, &ch);
250 for(i = 0; i < LENGTH(rules); i++) {
252 if((!r->title || strstr(c->name, r->title))
253 && (!r->class || (ch.res_class && strstr(ch.res_class, r->class)))
254 && (!r->instance || (ch.res_name && strstr(ch.res_name, r->instance)))) {
255 c->isfloating = r->isfloating;
257 if(r->tag[0] == '*' && r->tag[1] == 0)
258 for(j = 0; j < LENGTH(tags); i++)
261 c->tags[idxoftag(r->tag)] = True;
271 memcpy(c->tags, tagset[seltags], TAGSZ);
278 for(c = clients; c; c = c->next)
279 if(isvisible(c, NULL)) {
281 if(lt->isfloating || c->isfloating)
282 resize(c, c->fx, c->fy, c->fw, c->fh, True);
302 attachstack(Client *c) {
311 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
316 buttonpress(XEvent *e) {
319 XButtonPressedEvent *ev = &e->xbutton;
321 if(ev->window == barwin) {
323 for(i = 0; i < LENGTH(tags); i++) {
326 if(ev->button == Button1) {
327 if(ev->state & MODKEY)
332 else if(ev->button == Button3) {
333 if(ev->state & MODKEY)
341 if((ev->x < x + blw) && ev->button == Button1)
344 else if((c = getclient(ev->window))) {
346 if(CLEANMASK(ev->state) != MODKEY)
348 if(ev->button == Button1) {
352 else if(ev->button == Button2) {
353 if(!lt->isfloating && c->isfloating)
354 togglefloating(NULL);
358 else if(ev->button == Button3 && !c->isfixed) {
368 XSetErrorHandler(xerrorstart);
370 /* this causes an error if some other window manager is running */
371 XSelectInput(dpy, DefaultRootWindow(dpy), 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 XFreeCursor(dpy, cursor[CurNormal]);
396 XFreeCursor(dpy, cursor[CurResize]);
397 XFreeCursor(dpy, cursor[CurMove]);
398 XDestroyWindow(dpy, barwin);
400 XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime);
404 configure(Client *c) {
407 ce.type = ConfigureNotify;
415 ce.border_width = c->bw;
417 ce.override_redirect = False;
418 XSendEvent(dpy, c->win, False, StructureNotifyMask, (XEvent *)&ce);
422 configurenotify(XEvent *e) {
423 XConfigureEvent *ev = &e->xconfigure;
425 if(ev->window == root && (ev->width != sw || ev->height != sh)) {
435 configurerequest(XEvent *e) {
437 XConfigureRequestEvent *ev = &e->xconfigurerequest;
440 if((c = getclient(ev->window))) {
441 if(ev->value_mask & CWBorderWidth)
442 c->bw = ev->border_width;
443 if(c->isfixed || c->isfloating || lt->isfloating) {
444 if(ev->value_mask & CWX)
446 if(ev->value_mask & CWY)
448 if(ev->value_mask & CWWidth)
450 if(ev->value_mask & CWHeight)
452 if((c->x - sx + c->w) > sw && c->isfloating)
453 c->x = sx + (sw / 2 - c->w / 2); /* center in x direction */
454 if((c->y - sy + c->h) > sh && c->isfloating)
455 c->y = sy + (sh / 2 - c->h / 2); /* center in y direction */
456 if((ev->value_mask & (CWX|CWY))
457 && !(ev->value_mask & (CWWidth|CWHeight)))
459 if(isvisible(c, NULL))
460 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h);
468 wc.width = ev->width;
469 wc.height = ev->height;
470 wc.border_width = ev->border_width;
471 wc.sibling = ev->above;
472 wc.stack_mode = ev->detail;
473 XConfigureWindow(dpy, ev->window, ev->value_mask, &wc);
483 for(n = 0, c = nexttiled(clients); c; c = nexttiled(c->next), n++);
488 destroynotify(XEvent *e) {
490 XDestroyWindowEvent *ev = &e->xdestroywindow;
492 if((c = getclient(ev->window)))
499 c->prev->next = c->next;
501 c->next->prev = c->prev;
504 c->next = c->prev = NULL;
508 detachstack(Client *c) {
511 for(tc = &stack; *tc && *tc != c; tc = &(*tc)->snext);
521 for(c = stack; c && !isvisible(c, NULL); c = c->snext);
522 for(i = 0; i < LENGTH(tags); i++) {
523 dc.w = textw(tags[i]);
524 if(tagset[seltags][i]) {
525 drawtext(tags[i], dc.sel, isurgent(i));
526 drawsquare(c && c->tags[i], isoccupied(i), isurgent(i), dc.sel);
529 drawtext(tags[i], dc.norm, isurgent(i));
530 drawsquare(c && c->tags[i], isoccupied(i), isurgent(i), dc.norm);
536 drawtext(lt->symbol, dc.norm, False);
547 drawtext(stext, dc.norm, False);
548 if((dc.w = dc.x - x) > bh) {
551 drawtext(c->name, dc.sel, False);
552 drawsquare(False, c->isfloating, False, dc.sel);
555 drawtext(NULL, dc.norm, False);
557 XCopyArea(dpy, dc.drawable, barwin, dc.gc, 0, 0, bw, bh, 0, 0);
562 drawsquare(Bool filled, Bool empty, Bool invert, unsigned long col[ColLast]) {
565 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
567 gcv.foreground = col[invert ? ColBG : ColFG];
568 XChangeGC(dpy, dc.gc, GCForeground, &gcv);
569 x = (dc.font.ascent + dc.font.descent + 2) / 4;
573 r.width = r.height = x + 1;
574 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
577 r.width = r.height = x;
578 XDrawRectangles(dpy, dc.drawable, dc.gc, &r, 1);
583 drawtext(const char *text, unsigned long col[ColLast], Bool invert) {
585 unsigned int len, olen;
586 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
589 XSetForeground(dpy, dc.gc, col[invert ? ColFG : ColBG]);
590 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
594 len = MIN(olen, sizeof buf);
595 memcpy(buf, text, len);
597 h = dc.font.ascent + dc.font.descent;
598 y = dc.y + (dc.h / 2) - (h / 2) + dc.font.ascent;
600 /* shorten text if necessary */
601 for(; len && (w = textnw(buf, len)) > dc.w - h; len--);
612 XSetForeground(dpy, dc.gc, col[invert ? ColBG : ColFG]);
614 XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
616 XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
620 emallocz(unsigned int size) {
621 void *res = calloc(1, size);
624 eprint("fatal: could not malloc() %u bytes\n", size);
629 enternotify(XEvent *e) {
631 XCrossingEvent *ev = &e->xcrossing;
633 if((ev->mode != NotifyNormal || ev->detail == NotifyInferior) && ev->window != root)
635 if((c = getclient(ev->window)))
642 eprint(const char *errstr, ...) {
645 va_start(ap, errstr);
646 vfprintf(stderr, errstr, ap);
653 XExposeEvent *ev = &e->xexpose;
655 if(ev->count == 0 && (ev->window == barwin))
661 if(!c || (c && !isvisible(c, NULL)))
662 for(c = stack; c && !isvisible(c, NULL); c = c->snext);
663 if(sel && sel != c) {
664 grabbuttons(sel, False);
665 XSetWindowBorder(dpy, sel->win, dc.norm[ColBorder]);
670 grabbuttons(c, True);
674 XSetWindowBorder(dpy, c->win, dc.sel[ColBorder]);
675 XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
678 XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
683 focusin(XEvent *e) { /* there are some broken focus acquiring clients */
684 XFocusChangeEvent *ev = &e->xfocus;
686 if(sel && ev->window != sel->win)
687 XSetInputFocus(dpy, sel->win, RevertToPointerRoot, CurrentTime);
691 focusnext(const char *arg) {
696 for(c = sel->next; c && !isvisible(c, arg ? sel->tags : NULL); c = c->next);
698 for(c = clients; c && !isvisible(c, arg ? sel->tags : NULL); c = c->next);
706 focusprev(const char *arg) {
711 for(c = sel->prev; c && !isvisible(c, arg ? sel->tags : NULL); c = c->prev);
713 for(c = clients; c && c->next; c = c->next);
714 for(; c && !isvisible(c, arg ? sel->tags : NULL); c = c->prev);
723 getclient(Window w) {
726 for(c = clients; c && c->win != w; c = c->next);
731 getcolor(const char *colstr) {
732 Colormap cmap = DefaultColormap(dpy, screen);
735 if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
736 eprint("error, cannot allocate color '%s'\n", colstr);
744 unsigned char *p = NULL;
745 unsigned long n, extra;
748 status = XGetWindowProperty(dpy, w, wmatom[WMState], 0L, 2L, False, wmatom[WMState],
749 &real, &format, &n, &extra, (unsigned char **)&p);
750 if(status != Success)
759 gettextprop(Window w, Atom atom, char *text, unsigned int size) {
764 if(!text || size == 0)
767 XGetTextProperty(dpy, w, &name, atom);
770 if(name.encoding == XA_STRING)
771 strncpy(text, (char *)name.value, size - 1);
773 if(XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success
775 strncpy(text, *list, size - 1);
776 XFreeStringList(list);
779 text[size - 1] = '\0';
785 grabbuttons(Client *c, Bool focused) {
787 unsigned int buttons[] = { Button1, Button2, Button3 };
788 unsigned int modifiers[] = { MODKEY, MODKEY|LockMask, MODKEY|numlockmask,
789 MODKEY|numlockmask|LockMask} ;
791 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
793 for(i = 0; i < LENGTH(buttons); i++)
794 for(j = 0; j < LENGTH(modifiers); j++)
795 XGrabButton(dpy, buttons[i], modifiers[j], c->win, False,
796 BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
798 XGrabButton(dpy, AnyButton, AnyModifier, c->win, False,
799 BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
806 XModifierKeymap *modmap;
808 /* init modifier map */
809 modmap = XGetModifierMapping(dpy);
810 for(i = 0; i < 8; i++)
811 for(j = 0; j < modmap->max_keypermod; j++) {
812 if(modmap->modifiermap[i * modmap->max_keypermod + j] == XKeysymToKeycode(dpy, XK_Num_Lock))
813 numlockmask = (1 << i);
815 XFreeModifiermap(modmap);
817 XUngrabKey(dpy, AnyKey, AnyModifier, root);
818 for(i = 0; i < LENGTH(keys); i++) {
819 code = XKeysymToKeycode(dpy, keys[i].keysym);
820 XGrabKey(dpy, code, keys[i].mod, root, True,
821 GrabModeAsync, GrabModeAsync);
822 XGrabKey(dpy, code, keys[i].mod|LockMask, root, True,
823 GrabModeAsync, GrabModeAsync);
824 XGrabKey(dpy, code, keys[i].mod|numlockmask, root, True,
825 GrabModeAsync, GrabModeAsync);
826 XGrabKey(dpy, code, keys[i].mod|numlockmask|LockMask, root, True,
827 GrabModeAsync, GrabModeAsync);
832 idxoftag(const char *t) {
835 for(i = 0; (i < LENGTH(tags)) && t && strcmp(tags[i], t); i++);
836 return (i < LENGTH(tags)) ? i : 0;
840 initfont(const char *fontstr) {
841 char *def, **missing;
846 XFreeFontSet(dpy, dc.font.set);
847 dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
850 fprintf(stderr, "dwm: missing fontset: %s\n", missing[n]);
851 XFreeStringList(missing);
854 XFontSetExtents *font_extents;
855 XFontStruct **xfonts;
857 dc.font.ascent = dc.font.descent = 0;
858 font_extents = XExtentsOfFontSet(dc.font.set);
859 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
860 for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
861 dc.font.ascent = MAX(dc.font.ascent, (*xfonts)->ascent);
862 dc.font.descent = MAX(dc.font.descent,(*xfonts)->descent);
868 XFreeFont(dpy, dc.font.xfont);
869 dc.font.xfont = NULL;
870 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr))
871 && !(dc.font.xfont = XLoadQueryFont(dpy, "fixed")))
872 eprint("error, cannot load font: '%s'\n", fontstr);
873 dc.font.ascent = dc.font.xfont->ascent;
874 dc.font.descent = dc.font.xfont->descent;
876 dc.font.height = dc.font.ascent + dc.font.descent;
880 isoccupied(unsigned int t) {
883 for(c = clients; c; c = c->next)
890 isprotodel(Client *c) {
895 if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
896 for(i = 0; !ret && i < n; i++)
897 if(protocols[i] == wmatom[WMDelete])
905 isurgent(unsigned int t) {
908 for(c = clients; c; c = c->next)
909 if(c->isurgent && c->tags[t])
915 isvisible(Client *c, Bool *cmp) {
919 cmp = tagset[seltags];
920 for(i = 0; i < LENGTH(tags); i++)
921 if(c->tags[i] && cmp[i])
927 keypress(XEvent *e) {
933 keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
934 for(i = 0; i < LENGTH(keys); i++)
935 if(keysym == keys[i].keysym
936 && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state))
939 keys[i].func(keys[i].arg);
944 killclient(const char *arg) {
949 if(isprotodel(sel)) {
950 ev.type = ClientMessage;
951 ev.xclient.window = sel->win;
952 ev.xclient.message_type = wmatom[WMProtocols];
953 ev.xclient.format = 32;
954 ev.xclient.data.l[0] = wmatom[WMDelete];
955 ev.xclient.data.l[1] = CurrentTime;
956 XSendEvent(dpy, sel->win, False, NoEventMask, &ev);
959 XKillClient(dpy, sel->win);
963 manage(Window w, XWindowAttributes *wa) {
964 Client *c, *t = NULL;
969 c = emallocz(sizeof(Client));
970 c->tags = emallocz(TAGSZ);
976 c->w = c->fw = wa->width;
977 c->h = c->fh = wa->height;
978 c->oldbw = wa->border_width;
979 if(c->w == sw && c->h == sh) {
982 c->bw = wa->border_width;
985 if(c->x + c->w + 2 * c->bw > wx + ww)
986 c->x = wx + ww - c->w - 2 * c->bw;
987 if(c->y + c->h + 2 * c->bw > wy + wh)
988 c->y = wy + wh - c->h - 2 * c->bw;
989 c->x = MAX(c->x, wx);
990 c->y = MAX(c->y, wy);
996 wc.border_width = c->bw;
997 XConfigureWindow(dpy, w, CWBorderWidth, &wc);
998 XSetWindowBorder(dpy, w, dc.norm[ColBorder]);
999 configure(c); /* propagates border_width, if size doesn't change */
1001 XSelectInput(dpy, w, EnterWindowMask|FocusChangeMask|PropertyChangeMask|StructureNotifyMask);
1002 grabbuttons(c, False);
1004 if((rettrans = XGetTransientForHint(dpy, w, &trans) == Success))
1005 for(t = clients; t && t->win != trans; t = t->next);
1007 memcpy(c->tags, t->tags, TAGSZ);
1011 c->isfloating = (rettrans == Success) || c->isfixed;
1014 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h); /* some windows require this */
1016 XMapWindow(dpy, c->win);
1017 setclientstate(c, NormalState);
1022 mappingnotify(XEvent *e) {
1023 XMappingEvent *ev = &e->xmapping;
1025 XRefreshKeyboardMapping(ev);
1026 if(ev->request == MappingKeyboard)
1031 maprequest(XEvent *e) {
1032 static XWindowAttributes wa;
1033 XMapRequestEvent *ev = &e->xmaprequest;
1035 if(!XGetWindowAttributes(dpy, ev->window, &wa))
1037 if(wa.override_redirect)
1039 if(!getclient(ev->window))
1040 manage(ev->window, &wa);
1047 for(c = clients; c; c = c->next)
1048 if((lt->isfloating || !c->isfloating) && isvisible(c, NULL))
1049 resize(c, wx, wy, ww - 2 * c->bw, wh - 2 * c->bw, RESIZEHINTS);
1053 movemouse(Client *c) {
1054 int x1, y1, ocx, ocy, di, nx, ny;
1061 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1062 None, cursor[CurMove], CurrentTime) != GrabSuccess)
1064 XQueryPointer(dpy, root, &dummy, &dummy, &x1, &y1, &di, &di, &dui);
1066 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
1069 XUngrabPointer(dpy, CurrentTime);
1071 case ConfigureRequest:
1074 handler[ev.type](&ev);
1078 nx = ocx + (ev.xmotion.x - x1);
1079 ny = ocy + (ev.xmotion.y - y1);
1080 if(abs(wx - nx) < SNAP)
1082 else if(abs((wx + ww) - (nx + c->w + 2 * c->bw)) < SNAP)
1083 nx = wx + ww - c->w - 2 * c->bw;
1084 if(abs(wy - ny) < SNAP)
1086 else if(abs((wy + wh) - (ny + c->h + 2 * c->bw)) < SNAP)
1087 ny = wy + wh - c->h - 2 * c->bw;
1088 if(!c->isfloating && !lt->isfloating && (abs(nx - c->x) > SNAP || abs(ny - c->y) > SNAP))
1089 togglefloating(NULL);
1090 if(lt->isfloating || c->isfloating) {
1093 resize(c, nx, ny, c->w, c->h, False);
1101 nexttiled(Client *c) {
1102 for(; c && (c->isfloating || !isvisible(c, NULL)); c = c->next);
1107 propertynotify(XEvent *e) {
1110 XPropertyEvent *ev = &e->xproperty;
1112 if(ev->state == PropertyDelete)
1113 return; /* ignore */
1114 if((c = getclient(ev->window))) {
1117 case XA_WM_TRANSIENT_FOR:
1118 XGetTransientForHint(dpy, c->win, &trans);
1119 if(!c->isfloating && (c->isfloating = (getclient(trans) != NULL)))
1122 case XA_WM_NORMAL_HINTS:
1130 if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
1139 quit(const char *arg) {
1140 readin = running = False;
1144 reapply(const char *arg) {
1147 for(c = clients; c; c = c->next) {
1148 memset(c->tags, 0, TAGSZ);
1155 resize(Client *c, int x, int y, int w, int h, Bool sizehints) {
1159 /* set minimum possible */
1163 /* temporarily remove base dimensions */
1167 /* adjust for aspect limits */
1168 if(c->minax != c->maxax && c->minay != c->maxay
1169 && c->minax > 0 && c->maxax > 0 && c->minay > 0 && c->maxay > 0) {
1170 if(w * c->maxay > h * c->maxax)
1171 w = h * c->maxax / c->maxay;
1172 else if(w * c->minay < h * c->minax)
1173 h = w * c->minay / c->minax;
1176 /* adjust for increment value */
1182 /* restore base dimensions */
1186 w = MAX(w, c->minw);
1187 h = MAX(h, c->minh);
1190 w = MIN(w, c->maxw);
1193 h = MIN(h, c->maxh);
1195 if(w <= 0 || h <= 0)
1198 x = sw - w - 2 * c->bw;
1200 y = sh - h - 2 * c->bw;
1201 if(x + w + 2 * c->bw < sx)
1203 if(y + h + 2 * c->bw < sy)
1205 if(c->x != x || c->y != y || c->w != w || c->h != h) {
1208 c->w = wc.width = w;
1209 c->h = wc.height = h;
1210 wc.border_width = c->bw;
1211 XConfigureWindow(dpy, c->win,
1212 CWX|CWY|CWWidth|CWHeight|CWBorderWidth, &wc);
1219 resizemouse(Client *c) {
1226 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1227 None, cursor[CurResize], CurrentTime) != GrabSuccess)
1229 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->bw - 1, c->h + c->bw - 1);
1231 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask , &ev);
1234 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0,
1235 c->w + c->bw - 1, c->h + c->bw - 1);
1236 XUngrabPointer(dpy, CurrentTime);
1237 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1239 case ConfigureRequest:
1242 handler[ev.type](&ev);
1246 nw = MAX(ev.xmotion.x - ocx - 2 * c->bw + 1, 1);
1247 nh = MAX(ev.xmotion.y - ocy - 2 * c->bw + 1, 1);
1248 if(!c->isfloating && !lt->isfloating && (abs(nw - c->w) > SNAP || abs(nh - c->h) > SNAP)) {
1251 togglefloating(NULL);
1253 if((lt->isfloating) || c->isfloating) {
1254 resize(c, c->x, c->y, nw, nh, True);
1272 if(sel->isfloating || lt->isfloating)
1273 XRaiseWindow(dpy, sel->win);
1274 if(!lt->isfloating) {
1275 wc.stack_mode = Below;
1276 wc.sibling = barwin;
1277 for(c = stack; c; c = c->snext)
1278 if(!c->isfloating && isvisible(c, NULL)) {
1279 XConfigureWindow(dpy, c->win, CWSibling|CWStackMode, &wc);
1280 wc.sibling = c->win;
1284 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1290 char sbuf[sizeof stext];
1293 unsigned int len, offset;
1296 /* main event loop, also reads status text from stdin */
1298 xfd = ConnectionNumber(dpy);
1301 len = sizeof stext - 1;
1302 sbuf[len] = stext[len] = '\0'; /* 0-terminator is never touched */
1306 FD_SET(STDIN_FILENO, &rd);
1308 if(select(xfd + 1, &rd, NULL, NULL, NULL) == -1) {
1311 eprint("select failed\n");
1313 if(FD_ISSET(STDIN_FILENO, &rd)) {
1314 switch((r = read(STDIN_FILENO, sbuf + offset, len - offset))) {
1316 strncpy(stext, strerror(errno), len);
1320 strncpy(stext, "EOF", 4);
1324 for(p = sbuf + offset; r > 0; p++, r--, offset++)
1325 if(*p == '\n' || *p == '\0') {
1327 strncpy(stext, sbuf, len);
1328 p += r - 1; /* p is sbuf + offset + r - 1 */
1329 for(r = 0; *(p - r) && *(p - r) != '\n'; r++);
1332 memmove(sbuf, p - r + 1, r);
1339 while(XPending(dpy)) {
1340 XNextEvent(dpy, &ev);
1341 if(handler[ev.type])
1342 (handler[ev.type])(&ev); /* call handler */
1349 unsigned int i, num;
1350 Window *wins, d1, d2;
1351 XWindowAttributes wa;
1354 if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1355 for(i = 0; i < num; i++) {
1356 if(!XGetWindowAttributes(dpy, wins[i], &wa)
1357 || wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1359 if(wa.map_state == IsViewable || getstate(wins[i]) == IconicState)
1360 manage(wins[i], &wa);
1362 for(i = 0; i < num; i++) { /* now the transients */
1363 if(!XGetWindowAttributes(dpy, wins[i], &wa))
1365 if(XGetTransientForHint(dpy, wins[i], &d1)
1366 && (wa.map_state == IsViewable || getstate(wins[i]) == IconicState))
1367 manage(wins[i], &wa);
1375 setclientstate(Client *c, long state) {
1376 long data[] = {state, None};
1378 XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1379 PropModeReplace, (unsigned char *)data, 2);
1383 setlayout(const char *arg) {
1387 if(++lt == &layouts[LENGTH(layouts)])
1391 for(i = 0; i < LENGTH(layouts); i++)
1392 if(!strcmp(arg, layouts[i].symbol))
1394 if(i == LENGTH(layouts))
1405 setmfact(const char *arg) {
1413 d = strtod(arg, NULL);
1414 if(arg[0] == '-' || arg[0] == '+')
1416 if(d < 0.1 || d > 0.9)
1427 XSetWindowAttributes wa;
1430 screen = DefaultScreen(dpy);
1431 root = RootWindow(dpy, screen);
1435 sw = DisplayWidth(dpy, screen);
1436 sh = DisplayHeight(dpy, screen);
1437 bh = dc.font.height + 2;
1442 wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1443 wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1444 wmatom[WMName] = XInternAtom(dpy, "WM_NAME", False);
1445 wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1446 netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1447 netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1450 wa.cursor = cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1451 cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1452 cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1454 /* init appearance */
1455 dc.norm[ColBorder] = getcolor(NORMBORDERCOLOR);
1456 dc.norm[ColBG] = getcolor(NORMBGCOLOR);
1457 dc.norm[ColFG] = getcolor(NORMFGCOLOR);
1458 dc.sel[ColBorder] = getcolor(SELBORDERCOLOR);
1459 dc.sel[ColBG] = getcolor(SELBGCOLOR);
1460 dc.sel[ColFG] = getcolor(SELFGCOLOR);
1463 dc.drawable = XCreatePixmap(dpy, root, DisplayWidth(dpy, screen), bh, DefaultDepth(dpy, screen));
1464 dc.gc = XCreateGC(dpy, root, 0, 0);
1465 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
1467 XSetFont(dpy, dc.gc, dc.font.xfont->fid);
1470 tagset[0] = emallocz(TAGSZ);
1471 tagset[1] = emallocz(TAGSZ);
1472 tagset[0][0] = tagset[1][0] = True;
1475 for(blw = i = 0; LENGTH(layouts) > 1 && i < LENGTH(layouts); i++) {
1476 w = textw(layouts[i].symbol);
1480 wa.override_redirect = 1;
1481 wa.background_pixmap = ParentRelative;
1482 wa.event_mask = ButtonPressMask|ExposureMask;
1484 barwin = XCreateWindow(dpy, root, bx, by, bw, bh, 0, DefaultDepth(dpy, screen),
1485 CopyFromParent, DefaultVisual(dpy, screen),
1486 CWOverrideRedirect|CWBackPixmap|CWEventMask, &wa);
1487 XDefineCursor(dpy, barwin, cursor[CurNormal]);
1488 XMapRaised(dpy, barwin);
1489 strcpy(stext, "dwm-"VERSION);
1492 /* EWMH support per view */
1493 XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1494 PropModeReplace, (unsigned char *) netatom, NetLast);
1496 /* select for events */
1497 wa.event_mask = SubstructureRedirectMask|SubstructureNotifyMask
1498 |EnterWindowMask|LeaveWindowMask|StructureNotifyMask;
1499 XChangeWindowAttributes(dpy, root, CWEventMask|CWCursor, &wa);
1500 XSelectInput(dpy, root, wa.event_mask);
1508 spawn(const char *arg) {
1509 static char *shell = NULL;
1511 if(!shell && !(shell = getenv("SHELL")))
1515 /* The double-fork construct avoids zombie processes and keeps the code
1516 * clean from stupid signal handlers. */
1520 close(ConnectionNumber(dpy));
1522 execl(shell, shell, "-c", arg, (char *)NULL);
1523 fprintf(stderr, "dwm: execl '%s -c %s'", shell, arg);
1532 tag(const char *arg) {
1537 for(i = 0; i < LENGTH(tags); i++)
1538 sel->tags[i] = (arg == NULL);
1539 sel->tags[idxoftag(arg)] = True;
1544 textnw(const char *text, unsigned int len) {
1548 XmbTextExtents(dc.font.set, text, len, NULL, &r);
1551 return XTextWidth(dc.font.xfont, text, len);
1555 textw(const char *text) {
1556 return textnw(text, strlen(text)) + dc.font.height;
1562 unsigned int i, n = counttiled();
1576 for(i = 0, c = nexttiled(c->next); c; c = nexttiled(c->next), i++) {
1577 if(i + 1 == n) /* remainder */
1578 tileresize(c, x, ty, (tx + tw) - x - 2 * c->bw, th - 2 * c->bw);
1580 tileresize(c, x, ty, w - 2 * c->bw, th - 2 * c->bw);
1582 x = c->x + c->w + 2 * c->bw;
1587 tilemaster(unsigned int n) {
1588 Client *c = nexttiled(clients);
1591 tileresize(c, wx, wy, ww - 2 * c->bw, wh - 2 * c->bw);
1593 tileresize(c, mx, my, mw - 2 * c->bw, mh - 2 * c->bw);
1598 tileresize(Client *c, int x, int y, int w, int h) {
1599 resize(c, x, y, w, h, RESIZEHINTS);
1600 if((RESIZEHINTS) && ((c->h < bh) || (c->h > h) || (c->w < bh) || (c->w > w)))
1601 /* client doesn't accept size constraints */
1602 resize(c, x, y, w, h, False);
1608 unsigned int i, n = counttiled();
1622 for(i = 0, c = nexttiled(c->next); c; c = nexttiled(c->next), i++) {
1623 if(i + 1 == n) /* remainder */
1624 tileresize(c, tx, y, tw - 2 * c->bw, (ty + th) - y - 2 * c->bw);
1626 tileresize(c, tx, y, tw - 2 * c->bw, h - 2 * c->bw);
1628 y = c->y + c->h + 2 * c->bw;
1633 togglefloating(const char *arg) {
1636 sel->isfloating = !sel->isfloating;
1638 resize(sel, sel->x, sel->y, sel->w, sel->h, True);
1643 toggletag(const char *arg) {
1649 sel->tags[i] = !sel->tags[i];
1650 for(j = 0; j < LENGTH(tags) && !sel->tags[j]; j++);
1651 if(j == LENGTH(tags))
1652 sel->tags[i] = True; /* at least one tag must be enabled */
1657 toggleview(const char *arg) {
1661 tagset[seltags][i] = !tagset[seltags][i];
1662 for(j = 0; j < LENGTH(tags) && !tagset[seltags][j]; j++);
1663 if(j == LENGTH(tags))
1664 tagset[seltags][i] = True; /* at least one tag must be viewed */
1672 XMoveWindow(dpy, c->win, c->x, c->y);
1673 c->isbanned = False;
1677 unmanage(Client *c) {
1680 wc.border_width = c->oldbw;
1681 /* The server grab construct avoids race conditions. */
1683 XSetErrorHandler(xerrordummy);
1684 XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
1689 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1690 setclientstate(c, WithdrawnState);
1694 XSetErrorHandler(xerror);
1700 unmapnotify(XEvent *e) {
1702 XUnmapEvent *ev = &e->xunmap;
1704 if((c = getclient(ev->window)))
1710 if(dc.drawable != 0)
1711 XFreePixmap(dpy, dc.drawable);
1712 dc.drawable = XCreatePixmap(dpy, root, bw, bh, DefaultDepth(dpy, screen));
1713 XMoveResizeWindow(dpy, barwin, bx, by, bw, bh);
1724 /* window area geometry */
1730 /* master area geometry */
1736 /* tile area geometry */
1744 updatesizehints(Client *c) {
1748 if(!XGetWMNormalHints(dpy, c->win, &size, &msize) || !size.flags)
1750 c->flags = size.flags;
1751 if(c->flags & PBaseSize) {
1752 c->basew = size.base_width;
1753 c->baseh = size.base_height;
1755 else if(c->flags & PMinSize) {
1756 c->basew = size.min_width;
1757 c->baseh = size.min_height;
1760 c->basew = c->baseh = 0;
1761 if(c->flags & PResizeInc) {
1762 c->incw = size.width_inc;
1763 c->inch = size.height_inc;
1766 c->incw = c->inch = 0;
1767 if(c->flags & PMaxSize) {
1768 c->maxw = size.max_width;
1769 c->maxh = size.max_height;
1772 c->maxw = c->maxh = 0;
1773 if(c->flags & PMinSize) {
1774 c->minw = size.min_width;
1775 c->minh = size.min_height;
1777 else if(c->flags & PBaseSize) {
1778 c->minw = size.base_width;
1779 c->minh = size.base_height;
1782 c->minw = c->minh = 0;
1783 if(c->flags & PAspect) {
1784 c->minax = size.min_aspect.x;
1785 c->maxax = size.max_aspect.x;
1786 c->minay = size.min_aspect.y;
1787 c->maxay = size.max_aspect.y;
1790 c->minax = c->maxax = c->minay = c->maxay = 0;
1791 c->isfixed = (c->maxw && c->minw && c->maxh && c->minh
1792 && c->maxw == c->minw && c->maxh == c->minh);
1796 updatetitle(Client *c) {
1797 if(!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
1798 gettextprop(c->win, wmatom[WMName], c->name, sizeof c->name);
1802 updatewmhints(Client *c) {
1805 if((wmh = XGetWMHints(dpy, c->win))) {
1807 sel->isurgent = False;
1809 c->isurgent = (wmh->flags & XUrgencyHint) ? True : False;
1815 view(const char *arg) {
1816 seltags ^= 1; /* toggle sel tagset */
1817 memset(tagset[seltags], (NULL == arg), TAGSZ);
1818 tagset[seltags][idxoftag(arg)] = True;
1823 viewprevtag(const char *arg) {
1824 seltags ^= 1; /* toggle sel tagset */
1828 /* There's no way to check accesses to destroyed windows, thus those cases are
1829 * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
1830 * default error handler, which may call exit. */
1832 xerror(Display *dpy, XErrorEvent *ee) {
1833 if(ee->error_code == BadWindow
1834 || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1835 || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1836 || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1837 || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1838 || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1839 || (ee->request_code == X_GrabButton && ee->error_code == BadAccess)
1840 || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1841 || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1843 fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1844 ee->request_code, ee->error_code);
1845 return xerrorxlib(dpy, ee); /* may call exit */
1849 xerrordummy(Display *dpy, XErrorEvent *ee) {
1853 /* Startup Error handler to check if another window manager
1854 * is already running. */
1856 xerrorstart(Display *dpy, XErrorEvent *ee) {
1862 zoom(const char *arg) {
1865 if(c == nexttiled(clients))
1866 if(!c || !(c = nexttiled(c->next)))
1868 if(!lt->isfloating && !sel->isfloating) {
1877 main(int argc, char *argv[]) {
1878 if(argc == 2 && !strcmp("-v", argv[1]))
1879 eprint("dwm-"VERSION", © 2006-2008 dwm engineers, see LICENSE for details\n");
1881 eprint("usage: dwm [-v]\n");
1883 setlocale(LC_CTYPE, "");
1884 if(!(dpy = XOpenDisplay(0)))
1885 eprint("dwm: cannot open display\n");