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)
52 enum { CurNormal, CurResize, CurMove, CurLast }; /* cursor */
53 enum { ColBorder, ColFG, ColBG, ColLast }; /* color */
54 enum { NetSupported, NetWMName, NetLast }; /* EWMH atoms */
55 enum { WMProtocols, WMDelete, WMName, WMState, WMLast };/* default atoms */
58 typedef struct Client Client;
63 int basew, baseh, incw, inch, maxw, maxh, minw, minh;
64 int minax, maxax, minay, maxay;
66 unsigned int border, oldborder;
67 Bool isbanned, isfixed, isfloating, isurgent;
77 unsigned long norm[ColLast];
78 unsigned long sel[ColLast];
88 } DC; /* draw context */
93 void (*func)(const char *arg);
99 void (*arrange)(void);
108 /* function declarations */
109 void applyrules(Client *c);
111 void attach(Client *c);
112 void attachstack(Client *c);
114 void buttonpress(XEvent *e);
115 void checkotherwm(void);
117 void configure(Client *c);
118 void configurenotify(XEvent *e);
119 void configurerequest(XEvent *e);
120 void destroynotify(XEvent *e);
121 void detach(Client *c);
122 void detachstack(Client *c);
124 void drawsquare(Bool filled, Bool empty, Bool invert, unsigned long col[ColLast]);
125 void drawtext(const char *text, unsigned long col[ColLast], Bool invert);
126 void *emallocz(unsigned int size);
127 void enternotify(XEvent *e);
128 void eprint(const char *errstr, ...);
129 void expose(XEvent *e);
130 void floating(void); /* default floating layout */
131 void focus(Client *c);
132 void focusin(XEvent *e);
133 void focusnext(const char *arg);
134 void focusprev(const char *arg);
135 Client *getclient(Window w);
136 unsigned long getcolor(const char *colstr);
137 long getstate(Window w);
138 Bool gettextprop(Window w, Atom atom, char *text, unsigned int size);
139 void grabbuttons(Client *c, Bool focused);
141 unsigned int idxoftag(const char *t);
142 void initfont(const char *fontstr);
143 Bool isoccupied(unsigned int t);
144 Bool isprotodel(Client *c);
145 Bool isurgent(unsigned int t);
146 Bool isvisible(Client *c);
147 void keypress(XEvent *e);
148 void killclient(const char *arg);
149 void manage(Window w, XWindowAttributes *wa);
150 void mappingnotify(XEvent *e);
151 void maprequest(XEvent *e);
153 void movemouse(Client *c);
154 Client *nexttiled(Client *c);
155 void propertynotify(XEvent *e);
156 void quit(const char *arg);
157 void reapply(const char *arg);
158 void resize(Client *c, int x, int y, int w, int h, Bool sizehints);
159 void resizemouse(Client *c);
163 void setclientstate(Client *c, long state);
164 void setlayout(const char *arg);
166 void spawn(const char *arg);
167 void tag(const char *arg);
168 unsigned int textnw(const char *text, unsigned int len);
169 unsigned int textw(const char *text);
171 void togglefloating(const char *arg);
172 void toggletag(const char *arg);
173 void toggleview(const char *arg);
174 void unban(Client *c);
175 void unmanage(Client *c);
176 void unmapnotify(XEvent *e);
177 void updatesizehints(Client *c);
178 void updatetitle(Client *c);
179 void updatewmhints(Client *c);
180 void view(const char *arg);
181 void viewprevtag(const char *arg); /* views previous selected tags */
182 int xerror(Display *dpy, XErrorEvent *ee);
183 int xerrordummy(Display *dpy, XErrorEvent *ee);
184 int xerrorstart(Display *dpy, XErrorEvent *ee);
185 void zoom(const char *arg);
188 char stext[256], buf[256];
189 int screen, sx, sy, sw, sh;
190 int (*xerrorxlib)(Display *, XErrorEvent *);
191 unsigned int bh, blw = 0;
192 unsigned int numlockmask = 0;
193 void (*handler[LASTEvent]) (XEvent *) = {
194 [ButtonPress] = buttonpress,
195 [ConfigureRequest] = configurerequest,
196 [ConfigureNotify] = configurenotify,
197 [DestroyNotify] = destroynotify,
198 [EnterNotify] = enternotify,
201 [KeyPress] = keypress,
202 [MappingNotify] = mappingnotify,
203 [MapRequest] = maprequest,
204 [PropertyNotify] = propertynotify,
205 [UnmapNotify] = unmapnotify
207 Atom wmatom[WMLast], netatom[NetLast];
209 Bool otherwm, readin;
213 Client *clients = NULL;
215 Client *stack = NULL;
216 Cursor cursor[CurLast];
222 /* configuration, allows nested code to access above variables */
224 #define TAGSZ (LENGTH(tags) * sizeof(Bool))
225 static Bool tmp[LENGTH(tags)];
227 /* function implementations */
230 applyrules(Client *c) {
232 Bool matched = False;
234 XClassHint ch = { 0 };
237 XGetClassHint(dpy, c->win, &ch);
238 for(i = 0; i < LENGTH(rules); i++) {
240 if(strstr(c->name, r->prop)
241 || (ch.res_class && strstr(ch.res_class, r->prop))
242 || (ch.res_name && strstr(ch.res_name, r->prop)))
244 c->isfloating = r->isfloating;
246 c->tags[idxoftag(r->tag)] = True;
256 memcpy(c->tags, seltags, TAGSZ);
263 for(c = clients; c; c = c->next)
283 attachstack(Client *c) {
292 XMoveWindow(dpy, c->win, c->x + 3 * sw, c->y);
297 buttonpress(XEvent *e) {
300 XButtonPressedEvent *ev = &e->xbutton;
302 if(ev->window == barwin) {
304 for(i = 0; i < LENGTH(tags); i++) {
307 if(ev->button == Button1) {
308 if(ev->state & MODKEY)
313 else if(ev->button == Button3) {
314 if(ev->state & MODKEY)
323 else if((c = getclient(ev->window))) {
325 if(CLEANMASK(ev->state) != MODKEY)
327 if(ev->button == Button1) {
331 else if(ev->button == Button2) {
332 if((floating != lt->arrange) && c->isfloating)
333 togglefloating(NULL);
337 else if(ev->button == Button3 && !c->isfixed) {
347 XSetErrorHandler(xerrorstart);
349 /* this causes an error if some other window manager is running */
350 XSelectInput(dpy, DefaultRootWindow(dpy), SubstructureRedirectMask);
353 eprint("dwm: another window manager is already running\n");
355 XSetErrorHandler(NULL);
356 xerrorxlib = XSetErrorHandler(xerror);
368 XFreeFontSet(dpy, dc.font.set);
370 XFreeFont(dpy, dc.font.xfont);
371 XUngrabKey(dpy, AnyKey, AnyModifier, root);
372 XFreePixmap(dpy, dc.drawable);
374 XFreeCursor(dpy, cursor[CurNormal]);
375 XFreeCursor(dpy, cursor[CurResize]);
376 XFreeCursor(dpy, cursor[CurMove]);
377 XDestroyWindow(dpy, barwin);
379 XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime);
383 configure(Client *c) {
386 ce.type = ConfigureNotify;
394 ce.border_width = c->border;
396 ce.override_redirect = False;
397 XSendEvent(dpy, c->win, False, StructureNotifyMask, (XEvent *)&ce);
401 configurenotify(XEvent *e) {
402 XConfigureEvent *ev = &e->xconfigure;
404 if(ev->window == root && (ev->width != sw || ev->height != sh)) {
407 XFreePixmap(dpy, dc.drawable);
408 dc.drawable = XCreatePixmap(dpy, root, BW, bh, DefaultDepth(dpy, screen));
409 XMoveResizeWindow(dpy, barwin, BX, BY, BW, bh);
415 configurerequest(XEvent *e) {
417 XConfigureRequestEvent *ev = &e->xconfigurerequest;
420 if((c = getclient(ev->window))) {
421 if(ev->value_mask & CWBorderWidth)
422 c->border = ev->border_width;
423 if(c->isfixed || c->isfloating || (floating == lt->arrange)) {
424 if(ev->value_mask & CWX)
426 if(ev->value_mask & CWY)
428 if(ev->value_mask & CWWidth)
430 if(ev->value_mask & CWHeight)
432 if((c->x - sx + c->w) > sw && c->isfloating)
433 c->x = sx + (sw / 2 - c->w / 2); /* center in x direction */
434 if((c->y - sy + c->h) > sh && c->isfloating)
435 c->y = sy + (sh / 2 - c->h / 2); /* center in y direction */
436 if((ev->value_mask & (CWX|CWY))
437 && !(ev->value_mask & (CWWidth|CWHeight)))
440 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h);
448 wc.width = ev->width;
449 wc.height = ev->height;
450 wc.border_width = ev->border_width;
451 wc.sibling = ev->above;
452 wc.stack_mode = ev->detail;
453 XConfigureWindow(dpy, ev->window, ev->value_mask, &wc);
459 destroynotify(XEvent *e) {
461 XDestroyWindowEvent *ev = &e->xdestroywindow;
463 if((c = getclient(ev->window)))
470 c->prev->next = c->next;
472 c->next->prev = c->prev;
475 c->next = c->prev = NULL;
479 detachstack(Client *c) {
482 for(tc=&stack; *tc && *tc != c; tc=&(*tc)->snext);
492 for(c = stack; c && !isvisible(c); c = c->snext);
493 for(i = 0; i < LENGTH(tags); i++) {
494 dc.w = textw(tags[i]);
496 drawtext(tags[i], dc.sel, isurgent(i));
497 drawsquare(c && c->tags[i], isoccupied(i), isurgent(i), dc.sel);
500 drawtext(tags[i], dc.norm, isurgent(i));
501 drawsquare(c && c->tags[i], isoccupied(i), isurgent(i), dc.norm);
506 drawtext(lt->symbol, dc.norm, False);
514 drawtext(stext, dc.norm, False);
515 if((dc.w = dc.x - x) > bh) {
518 drawtext(c->name, dc.sel, False);
519 drawsquare(False, c->isfloating, False, dc.sel);
522 drawtext(NULL, dc.norm, False);
524 XCopyArea(dpy, dc.drawable, barwin, dc.gc, 0, 0, BW, bh, 0, 0);
529 drawsquare(Bool filled, Bool empty, Bool invert, unsigned long col[ColLast]) {
532 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
534 gcv.foreground = col[invert ? ColBG : ColFG];
535 XChangeGC(dpy, dc.gc, GCForeground, &gcv);
536 x = (dc.font.ascent + dc.font.descent + 2) / 4;
540 r.width = r.height = x + 1;
541 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
544 r.width = r.height = x;
545 XDrawRectangles(dpy, dc.drawable, dc.gc, &r, 1);
550 drawtext(const char *text, unsigned long col[ColLast], Bool invert) {
552 unsigned int len, olen;
553 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
555 XSetForeground(dpy, dc.gc, col[invert ? ColFG : ColBG]);
556 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
560 olen = len = strlen(text);
561 if(len >= sizeof buf)
562 len = sizeof buf - 1;
563 memcpy(buf, text, len);
565 h = dc.font.ascent + dc.font.descent;
566 y = dc.y + (dc.h / 2) - (h / 2) + dc.font.ascent;
568 /* shorten text if necessary */
569 while(len && (w = textnw(buf, len)) > dc.w - h)
580 return; /* too long */
581 XSetForeground(dpy, dc.gc, col[invert ? ColBG : ColFG]);
583 XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
585 XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
589 emallocz(unsigned int size) {
590 void *res = calloc(1, size);
593 eprint("fatal: could not malloc() %u bytes\n", size);
598 enternotify(XEvent *e) {
600 XCrossingEvent *ev = &e->xcrossing;
602 if((ev->mode != NotifyNormal || ev->detail == NotifyInferior) && ev->window != root)
604 if((c = getclient(ev->window)))
611 eprint(const char *errstr, ...) {
614 va_start(ap, errstr);
615 vfprintf(stderr, errstr, ap);
622 XExposeEvent *ev = &e->xexpose;
624 if(ev->count == 0 && (ev->window == barwin))
629 floating(void) { /* default floating layout */
633 for(c = clients; c; c = c->next)
635 resize(c, c->x, c->y, c->w, c->h, True);
640 if(!c || (c && !isvisible(c)))
641 for(c = stack; c && !isvisible(c); c = c->snext);
642 if(sel && sel != c) {
643 grabbuttons(sel, False);
644 XSetWindowBorder(dpy, sel->win, dc.norm[ColBorder]);
645 if(lt->arrange == monocle)
646 resize(sel, sel->rx, sel->ry, sel->rw, sel->rh, True);
651 grabbuttons(c, True);
652 if(lt->arrange == monocle) {
659 resize(c, MOX, MOY, MOW, MOH, RESIZEHINTS);
664 XSetWindowBorder(dpy, c->win, dc.sel[ColBorder]);
665 XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
668 XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
673 focusin(XEvent *e) { /* there are some broken focus acquiring clients */
674 XFocusChangeEvent *ev = &e->xfocus;
676 if(sel && ev->window != sel->win)
677 XSetInputFocus(dpy, sel->win, RevertToPointerRoot, CurrentTime);
681 focusnext(const char *arg) {
686 for(c = sel->next; c && !isvisible(c); c = c->next);
688 for(c = clients; c && !isvisible(c); c = c->next);
696 focusprev(const char *arg) {
701 for(c = sel->prev; c && !isvisible(c); c = c->prev);
703 for(c = clients; c && c->next; c = c->next);
704 for(; c && !isvisible(c); c = c->prev);
713 getclient(Window w) {
716 for(c = clients; c && c->win != w; c = c->next);
721 getcolor(const char *colstr) {
722 Colormap cmap = DefaultColormap(dpy, screen);
725 if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
726 eprint("error, cannot allocate color '%s'\n", colstr);
734 unsigned char *p = NULL;
735 unsigned long n, extra;
738 status = XGetWindowProperty(dpy, w, wmatom[WMState], 0L, 2L, False, wmatom[WMState],
739 &real, &format, &n, &extra, (unsigned char **)&p);
740 if(status != Success)
749 gettextprop(Window w, Atom atom, char *text, unsigned int size) {
754 if(!text || size == 0)
757 XGetTextProperty(dpy, w, &name, atom);
760 if(name.encoding == XA_STRING)
761 strncpy(text, (char *)name.value, size - 1);
763 if(XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success
765 strncpy(text, *list, size - 1);
766 XFreeStringList(list);
769 text[size - 1] = '\0';
775 grabbuttons(Client *c, Bool focused) {
776 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
779 XGrabButton(dpy, Button1, MODKEY, c->win, False, BUTTONMASK,
780 GrabModeAsync, GrabModeSync, None, None);
781 XGrabButton(dpy, Button1, MODKEY|LockMask, c->win, False, BUTTONMASK,
782 GrabModeAsync, GrabModeSync, None, None);
783 XGrabButton(dpy, Button1, MODKEY|numlockmask, c->win, False, BUTTONMASK,
784 GrabModeAsync, GrabModeSync, None, None);
785 XGrabButton(dpy, Button1, MODKEY|numlockmask|LockMask, c->win, False, BUTTONMASK,
786 GrabModeAsync, GrabModeSync, None, None);
788 XGrabButton(dpy, Button2, MODKEY, c->win, False, BUTTONMASK,
789 GrabModeAsync, GrabModeSync, None, None);
790 XGrabButton(dpy, Button2, MODKEY|LockMask, c->win, False, BUTTONMASK,
791 GrabModeAsync, GrabModeSync, None, None);
792 XGrabButton(dpy, Button2, MODKEY|numlockmask, c->win, False, BUTTONMASK,
793 GrabModeAsync, GrabModeSync, None, None);
794 XGrabButton(dpy, Button2, MODKEY|numlockmask|LockMask, c->win, False, BUTTONMASK,
795 GrabModeAsync, GrabModeSync, None, None);
797 XGrabButton(dpy, Button3, MODKEY, c->win, False, BUTTONMASK,
798 GrabModeAsync, GrabModeSync, None, None);
799 XGrabButton(dpy, Button3, MODKEY|LockMask, c->win, False, BUTTONMASK,
800 GrabModeAsync, GrabModeSync, None, None);
801 XGrabButton(dpy, Button3, MODKEY|numlockmask, c->win, False, BUTTONMASK,
802 GrabModeAsync, GrabModeSync, None, None);
803 XGrabButton(dpy, Button3, MODKEY|numlockmask|LockMask, c->win, False, BUTTONMASK,
804 GrabModeAsync, GrabModeSync, None, None);
807 XGrabButton(dpy, AnyButton, AnyModifier, c->win, False, BUTTONMASK,
808 GrabModeAsync, GrabModeSync, None, None);
815 XModifierKeymap *modmap;
817 /* init modifier map */
818 modmap = XGetModifierMapping(dpy);
819 for(i = 0; i < 8; i++)
820 for(j = 0; j < modmap->max_keypermod; j++) {
821 if(modmap->modifiermap[i * modmap->max_keypermod + j] == XKeysymToKeycode(dpy, XK_Num_Lock))
822 numlockmask = (1 << i);
824 XFreeModifiermap(modmap);
826 XUngrabKey(dpy, AnyKey, AnyModifier, root);
827 for(i = 0; i < LENGTH(keys); i++) {
828 code = XKeysymToKeycode(dpy, keys[i].keysym);
829 XGrabKey(dpy, code, keys[i].mod, root, True,
830 GrabModeAsync, GrabModeAsync);
831 XGrabKey(dpy, code, keys[i].mod|LockMask, root, True,
832 GrabModeAsync, GrabModeAsync);
833 XGrabKey(dpy, code, keys[i].mod|numlockmask, root, True,
834 GrabModeAsync, GrabModeAsync);
835 XGrabKey(dpy, code, keys[i].mod|numlockmask|LockMask, root, True,
836 GrabModeAsync, GrabModeAsync);
841 idxoftag(const char *t) {
844 for(i = 0; (i < LENGTH(tags)) && (tags[i] != t); i++);
845 return (i < LENGTH(tags)) ? i : 0;
849 initfont(const char *fontstr) {
850 char *def, **missing;
855 XFreeFontSet(dpy, dc.font.set);
856 dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
859 fprintf(stderr, "dwm: missing fontset: %s\n", missing[n]);
860 XFreeStringList(missing);
863 XFontSetExtents *font_extents;
864 XFontStruct **xfonts;
866 dc.font.ascent = dc.font.descent = 0;
867 font_extents = XExtentsOfFontSet(dc.font.set);
868 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
869 for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
870 if(dc.font.ascent < (*xfonts)->ascent)
871 dc.font.ascent = (*xfonts)->ascent;
872 if(dc.font.descent < (*xfonts)->descent)
873 dc.font.descent = (*xfonts)->descent;
879 XFreeFont(dpy, dc.font.xfont);
880 dc.font.xfont = NULL;
881 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr))
882 && !(dc.font.xfont = XLoadQueryFont(dpy, "fixed")))
883 eprint("error, cannot load font: '%s'\n", fontstr);
884 dc.font.ascent = dc.font.xfont->ascent;
885 dc.font.descent = dc.font.xfont->descent;
887 dc.font.height = dc.font.ascent + dc.font.descent;
891 isoccupied(unsigned int t) {
894 for(c = clients; c; c = c->next)
901 isprotodel(Client *c) {
906 if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
907 for(i = 0; !ret && i < n; i++)
908 if(protocols[i] == wmatom[WMDelete])
916 isurgent(unsigned int t) {
919 for(c = clients; c; c = c->next)
920 if(c->isurgent && c->tags[t])
926 isvisible(Client *c) {
929 for(i = 0; i < LENGTH(tags); i++)
930 if(c->tags[i] && seltags[i])
936 keypress(XEvent *e) {
942 keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
943 for(i = 0; i < LENGTH(keys); i++)
944 if(keysym == keys[i].keysym
945 && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state))
948 keys[i].func(keys[i].arg);
953 killclient(const char *arg) {
958 if(isprotodel(sel)) {
959 ev.type = ClientMessage;
960 ev.xclient.window = sel->win;
961 ev.xclient.message_type = wmatom[WMProtocols];
962 ev.xclient.format = 32;
963 ev.xclient.data.l[0] = wmatom[WMDelete];
964 ev.xclient.data.l[1] = CurrentTime;
965 XSendEvent(dpy, sel->win, False, NoEventMask, &ev);
968 XKillClient(dpy, sel->win);
972 manage(Window w, XWindowAttributes *wa) {
973 Client *c, *t = NULL;
978 c = emallocz(sizeof(Client));
979 c->tags = emallocz(TAGSZ);
982 c->x = c->rx = wa->x + sx;
983 c->y = c->ry = wa->y + sy;
984 c->w = c->rw = wa->width;
985 c->h = c->rh = wa->height;
986 c->oldborder = wa->border_width;
988 if(c->w == sw && c->h == sh) {
991 c->border = wa->border_width;
994 if(c->x + c->w + 2 * c->border > sx + sw)
995 c->x = sx + sw - c->w - 2 * c->border;
996 if(c->y + c->h + 2 * c->border > sy + sh)
997 c->y = sy + sh - c->h - 2 * c->border;
1002 c->border = BORDERPX;
1004 wc.border_width = c->border;
1005 XConfigureWindow(dpy, w, CWBorderWidth, &wc);
1006 XSetWindowBorder(dpy, w, dc.norm[ColBorder]);
1007 configure(c); /* propagates border_width, if size doesn't change */
1009 XSelectInput(dpy, w, EnterWindowMask|FocusChangeMask|PropertyChangeMask|StructureNotifyMask);
1010 grabbuttons(c, False);
1012 if((rettrans = XGetTransientForHint(dpy, w, &trans) == Success))
1013 for(t = clients; t && t->win != trans; t = t->next);
1015 memcpy(c->tags, t->tags, TAGSZ);
1019 c->isfloating = (rettrans == Success) || c->isfixed;
1022 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h); /* some windows require this */
1024 XMapWindow(dpy, c->win);
1025 setclientstate(c, NormalState);
1030 mappingnotify(XEvent *e) {
1031 XMappingEvent *ev = &e->xmapping;
1033 XRefreshKeyboardMapping(ev);
1034 if(ev->request == MappingKeyboard)
1039 maprequest(XEvent *e) {
1040 static XWindowAttributes wa;
1041 XMapRequestEvent *ev = &e->xmaprequest;
1043 if(!XGetWindowAttributes(dpy, ev->window, &wa))
1045 if(wa.override_redirect)
1047 if(!getclient(ev->window))
1048 manage(ev->window, &wa);
1057 movemouse(Client *c) {
1058 int x1, y1, ocx, ocy, di, nx, ny;
1065 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1066 None, cursor[CurMove], CurrentTime) != GrabSuccess)
1068 XQueryPointer(dpy, root, &dummy, &dummy, &x1, &y1, &di, &di, &dui);
1070 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
1073 XUngrabPointer(dpy, CurrentTime);
1075 case ConfigureRequest:
1078 handler[ev.type](&ev);
1082 nx = ocx + (ev.xmotion.x - x1);
1083 ny = ocy + (ev.xmotion.y - y1);
1084 if(abs(sx - nx) < SNAP)
1086 else if(abs((sx + sw) - (nx + c->w + 2 * c->border)) < SNAP)
1087 nx = sx + sw - c->w - 2 * c->border;
1088 if(abs(sy - ny) < SNAP)
1090 else if(abs((sy + sh) - (ny + c->h + 2 * c->border)) < SNAP)
1091 ny = sy + sh - c->h - 2 * c->border;
1092 if(!c->isfloating && (lt->arrange != floating) && (abs(nx - c->x) > SNAP || abs(ny - c->y) > SNAP))
1093 togglefloating(NULL);
1094 if((lt->arrange == floating) || c->isfloating)
1095 resize(c, nx, ny, c->w, c->h, False);
1102 nexttiled(Client *c) {
1103 for(; c && (c->isfloating || !isvisible(c)); c = c->next);
1108 propertynotify(XEvent *e) {
1111 XPropertyEvent *ev = &e->xproperty;
1113 if(ev->state == PropertyDelete)
1114 return; /* ignore */
1115 if((c = getclient(ev->window))) {
1118 case XA_WM_TRANSIENT_FOR:
1119 XGetTransientForHint(dpy, c->win, &trans);
1120 if(!c->isfloating && (c->isfloating = (getclient(trans) != NULL)))
1123 case XA_WM_NORMAL_HINTS:
1131 if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
1140 quit(const char *arg) {
1141 readin = running = False;
1145 reapply(const char *arg) {
1146 static Bool zerotags[LENGTH(tags)] = { 0 };
1149 for(c = clients; c; c = c->next) {
1150 memcpy(c->tags, zerotags, sizeof zerotags);
1157 resize(Client *c, int x, int y, int w, int h, Bool sizehints) {
1161 /* set minimum possible */
1167 /* temporarily remove base dimensions */
1171 /* adjust for aspect limits */
1172 if (c->minay > 0 && c->maxay > 0 && c->minax > 0 && c->maxax > 0) {
1173 if (w * c->maxay > h * c->maxax)
1174 w = h * c->maxax / c->maxay;
1175 else if (w * c->minay < h * c->minax)
1176 h = w * c->minay / c->minax;
1179 /* adjust for increment value */
1185 /* restore base dimensions */
1189 if(c->minw > 0 && w < c->minw)
1191 if(c->minh > 0 && h < c->minh)
1193 if(c->maxw > 0 && w > c->maxw)
1195 if(c->maxh > 0 && h > c->maxh)
1198 if(w <= 0 || h <= 0)
1201 x = sw - w - 2 * c->border;
1203 y = sh - h - 2 * c->border;
1204 if(x + w + 2 * c->border < sx)
1206 if(y + h + 2 * c->border < sy)
1208 if(c->x != x || c->y != y || c->w != w || c->h != h) {
1211 c->w = wc.width = w;
1212 c->h = wc.height = h;
1213 wc.border_width = c->border;
1214 XConfigureWindow(dpy, c->win,
1215 CWX|CWY|CWWidth|CWHeight|CWBorderWidth, &wc);
1222 resizemouse(Client *c) {
1229 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1230 None, cursor[CurResize], CurrentTime) != GrabSuccess)
1232 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->border - 1, c->h + c->border - 1);
1234 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask , &ev);
1237 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0,
1238 c->w + c->border - 1, c->h + c->border - 1);
1239 XUngrabPointer(dpy, CurrentTime);
1240 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1242 case ConfigureRequest:
1245 handler[ev.type](&ev);
1249 if((nw = ev.xmotion.x - ocx - 2 * c->border + 1) <= 0)
1251 if((nh = ev.xmotion.y - ocy - 2 * c->border + 1) <= 0)
1253 if(!c->isfloating && (lt->arrange != floating) && (abs(nw - c->w) > SNAP || abs(nh - c->h) > SNAP))
1254 togglefloating(NULL);
1255 if((lt->arrange == floating) || c->isfloating)
1256 resize(c, c->x, c->y, nw, nh, True);
1271 if(sel->isfloating || (lt->arrange == floating))
1272 XRaiseWindow(dpy, sel->win);
1273 if(lt->arrange != floating) {
1274 wc.stack_mode = Below;
1275 wc.sibling = barwin;
1276 if(!sel->isfloating) {
1277 XConfigureWindow(dpy, sel->win, CWSibling|CWStackMode, &wc);
1278 wc.sibling = sel->win;
1280 for(c = nexttiled(clients); c; c = nexttiled(c->next)) {
1283 XConfigureWindow(dpy, c->win, CWSibling|CWStackMode, &wc);
1284 wc.sibling = c->win;
1288 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1294 char sbuf[sizeof stext];
1297 unsigned int len, offset;
1300 /* main event loop, also reads status text from stdin */
1302 xfd = ConnectionNumber(dpy);
1305 len = sizeof stext - 1;
1306 sbuf[len] = stext[len] = '\0'; /* 0-terminator is never touched */
1310 FD_SET(STDIN_FILENO, &rd);
1312 if(select(xfd + 1, &rd, NULL, NULL, NULL) == -1) {
1315 eprint("select failed\n");
1317 if(FD_ISSET(STDIN_FILENO, &rd)) {
1318 switch((r = read(STDIN_FILENO, sbuf + offset, len - offset))) {
1320 strncpy(stext, strerror(errno), len);
1324 strncpy(stext, "EOF", 4);
1328 for(p = sbuf + offset; r > 0; p++, r--, offset++)
1329 if(*p == '\n' || *p == '\0') {
1331 strncpy(stext, sbuf, len);
1332 p += r - 1; /* p is sbuf + offset + r - 1 */
1333 for(r = 0; *(p - r) && *(p - r) != '\n'; r++);
1336 memmove(sbuf, p - r + 1, r);
1343 while(XPending(dpy)) {
1344 XNextEvent(dpy, &ev);
1345 if(handler[ev.type])
1346 (handler[ev.type])(&ev); /* call handler */
1353 unsigned int i, num;
1354 Window *wins, d1, d2;
1355 XWindowAttributes wa;
1358 if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1359 for(i = 0; i < num; i++) {
1360 if(!XGetWindowAttributes(dpy, wins[i], &wa)
1361 || wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1363 if(wa.map_state == IsViewable || getstate(wins[i]) == IconicState)
1364 manage(wins[i], &wa);
1366 for(i = 0; i < num; i++) { /* now the transients */
1367 if(!XGetWindowAttributes(dpy, wins[i], &wa))
1369 if(XGetTransientForHint(dpy, wins[i], &d1)
1370 && (wa.map_state == IsViewable || getstate(wins[i]) == IconicState))
1371 manage(wins[i], &wa);
1379 setclientstate(Client *c, long state) {
1380 long data[] = {state, None};
1382 XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1383 PropModeReplace, (unsigned char *)data, 2);
1387 setlayout(const char *arg) {
1392 for(i = 0; i < LENGTH(layouts); i++)
1393 if(!strcmp(arg, layouts[i].symbol))
1395 if(i == LENGTH(layouts))
1407 XSetWindowAttributes wa;
1410 screen = DefaultScreen(dpy);
1411 root = RootWindow(dpy, screen);
1414 sw = DisplayWidth(dpy, screen);
1415 sh = DisplayHeight(dpy, screen);
1418 wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1419 wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1420 wmatom[WMName] = XInternAtom(dpy, "WM_NAME", False);
1421 wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1422 netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1423 netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1426 wa.cursor = cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1427 cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1428 cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1430 /* init appearance */
1431 dc.norm[ColBorder] = getcolor(NORMBORDERCOLOR);
1432 dc.norm[ColBG] = getcolor(NORMBGCOLOR);
1433 dc.norm[ColFG] = getcolor(NORMFGCOLOR);
1434 dc.sel[ColBorder] = getcolor(SELBORDERCOLOR);
1435 dc.sel[ColBG] = getcolor(SELBGCOLOR);
1436 dc.sel[ColFG] = getcolor(SELFGCOLOR);
1438 dc.h = bh = dc.font.height + 2;
1439 dc.drawable = XCreatePixmap(dpy, root, DisplayWidth(dpy, screen), bh, DefaultDepth(dpy, screen));
1440 dc.gc = XCreateGC(dpy, root, 0, 0);
1441 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
1443 XSetFont(dpy, dc.gc, dc.font.xfont->fid);
1446 seltags = emallocz(TAGSZ);
1447 prevtags = emallocz(TAGSZ);
1448 seltags[0] = prevtags[0] = True;
1454 for(blw = i = 0; i < LENGTH(layouts); i++) {
1455 i = textw(layouts[i].symbol);
1460 wa.override_redirect = 1;
1461 wa.background_pixmap = ParentRelative;
1462 wa.event_mask = ButtonPressMask|ExposureMask;
1464 barwin = XCreateWindow(dpy, root, BX, BY, BW, bh, 0, DefaultDepth(dpy, screen),
1465 CopyFromParent, DefaultVisual(dpy, screen),
1466 CWOverrideRedirect|CWBackPixmap|CWEventMask, &wa);
1467 XDefineCursor(dpy, barwin, cursor[CurNormal]);
1468 XMapRaised(dpy, barwin);
1469 strcpy(stext, "dwm-"VERSION);
1472 /* EWMH support per view */
1473 XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1474 PropModeReplace, (unsigned char *) netatom, NetLast);
1476 /* select for events */
1477 wa.event_mask = SubstructureRedirectMask|SubstructureNotifyMask
1478 |EnterWindowMask|LeaveWindowMask|StructureNotifyMask;
1479 XChangeWindowAttributes(dpy, root, CWEventMask|CWCursor, &wa);
1480 XSelectInput(dpy, root, wa.event_mask);
1488 spawn(const char *arg) {
1489 static char *shell = NULL;
1491 if(!shell && !(shell = getenv("SHELL")))
1495 /* The double-fork construct avoids zombie processes and keeps the code
1496 * clean from stupid signal handlers. */
1500 close(ConnectionNumber(dpy));
1502 execl(shell, shell, "-c", arg, (char *)NULL);
1503 fprintf(stderr, "dwm: execl '%s -c %s'", shell, arg);
1512 tag(const char *arg) {
1517 for(i = 0; i < LENGTH(tags); i++)
1518 sel->tags[i] = (NULL == arg);
1519 sel->tags[idxoftag(arg)] = True;
1524 textnw(const char *text, unsigned int len) {
1528 XmbTextExtents(dc.font.set, text, len, NULL, &r);
1531 return XTextWidth(dc.font.xfont, text, len);
1535 textw(const char *text) {
1536 return textnw(text, strlen(text)) + dc.font.height;
1541 unsigned int i, n, nx, ny, nw, nh, mw, th;
1548 for(n = 0, c = nexttiled(clients); c; c = nexttiled(c->next))
1552 mw = (n == 1) ? MOW : MW;
1553 th = (n > 1) ? TH / (n - 1) : 0;
1554 if(n > 1 && th < bh)
1557 for(i = 0, c = mc = nexttiled(clients); c; c = nexttiled(c->next)) {
1558 if(i == 0) { /* master */
1559 nw = mw - 2 * c->border;
1560 nh = MH - 2 * c->border;
1562 else { /* tile window */
1566 nw = TW - 2 * c->border;
1568 if(i + 1 == n) /* remainder */
1569 nh = (TY + TH) - ny - 2 * c->border;
1571 nh = th - 2 * c->border;
1573 resize(c, nx, ny, nw, nh, RESIZEHINTS);
1574 if((RESIZEHINTS) && ((c->h < bh) || (c->h > nh) || (c->w < bh) || (c->w > nw)))
1575 /* client doesn't accept size constraints */
1576 resize(c, nx, ny, nw, nh, False);
1577 if(n > 1 && th != TH)
1578 ny = c->y + c->h + 2 * c->border;
1584 togglefloating(const char *arg) {
1587 sel->isfloating = !sel->isfloating;
1589 resize(sel, sel->x, sel->y, sel->w, sel->h, True);
1594 toggletag(const char *arg) {
1600 sel->tags[i] = !sel->tags[i];
1601 for(j = 0; j < LENGTH(tags) && !sel->tags[j]; j++);
1602 if(j == LENGTH(tags))
1603 sel->tags[i] = True; /* at least one tag must be enabled */
1608 toggleview(const char *arg) {
1612 seltags[i] = !seltags[i];
1613 for(j = 0; j < LENGTH(tags) && !seltags[j]; j++);
1614 if(j == LENGTH(tags))
1615 seltags[i] = True; /* at least one tag must be viewed */
1623 XMoveWindow(dpy, c->win, c->x, c->y);
1624 c->isbanned = False;
1628 unmanage(Client *c) {
1631 wc.border_width = c->oldborder;
1632 /* The server grab construct avoids race conditions. */
1634 XSetErrorHandler(xerrordummy);
1635 XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
1640 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1641 setclientstate(c, WithdrawnState);
1645 XSetErrorHandler(xerror);
1651 unmapnotify(XEvent *e) {
1653 XUnmapEvent *ev = &e->xunmap;
1655 if((c = getclient(ev->window)))
1660 updatesizehints(Client *c) {
1664 if(!XGetWMNormalHints(dpy, c->win, &size, &msize) || !size.flags)
1666 c->flags = size.flags;
1667 if(c->flags & PBaseSize) {
1668 c->basew = size.base_width;
1669 c->baseh = size.base_height;
1671 else if(c->flags & PMinSize) {
1672 c->basew = size.min_width;
1673 c->baseh = size.min_height;
1676 c->basew = c->baseh = 0;
1677 if(c->flags & PResizeInc) {
1678 c->incw = size.width_inc;
1679 c->inch = size.height_inc;
1682 c->incw = c->inch = 0;
1683 if(c->flags & PMaxSize) {
1684 c->maxw = size.max_width;
1685 c->maxh = size.max_height;
1688 c->maxw = c->maxh = 0;
1689 if(c->flags & PMinSize) {
1690 c->minw = size.min_width;
1691 c->minh = size.min_height;
1693 else if(c->flags & PBaseSize) {
1694 c->minw = size.base_width;
1695 c->minh = size.base_height;
1698 c->minw = c->minh = 0;
1699 if(c->flags & PAspect) {
1700 c->minax = size.min_aspect.x;
1701 c->maxax = size.max_aspect.x;
1702 c->minay = size.min_aspect.y;
1703 c->maxay = size.max_aspect.y;
1706 c->minax = c->maxax = c->minay = c->maxay = 0;
1707 c->isfixed = (c->maxw && c->minw && c->maxh && c->minh
1708 && c->maxw == c->minw && c->maxh == c->minh);
1712 updatetitle(Client *c) {
1713 if(!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
1714 gettextprop(c->win, wmatom[WMName], c->name, sizeof c->name);
1718 updatewmhints(Client *c) {
1721 if((wmh = XGetWMHints(dpy, c->win))) {
1723 sel->isurgent = False;
1725 c->isurgent = (wmh->flags & XUrgencyHint) ? True : False;
1732 view(const char *arg) {
1735 for(i = 0; i < LENGTH(tags); i++)
1736 tmp[i] = (NULL == arg);
1737 tmp[idxoftag(arg)] = True;
1739 if(memcmp(seltags, tmp, TAGSZ) != 0) {
1740 memcpy(prevtags, seltags, TAGSZ);
1741 memcpy(seltags, tmp, TAGSZ);
1747 viewprevtag(const char *arg) {
1749 memcpy(tmp, seltags, TAGSZ);
1750 memcpy(seltags, prevtags, TAGSZ);
1751 memcpy(prevtags, tmp, TAGSZ);
1755 /* There's no way to check accesses to destroyed windows, thus those cases are
1756 * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
1757 * default error handler, which may call exit. */
1759 xerror(Display *dpy, XErrorEvent *ee) {
1760 if(ee->error_code == BadWindow
1761 || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1762 || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1763 || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1764 || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1765 || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1766 || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1767 || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1769 fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1770 ee->request_code, ee->error_code);
1771 return xerrorxlib(dpy, ee); /* may call exit */
1775 xerrordummy(Display *dpy, XErrorEvent *ee) {
1779 /* Startup Error handler to check if another window manager
1780 * is already running. */
1782 xerrorstart(Display *dpy, XErrorEvent *ee) {
1788 zoom(const char *arg) {
1791 if(!sel || !dozoom || sel->isfloating)
1793 if(c == nexttiled(clients))
1794 if(!(c = nexttiled(c->next)))
1803 main(int argc, char *argv[]) {
1804 if(argc == 2 && !strcmp("-v", argv[1]))
1805 eprint("dwm-"VERSION", © 2006-2008 dwm engineers, see LICENSE for details\n");
1807 eprint("usage: dwm [-v]\n");
1809 setlocale(LC_CTYPE, "");
1810 if(!(dpy = XOpenDisplay(0)))
1811 eprint("dwm: cannot open display\n");