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 BUTTONMASK (ButtonPressMask|ButtonReleaseMask)
45 #define CLEANMASK(mask) (mask & ~(numlockmask|LockMask))
46 #define LENGTH(x) (sizeof x / sizeof x[0])
48 #define MOUSEMASK (BUTTONMASK|PointerMotionMask)
51 enum { CurNormal, CurResize, CurMove, CurLast }; /* cursor */
52 enum { ColBorder, ColFG, ColBG, ColLast }; /* color */
53 enum { NetSupported, NetWMName, NetLast }; /* EWMH atoms */
54 enum { WMProtocols, WMDelete, WMName, WMState, WMLast };/* default atoms */
57 typedef struct Client Client;
61 int basew, baseh, incw, inch, maxw, maxh, minw, minh;
62 int minax, maxax, minay, maxay;
64 unsigned int border, oldborder;
65 Bool isbanned, isfixed, isfloating, isurgent;
75 unsigned long norm[ColLast];
76 unsigned long sel[ColLast];
86 } DC; /* draw context */
91 void (*func)(const char *arg);
97 void (*arrange)(void);
99 } Layout; /* TODO: layout should keep an auxilliary pointer to its Geometry,
100 instead of having all those layout specific vars globally */
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 unsigned int counttiled(void);
121 void destroynotify(XEvent *e);
122 void detach(Client *c);
123 void detachstack(Client *c);
125 void drawsquare(Bool filled, Bool empty, Bool invert, unsigned long col[ColLast]);
126 void drawtext(const char *text, unsigned long col[ColLast], Bool invert);
127 void *emallocz(unsigned int size);
128 void enternotify(XEvent *e);
129 void eprint(const char *errstr, ...);
130 void expose(XEvent *e);
131 void floating(void); /* default floating layout */
132 void focus(Client *c);
133 void focusin(XEvent *e);
134 void focusnext(const char *arg);
135 void focusprev(const char *arg);
136 Client *getclient(Window w);
137 unsigned long getcolor(const char *colstr);
138 long getstate(Window w);
139 Bool gettextprop(Window w, Atom atom, char *text, unsigned int size);
140 void grabbuttons(Client *c, Bool focused);
142 unsigned int idxoftag(const char *t);
143 void initfont(const char *fontstr);
144 Bool isoccupied(unsigned int t);
145 Bool isprotodel(Client *c);
146 Bool isurgent(unsigned int t);
147 Bool isvisible(Client *c);
148 void keypress(XEvent *e);
149 void killclient(const char *arg);
150 void manage(Window w, XWindowAttributes *wa);
151 void mappingnotify(XEvent *e);
152 void maprequest(XEvent *e);
154 void movemouse(Client *c);
155 Client *nexttiled(Client *c);
156 void propertynotify(XEvent *e);
157 void quit(const char *arg);
158 void reapply(const char *arg);
159 void resize(Client *c, int x, int y, int w, int h, Bool sizehints);
160 void resizemouse(Client *c);
164 void setclientstate(Client *c, long state);
165 void setdefaultgeoms(void);
166 void setlayout(const char *arg);
168 void spawn(const char *arg);
169 void tag(const char *arg);
170 unsigned int textnw(const char *text, unsigned int len);
171 unsigned int textw(const char *text);
173 void tilehstack(unsigned int n);
174 Client *tilemaster(unsigned int n);
175 void tileresize(Client *c, int x, int y, int w, int h);
177 void tilevstack(unsigned int n);
178 void togglefloating(const char *arg);
179 void toggletag(const char *arg);
180 void toggleview(const char *arg);
181 void unban(Client *c);
182 void unmanage(Client *c);
183 void unmapnotify(XEvent *e);
184 void updatebarpos(void);
185 void updatesizehints(Client *c);
186 void updatetitle(Client *c);
187 void updatewmhints(Client *c);
188 void view(const char *arg);
189 void viewprevtag(const char *arg); /* views previous selected tags */
190 int xerror(Display *dpy, XErrorEvent *ee);
191 int xerrordummy(Display *dpy, XErrorEvent *ee);
192 int xerrorstart(Display *dpy, XErrorEvent *ee);
193 void zoom(const char *arg);
196 char stext[256], buf[256];
197 int screen, sx, sy, sw, sh;
198 int (*xerrorxlib)(Display *, XErrorEvent *);
199 int bx, by, bw, bh, blw, mx, my, mw, mh, mox, moy, mow, moh, tx, ty, tw, th, wx, wy, ww, wh;
200 unsigned int numlockmask = 0;
201 void (*handler[LASTEvent]) (XEvent *) = {
202 [ButtonPress] = buttonpress,
203 [ConfigureRequest] = configurerequest,
204 [ConfigureNotify] = configurenotify,
205 [DestroyNotify] = destroynotify,
206 [EnterNotify] = enternotify,
209 [KeyPress] = keypress,
210 [MappingNotify] = mappingnotify,
211 [MapRequest] = maprequest,
212 [PropertyNotify] = propertynotify,
213 [UnmapNotify] = unmapnotify
215 Atom wmatom[WMLast], netatom[NetLast];
216 Bool otherwm, readin;
220 Client *clients = NULL;
222 Client *stack = NULL;
223 Cursor cursor[CurLast];
228 void (*setgeoms)(void) = setdefaultgeoms;
230 /* configuration, allows nested code to access above variables */
232 #define TAGSZ (LENGTH(tags) * sizeof(Bool))
233 static Bool tmp[LENGTH(tags)];
235 /* function implementations */
238 applyrules(Client *c) {
240 Bool matched = False;
242 XClassHint ch = { 0 };
245 XGetClassHint(dpy, c->win, &ch);
246 for(i = 0; i < LENGTH(rules); i++) {
248 if(strstr(c->name, r->prop)
249 || (ch.res_class && strstr(ch.res_class, r->prop))
250 || (ch.res_name && strstr(ch.res_name, r->prop)))
252 c->isfloating = r->isfloating;
254 c->tags[idxoftag(r->tag)] = True;
264 memcpy(c->tags, seltags, TAGSZ);
271 for(c = clients; c; c = c->next)
291 attachstack(Client *c) {
300 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
305 buttonpress(XEvent *e) {
308 XButtonPressedEvent *ev = &e->xbutton;
310 if(ev->window == barwin) {
312 for(i = 0; i < LENGTH(tags); i++) {
315 if(ev->button == Button1) {
316 if(ev->state & MODKEY)
321 else if(ev->button == Button3) {
322 if(ev->state & MODKEY)
331 else if((c = getclient(ev->window))) {
333 if(CLEANMASK(ev->state) != MODKEY)
335 if(ev->button == Button1) {
339 else if(ev->button == Button2) {
340 if((floating != lt->arrange) && c->isfloating)
341 togglefloating(NULL);
345 else if(ev->button == Button3 && !c->isfixed) {
355 XSetErrorHandler(xerrorstart);
357 /* this causes an error if some other window manager is running */
358 XSelectInput(dpy, DefaultRootWindow(dpy), SubstructureRedirectMask);
361 eprint("dwm: another window manager is already running\n");
363 XSetErrorHandler(NULL);
364 xerrorxlib = XSetErrorHandler(xerror);
376 XFreeFontSet(dpy, dc.font.set);
378 XFreeFont(dpy, dc.font.xfont);
379 XUngrabKey(dpy, AnyKey, AnyModifier, root);
380 XFreePixmap(dpy, dc.drawable);
382 XFreeCursor(dpy, cursor[CurNormal]);
383 XFreeCursor(dpy, cursor[CurResize]);
384 XFreeCursor(dpy, cursor[CurMove]);
385 XDestroyWindow(dpy, barwin);
387 XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime);
391 configure(Client *c) {
394 ce.type = ConfigureNotify;
402 ce.border_width = c->border;
404 ce.override_redirect = False;
405 XSendEvent(dpy, c->win, False, StructureNotifyMask, (XEvent *)&ce);
409 configurenotify(XEvent *e) {
410 XConfigureEvent *ev = &e->xconfigure;
412 if(ev->window == root && (ev->width != sw || ev->height != sh)) {
420 configurerequest(XEvent *e) {
422 XConfigureRequestEvent *ev = &e->xconfigurerequest;
425 if((c = getclient(ev->window))) {
426 if(ev->value_mask & CWBorderWidth)
427 c->border = ev->border_width;
428 if(c->isfixed || c->isfloating || lt->isfloating) {
429 if(ev->value_mask & CWX)
431 if(ev->value_mask & CWY)
433 if(ev->value_mask & CWWidth)
435 if(ev->value_mask & CWHeight)
437 if((c->x - sx + c->w) > sw && c->isfloating)
438 c->x = sx + (sw / 2 - c->w / 2); /* center in x direction */
439 if((c->y - sy + c->h) > sh && c->isfloating)
440 c->y = sy + (sh / 2 - c->h / 2); /* center in y direction */
441 if((ev->value_mask & (CWX|CWY))
442 && !(ev->value_mask & (CWWidth|CWHeight)))
445 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h);
453 wc.width = ev->width;
454 wc.height = ev->height;
455 wc.border_width = ev->border_width;
456 wc.sibling = ev->above;
457 wc.stack_mode = ev->detail;
458 XConfigureWindow(dpy, ev->window, ev->value_mask, &wc);
468 for(n = 0, c = nexttiled(clients); c; c = nexttiled(c->next), n++);
473 destroynotify(XEvent *e) {
475 XDestroyWindowEvent *ev = &e->xdestroywindow;
477 if((c = getclient(ev->window)))
484 c->prev->next = c->next;
486 c->next->prev = c->prev;
489 c->next = c->prev = NULL;
493 detachstack(Client *c) {
496 for(tc=&stack; *tc && *tc != c; tc=&(*tc)->snext);
506 for(c = stack; c && !isvisible(c); c = c->snext);
507 for(i = 0; i < LENGTH(tags); i++) {
508 dc.w = textw(tags[i]);
510 drawtext(tags[i], dc.sel, isurgent(i));
511 drawsquare(c && c->tags[i], isoccupied(i), isurgent(i), dc.sel);
514 drawtext(tags[i], dc.norm, isurgent(i));
515 drawsquare(c && c->tags[i], isoccupied(i), isurgent(i), dc.norm);
520 drawtext(lt->symbol, dc.norm, False);
528 drawtext(stext, dc.norm, False);
529 if((dc.w = dc.x - x) > bh) {
532 drawtext(c->name, dc.sel, False);
533 drawsquare(False, c->isfloating, False, dc.sel);
536 drawtext(NULL, dc.norm, False);
538 XCopyArea(dpy, dc.drawable, barwin, dc.gc, 0, 0, bw, bh, 0, 0);
543 drawsquare(Bool filled, Bool empty, Bool invert, unsigned long col[ColLast]) {
546 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
548 gcv.foreground = col[invert ? ColBG : ColFG];
549 XChangeGC(dpy, dc.gc, GCForeground, &gcv);
550 x = (dc.font.ascent + dc.font.descent + 2) / 4;
554 r.width = r.height = x + 1;
555 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
558 r.width = r.height = x;
559 XDrawRectangles(dpy, dc.drawable, dc.gc, &r, 1);
564 drawtext(const char *text, unsigned long col[ColLast], Bool invert) {
566 unsigned int len, olen;
567 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
569 XSetForeground(dpy, dc.gc, col[invert ? ColFG : ColBG]);
570 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
574 olen = len = strlen(text);
575 if(len >= sizeof buf)
576 len = sizeof buf - 1;
577 memcpy(buf, text, len);
579 h = dc.font.ascent + dc.font.descent;
580 y = dc.y + (dc.h / 2) - (h / 2) + dc.font.ascent;
582 /* shorten text if necessary */
583 while(len && (w = textnw(buf, len)) > dc.w - h)
594 return; /* too long */
595 XSetForeground(dpy, dc.gc, col[invert ? ColBG : ColFG]);
597 XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
599 XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
603 emallocz(unsigned int size) {
604 void *res = calloc(1, size);
607 eprint("fatal: could not malloc() %u bytes\n", size);
612 enternotify(XEvent *e) {
614 XCrossingEvent *ev = &e->xcrossing;
616 if((ev->mode != NotifyNormal || ev->detail == NotifyInferior) && ev->window != root)
618 if((c = getclient(ev->window)))
625 eprint(const char *errstr, ...) {
628 va_start(ap, errstr);
629 vfprintf(stderr, errstr, ap);
636 XExposeEvent *ev = &e->xexpose;
638 if(ev->count == 0 && (ev->window == barwin))
643 floating(void) { /* default floating layout */
646 for(c = clients; c; c = c->next)
648 resize(c, c->x, c->y, c->w, c->h, True);
653 if(!c || (c && !isvisible(c)))
654 for(c = stack; c && !isvisible(c); c = c->snext);
655 if(sel && sel != c) {
656 grabbuttons(sel, False);
657 XSetWindowBorder(dpy, sel->win, dc.norm[ColBorder]);
662 grabbuttons(c, True);
666 XSetWindowBorder(dpy, c->win, dc.sel[ColBorder]);
667 XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
670 XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
675 focusin(XEvent *e) { /* there are some broken focus acquiring clients */
676 XFocusChangeEvent *ev = &e->xfocus;
678 if(sel && ev->window != sel->win)
679 XSetInputFocus(dpy, sel->win, RevertToPointerRoot, CurrentTime);
683 focusnext(const char *arg) {
688 for(c = sel->next; c && !isvisible(c); c = c->next);
690 for(c = clients; c && !isvisible(c); c = c->next);
698 focusprev(const char *arg) {
703 for(c = sel->prev; c && !isvisible(c); c = c->prev);
705 for(c = clients; c && c->next; c = c->next);
706 for(; c && !isvisible(c); c = c->prev);
715 getclient(Window w) {
718 for(c = clients; c && c->win != w; c = c->next);
723 getcolor(const char *colstr) {
724 Colormap cmap = DefaultColormap(dpy, screen);
727 if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
728 eprint("error, cannot allocate color '%s'\n", colstr);
736 unsigned char *p = NULL;
737 unsigned long n, extra;
740 status = XGetWindowProperty(dpy, w, wmatom[WMState], 0L, 2L, False, wmatom[WMState],
741 &real, &format, &n, &extra, (unsigned char **)&p);
742 if(status != Success)
751 gettextprop(Window w, Atom atom, char *text, unsigned int size) {
756 if(!text || size == 0)
759 XGetTextProperty(dpy, w, &name, atom);
762 if(name.encoding == XA_STRING)
763 strncpy(text, (char *)name.value, size - 1);
765 if(XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success
767 strncpy(text, *list, size - 1);
768 XFreeStringList(list);
771 text[size - 1] = '\0';
777 grabbuttons(Client *c, Bool focused) {
778 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
781 XGrabButton(dpy, Button1, MODKEY, c->win, False, BUTTONMASK,
782 GrabModeAsync, GrabModeSync, None, None);
783 XGrabButton(dpy, Button1, MODKEY|LockMask, c->win, False, BUTTONMASK,
784 GrabModeAsync, GrabModeSync, None, None);
785 XGrabButton(dpy, Button1, MODKEY|numlockmask, c->win, False, BUTTONMASK,
786 GrabModeAsync, GrabModeSync, None, None);
787 XGrabButton(dpy, Button1, MODKEY|numlockmask|LockMask, c->win, False, BUTTONMASK,
788 GrabModeAsync, GrabModeSync, None, None);
790 XGrabButton(dpy, Button2, MODKEY, c->win, False, BUTTONMASK,
791 GrabModeAsync, GrabModeSync, None, None);
792 XGrabButton(dpy, Button2, MODKEY|LockMask, c->win, False, BUTTONMASK,
793 GrabModeAsync, GrabModeSync, None, None);
794 XGrabButton(dpy, Button2, MODKEY|numlockmask, c->win, False, BUTTONMASK,
795 GrabModeAsync, GrabModeSync, None, None);
796 XGrabButton(dpy, Button2, MODKEY|numlockmask|LockMask, c->win, False, BUTTONMASK,
797 GrabModeAsync, GrabModeSync, None, None);
799 XGrabButton(dpy, Button3, MODKEY, c->win, False, BUTTONMASK,
800 GrabModeAsync, GrabModeSync, None, None);
801 XGrabButton(dpy, Button3, MODKEY|LockMask, c->win, False, BUTTONMASK,
802 GrabModeAsync, GrabModeSync, None, None);
803 XGrabButton(dpy, Button3, MODKEY|numlockmask, c->win, False, BUTTONMASK,
804 GrabModeAsync, GrabModeSync, None, None);
805 XGrabButton(dpy, Button3, MODKEY|numlockmask|LockMask, c->win, False, BUTTONMASK,
806 GrabModeAsync, GrabModeSync, None, None);
809 XGrabButton(dpy, AnyButton, AnyModifier, c->win, False, BUTTONMASK,
810 GrabModeAsync, GrabModeSync, None, None);
817 XModifierKeymap *modmap;
819 /* init modifier map */
820 modmap = XGetModifierMapping(dpy);
821 for(i = 0; i < 8; i++)
822 for(j = 0; j < modmap->max_keypermod; j++) {
823 if(modmap->modifiermap[i * modmap->max_keypermod + j] == XKeysymToKeycode(dpy, XK_Num_Lock))
824 numlockmask = (1 << i);
826 XFreeModifiermap(modmap);
828 XUngrabKey(dpy, AnyKey, AnyModifier, root);
829 for(i = 0; i < LENGTH(keys); i++) {
830 code = XKeysymToKeycode(dpy, keys[i].keysym);
831 XGrabKey(dpy, code, keys[i].mod, root, True,
832 GrabModeAsync, GrabModeAsync);
833 XGrabKey(dpy, code, keys[i].mod|LockMask, root, True,
834 GrabModeAsync, GrabModeAsync);
835 XGrabKey(dpy, code, keys[i].mod|numlockmask, root, True,
836 GrabModeAsync, GrabModeAsync);
837 XGrabKey(dpy, code, keys[i].mod|numlockmask|LockMask, root, True,
838 GrabModeAsync, GrabModeAsync);
843 idxoftag(const char *t) {
846 for(i = 0; (i < LENGTH(tags)) && (tags[i] != t); i++);
847 return (i < LENGTH(tags)) ? i : 0;
851 initfont(const char *fontstr) {
852 char *def, **missing;
857 XFreeFontSet(dpy, dc.font.set);
858 dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
861 fprintf(stderr, "dwm: missing fontset: %s\n", missing[n]);
862 XFreeStringList(missing);
865 XFontSetExtents *font_extents;
866 XFontStruct **xfonts;
868 dc.font.ascent = dc.font.descent = 0;
869 font_extents = XExtentsOfFontSet(dc.font.set);
870 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
871 for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
872 if(dc.font.ascent < (*xfonts)->ascent)
873 dc.font.ascent = (*xfonts)->ascent;
874 if(dc.font.descent < (*xfonts)->descent)
875 dc.font.descent = (*xfonts)->descent;
881 XFreeFont(dpy, dc.font.xfont);
882 dc.font.xfont = NULL;
883 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr))
884 && !(dc.font.xfont = XLoadQueryFont(dpy, "fixed")))
885 eprint("error, cannot load font: '%s'\n", fontstr);
886 dc.font.ascent = dc.font.xfont->ascent;
887 dc.font.descent = dc.font.xfont->descent;
889 dc.font.height = dc.font.ascent + dc.font.descent;
893 isoccupied(unsigned int t) {
896 for(c = clients; c; c = c->next)
903 isprotodel(Client *c) {
908 if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
909 for(i = 0; !ret && i < n; i++)
910 if(protocols[i] == wmatom[WMDelete])
918 isurgent(unsigned int t) {
921 for(c = clients; c; c = c->next)
922 if(c->isurgent && c->tags[t])
928 isvisible(Client *c) {
931 for(i = 0; i < LENGTH(tags); i++)
932 if(c->tags[i] && seltags[i])
938 keypress(XEvent *e) {
944 keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
945 for(i = 0; i < LENGTH(keys); i++)
946 if(keysym == keys[i].keysym
947 && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state))
950 keys[i].func(keys[i].arg);
955 killclient(const char *arg) {
960 if(isprotodel(sel)) {
961 ev.type = ClientMessage;
962 ev.xclient.window = sel->win;
963 ev.xclient.message_type = wmatom[WMProtocols];
964 ev.xclient.format = 32;
965 ev.xclient.data.l[0] = wmatom[WMDelete];
966 ev.xclient.data.l[1] = CurrentTime;
967 XSendEvent(dpy, sel->win, False, NoEventMask, &ev);
970 XKillClient(dpy, sel->win);
974 manage(Window w, XWindowAttributes *wa) {
975 Client *c, *t = NULL;
980 c = emallocz(sizeof(Client));
981 c->tags = emallocz(TAGSZ);
989 c->oldborder = wa->border_width;
990 if(c->w == sw && c->h == sh) {
993 c->border = wa->border_width;
996 if(c->x + c->w + 2 * c->border > wx + ww)
997 c->x = wx + ww - c->w - 2 * c->border;
998 if(c->y + c->h + 2 * c->border > wy + wh)
999 c->y = wy + wh - c->h - 2 * c->border;
1004 c->border = BORDERPX;
1007 wc.border_width = c->border;
1008 XConfigureWindow(dpy, w, CWBorderWidth, &wc);
1009 XSetWindowBorder(dpy, w, dc.norm[ColBorder]);
1010 configure(c); /* propagates border_width, if size doesn't change */
1012 XSelectInput(dpy, w, EnterWindowMask|FocusChangeMask|PropertyChangeMask|StructureNotifyMask);
1013 grabbuttons(c, False);
1015 if((rettrans = XGetTransientForHint(dpy, w, &trans) == Success))
1016 for(t = clients; t && t->win != trans; t = t->next);
1018 memcpy(c->tags, t->tags, TAGSZ);
1022 c->isfloating = (rettrans == Success) || c->isfixed;
1025 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h); /* some windows require this */
1027 XMapWindow(dpy, c->win);
1028 setclientstate(c, NormalState);
1033 mappingnotify(XEvent *e) {
1034 XMappingEvent *ev = &e->xmapping;
1036 XRefreshKeyboardMapping(ev);
1037 if(ev->request == MappingKeyboard)
1042 maprequest(XEvent *e) {
1043 static XWindowAttributes wa;
1044 XMapRequestEvent *ev = &e->xmaprequest;
1046 if(!XGetWindowAttributes(dpy, ev->window, &wa))
1048 if(wa.override_redirect)
1050 if(!getclient(ev->window))
1051 manage(ev->window, &wa);
1058 for(c = clients; c; c = c->next)
1060 resize(c, mox, moy, mow, moh, RESIZEHINTS);
1064 movemouse(Client *c) {
1065 int x1, y1, ocx, ocy, di, nx, ny;
1072 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1073 None, cursor[CurMove], CurrentTime) != GrabSuccess)
1075 XQueryPointer(dpy, root, &dummy, &dummy, &x1, &y1, &di, &di, &dui);
1077 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
1080 XUngrabPointer(dpy, CurrentTime);
1082 case ConfigureRequest:
1085 handler[ev.type](&ev);
1089 nx = ocx + (ev.xmotion.x - x1);
1090 ny = ocy + (ev.xmotion.y - y1);
1091 if(abs(wx - nx) < SNAP)
1093 else if(abs((wx + ww) - (nx + c->w + 2 * c->border)) < SNAP)
1094 nx = wx + ww - c->w - 2 * c->border;
1095 if(abs(wy - ny) < SNAP)
1097 else if(abs((wy + wh) - (ny + c->h + 2 * c->border)) < SNAP)
1098 ny = wy + wh - c->h - 2 * c->border;
1099 if(!c->isfloating && !lt->isfloating && (abs(nx - c->x) > SNAP || abs(ny - c->y) > SNAP))
1100 togglefloating(NULL);
1101 if((lt->isfloating) || c->isfloating)
1102 resize(c, nx, ny, c->w, c->h, False);
1109 nexttiled(Client *c) {
1110 for(; c && (c->isfloating || !isvisible(c)); c = c->next);
1115 propertynotify(XEvent *e) {
1118 XPropertyEvent *ev = &e->xproperty;
1120 if(ev->state == PropertyDelete)
1121 return; /* ignore */
1122 if((c = getclient(ev->window))) {
1125 case XA_WM_TRANSIENT_FOR:
1126 XGetTransientForHint(dpy, c->win, &trans);
1127 if(!c->isfloating && (c->isfloating = (getclient(trans) != NULL)))
1130 case XA_WM_NORMAL_HINTS:
1138 if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
1147 quit(const char *arg) {
1148 readin = running = False;
1152 reapply(const char *arg) {
1153 static Bool zerotags[LENGTH(tags)] = { 0 };
1156 for(c = clients; c; c = c->next) {
1157 memcpy(c->tags, zerotags, sizeof zerotags);
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)
1208 x = sw - w - 2 * c->border;
1210 y = sh - h - 2 * c->border;
1211 if(x + w + 2 * c->border < sx)
1213 if(y + h + 2 * c->border < sy)
1215 if(c->x != x || c->y != y || c->w != w || c->h != h) {
1218 c->w = wc.width = w;
1219 c->h = wc.height = h;
1220 wc.border_width = c->border;
1221 XConfigureWindow(dpy, c->win,
1222 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)
1239 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->border - 1, c->h + c->border - 1);
1241 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask , &ev);
1244 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0,
1245 c->w + c->border - 1, c->h + c->border - 1);
1246 XUngrabPointer(dpy, CurrentTime);
1247 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1249 case ConfigureRequest:
1252 handler[ev.type](&ev);
1256 if((nw = ev.xmotion.x - ocx - 2 * c->border + 1) <= 0)
1258 if((nh = ev.xmotion.y - ocy - 2 * c->border + 1) <= 0)
1260 if(!c->isfloating && !lt->isfloating && (abs(nw - c->w) > SNAP || abs(nh - c->h) > SNAP))
1261 togglefloating(NULL);
1262 if((lt->isfloating) || c->isfloating)
1263 resize(c, c->x, c->y, nw, nh, True);
1278 if(sel->isfloating || lt->isfloating)
1279 XRaiseWindow(dpy, sel->win);
1280 if(!lt->isfloating) {
1281 wc.stack_mode = Below;
1282 wc.sibling = barwin;
1283 if(!sel->isfloating) {
1284 XConfigureWindow(dpy, sel->win, CWSibling|CWStackMode, &wc);
1285 wc.sibling = sel->win;
1287 for(c = nexttiled(clients); c; c = nexttiled(c->next)) {
1290 XConfigureWindow(dpy, c->win, CWSibling|CWStackMode, &wc);
1291 wc.sibling = c->win;
1295 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1301 char sbuf[sizeof stext];
1304 unsigned int len, offset;
1307 /* main event loop, also reads status text from stdin */
1309 xfd = ConnectionNumber(dpy);
1312 len = sizeof stext - 1;
1313 sbuf[len] = stext[len] = '\0'; /* 0-terminator is never touched */
1317 FD_SET(STDIN_FILENO, &rd);
1319 if(select(xfd + 1, &rd, NULL, NULL, NULL) == -1) {
1322 eprint("select failed\n");
1324 if(FD_ISSET(STDIN_FILENO, &rd)) {
1325 switch((r = read(STDIN_FILENO, sbuf + offset, len - offset))) {
1327 strncpy(stext, strerror(errno), len);
1331 strncpy(stext, "EOF", 4);
1335 for(p = sbuf + offset; r > 0; p++, r--, offset++)
1336 if(*p == '\n' || *p == '\0') {
1338 strncpy(stext, sbuf, len);
1339 p += r - 1; /* p is sbuf + offset + r - 1 */
1340 for(r = 0; *(p - r) && *(p - r) != '\n'; r++);
1343 memmove(sbuf, p - r + 1, r);
1350 while(XPending(dpy)) {
1351 XNextEvent(dpy, &ev);
1352 if(handler[ev.type])
1353 (handler[ev.type])(&ev); /* call handler */
1360 unsigned int i, num;
1361 Window *wins, d1, d2;
1362 XWindowAttributes wa;
1365 if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1366 for(i = 0; i < num; i++) {
1367 if(!XGetWindowAttributes(dpy, wins[i], &wa)
1368 || wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1370 if(wa.map_state == IsViewable || getstate(wins[i]) == IconicState)
1371 manage(wins[i], &wa);
1373 for(i = 0; i < num; i++) { /* now the transients */
1374 if(!XGetWindowAttributes(dpy, wins[i], &wa))
1376 if(XGetTransientForHint(dpy, wins[i], &d1)
1377 && (wa.map_state == IsViewable || getstate(wins[i]) == IconicState))
1378 manage(wins[i], &wa);
1386 setclientstate(Client *c, long state) {
1387 long data[] = {state, None};
1389 XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1390 PropModeReplace, (unsigned char *)data, 2);
1394 setdefaultgeoms(void) {
1396 /* screen dimensions */
1399 sw = DisplayWidth(dpy, screen);
1400 sh = DisplayHeight(dpy, screen);
1406 bh = dc.font.height + 2;
1417 mw = ((float)sw) * 0.55;
1434 setlayout(const char *arg) {
1435 static Layout *revert = 0;
1440 for(i = 0; i < LENGTH(layouts); i++)
1441 if(!strcmp(arg, layouts[i].symbol))
1443 if(i == LENGTH(layouts))
1445 if(revert && &layouts[i] == lt)
1460 XSetWindowAttributes wa;
1463 screen = DefaultScreen(dpy);
1464 root = RootWindow(dpy, screen);
1467 /* apply default geometries */
1471 wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1472 wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1473 wmatom[WMName] = XInternAtom(dpy, "WM_NAME", False);
1474 wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1475 netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1476 netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1479 wa.cursor = cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1480 cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1481 cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1483 /* init appearance */
1484 dc.norm[ColBorder] = getcolor(NORMBORDERCOLOR);
1485 dc.norm[ColBG] = getcolor(NORMBGCOLOR);
1486 dc.norm[ColFG] = getcolor(NORMFGCOLOR);
1487 dc.sel[ColBorder] = getcolor(SELBORDERCOLOR);
1488 dc.sel[ColBG] = getcolor(SELBGCOLOR);
1489 dc.sel[ColFG] = getcolor(SELFGCOLOR);
1492 dc.drawable = XCreatePixmap(dpy, root, DisplayWidth(dpy, screen), bh, DefaultDepth(dpy, screen));
1493 dc.gc = XCreateGC(dpy, root, 0, 0);
1494 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
1496 XSetFont(dpy, dc.gc, dc.font.xfont->fid);
1499 seltags = emallocz(TAGSZ);
1500 prevtags = emallocz(TAGSZ);
1501 seltags[0] = prevtags[0] = True;
1507 for(blw = i = 0; i < LENGTH(layouts); i++) {
1508 i = textw(layouts[i].symbol);
1513 wa.override_redirect = 1;
1514 wa.background_pixmap = ParentRelative;
1515 wa.event_mask = ButtonPressMask|ExposureMask;
1517 barwin = XCreateWindow(dpy, root, bx, by, bw, bh, 0, DefaultDepth(dpy, screen),
1518 CopyFromParent, DefaultVisual(dpy, screen),
1519 CWOverrideRedirect|CWBackPixmap|CWEventMask, &wa);
1520 XDefineCursor(dpy, barwin, cursor[CurNormal]);
1521 XMapRaised(dpy, barwin);
1522 strcpy(stext, "dwm-"VERSION);
1525 /* EWMH support per view */
1526 XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1527 PropModeReplace, (unsigned char *) netatom, NetLast);
1529 /* select for events */
1530 wa.event_mask = SubstructureRedirectMask|SubstructureNotifyMask
1531 |EnterWindowMask|LeaveWindowMask|StructureNotifyMask;
1532 XChangeWindowAttributes(dpy, root, CWEventMask|CWCursor, &wa);
1533 XSelectInput(dpy, root, wa.event_mask);
1541 spawn(const char *arg) {
1542 static char *shell = NULL;
1544 if(!shell && !(shell = getenv("SHELL")))
1548 /* The double-fork construct avoids zombie processes and keeps the code
1549 * clean from stupid signal handlers. */
1553 close(ConnectionNumber(dpy));
1555 execl(shell, shell, "-c", arg, (char *)NULL);
1556 fprintf(stderr, "dwm: execl '%s -c %s'", shell, arg);
1565 tag(const char *arg) {
1570 for(i = 0; i < LENGTH(tags); i++)
1571 sel->tags[i] = (NULL == arg);
1572 sel->tags[idxoftag(arg)] = True;
1577 textnw(const char *text, unsigned int len) {
1581 XmbTextExtents(dc.font.set, text, len, NULL, &r);
1584 return XTextWidth(dc.font.xfont, text, len);
1588 textw(const char *text) {
1589 return textnw(text, strlen(text)) + dc.font.height;
1595 unsigned int i, n = counttiled();
1609 for(i = 0, c = nexttiled(c->next); c; c = nexttiled(c->next), i++) {
1610 if(i + 1 == n) /* remainder */
1611 tileresize(c, x, ty, (tx + tw) - x - 2 * c->border, th - 2 * c->border);
1613 tileresize(c, x, ty, w - 2 * c->border, th - 2 * c->border);
1615 x = c->x + c->w + 2 * c->border;
1620 tilemaster(unsigned int n) {
1621 Client *c = nexttiled(clients);
1624 tileresize(c, mox, moy, mow - 2 * c->border, moh - 2 * c->border);
1626 tileresize(c, mx, my, mw - 2 * c->border, mh - 2 * c->border);
1631 tileresize(Client *c, int x, int y, int w, int h) {
1632 resize(c, x, y, w, h, RESIZEHINTS);
1633 if((RESIZEHINTS) && ((c->h < bh) || (c->h > h) || (c->w < bh) || (c->w > w)))
1634 /* client doesn't accept size constraints */
1635 resize(c, x, y, w, h, False);
1641 unsigned int i, n = counttiled();
1655 for(i = 0, c = nexttiled(c->next); c; c = nexttiled(c->next), i++) {
1656 if(i + 1 == n) /* remainder */
1657 tileresize(c, tx, y, tw - 2 * c->border, (ty + th) - y - 2 * c->border);
1659 tileresize(c, tx, y, tw - 2 * c->border, h - 2 * c->border);
1661 y = c->y + c->h + 2 * c->border;
1666 togglefloating(const char *arg) {
1669 sel->isfloating = !sel->isfloating;
1671 resize(sel, sel->x, sel->y, sel->w, sel->h, True);
1676 toggletag(const char *arg) {
1682 sel->tags[i] = !sel->tags[i];
1683 for(j = 0; j < LENGTH(tags) && !sel->tags[j]; j++);
1684 if(j == LENGTH(tags))
1685 sel->tags[i] = True; /* at least one tag must be enabled */
1690 toggleview(const char *arg) {
1694 seltags[i] = !seltags[i];
1695 for(j = 0; j < LENGTH(tags) && !seltags[j]; j++);
1696 if(j == LENGTH(tags))
1697 seltags[i] = True; /* at least one tag must be viewed */
1705 XMoveWindow(dpy, c->win, c->x, c->y);
1706 c->isbanned = False;
1710 unmanage(Client *c) {
1713 wc.border_width = c->oldborder;
1714 /* The server grab construct avoids race conditions. */
1716 XSetErrorHandler(xerrordummy);
1717 XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
1722 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1723 setclientstate(c, WithdrawnState);
1727 XSetErrorHandler(xerror);
1733 unmapnotify(XEvent *e) {
1735 XUnmapEvent *ev = &e->xunmap;
1737 if((c = getclient(ev->window)))
1742 updatebarpos(void) {
1744 if(dc.drawable != 0)
1745 XFreePixmap(dpy, dc.drawable);
1746 dc.drawable = XCreatePixmap(dpy, root, bw, bh, DefaultDepth(dpy, screen));
1747 XMoveResizeWindow(dpy, barwin, bx, by, bw, bh);
1751 updatesizehints(Client *c) {
1755 if(!XGetWMNormalHints(dpy, c->win, &size, &msize) || !size.flags)
1757 c->flags = size.flags;
1758 if(c->flags & PBaseSize) {
1759 c->basew = size.base_width;
1760 c->baseh = size.base_height;
1762 else if(c->flags & PMinSize) {
1763 c->basew = size.min_width;
1764 c->baseh = size.min_height;
1767 c->basew = c->baseh = 0;
1768 if(c->flags & PResizeInc) {
1769 c->incw = size.width_inc;
1770 c->inch = size.height_inc;
1773 c->incw = c->inch = 0;
1774 if(c->flags & PMaxSize) {
1775 c->maxw = size.max_width;
1776 c->maxh = size.max_height;
1779 c->maxw = c->maxh = 0;
1780 if(c->flags & PMinSize) {
1781 c->minw = size.min_width;
1782 c->minh = size.min_height;
1784 else if(c->flags & PBaseSize) {
1785 c->minw = size.base_width;
1786 c->minh = size.base_height;
1789 c->minw = c->minh = 0;
1790 if(c->flags & PAspect) {
1791 c->minax = size.min_aspect.x;
1792 c->maxax = size.max_aspect.x;
1793 c->minay = size.min_aspect.y;
1794 c->maxay = size.max_aspect.y;
1797 c->minax = c->maxax = c->minay = c->maxay = 0;
1798 c->isfixed = (c->maxw && c->minw && c->maxh && c->minh
1799 && c->maxw == c->minw && c->maxh == c->minh);
1803 updatetitle(Client *c) {
1804 if(!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
1805 gettextprop(c->win, wmatom[WMName], c->name, sizeof c->name);
1809 updatewmhints(Client *c) {
1812 if((wmh = XGetWMHints(dpy, c->win))) {
1814 sel->isurgent = False;
1816 c->isurgent = (wmh->flags & XUrgencyHint) ? True : False;
1823 view(const char *arg) {
1826 for(i = 0; i < LENGTH(tags); i++)
1827 tmp[i] = (NULL == arg);
1828 tmp[idxoftag(arg)] = True;
1830 if(memcmp(seltags, tmp, TAGSZ) != 0) {
1831 memcpy(prevtags, seltags, TAGSZ);
1832 memcpy(seltags, tmp, TAGSZ);
1838 viewprevtag(const char *arg) {
1840 memcpy(tmp, seltags, TAGSZ);
1841 memcpy(seltags, prevtags, TAGSZ);
1842 memcpy(prevtags, tmp, TAGSZ);
1846 /* There's no way to check accesses to destroyed windows, thus those cases are
1847 * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
1848 * default error handler, which may call exit. */
1850 xerror(Display *dpy, XErrorEvent *ee) {
1851 if(ee->error_code == BadWindow
1852 || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1853 || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1854 || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1855 || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1856 || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1857 || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1858 || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1860 fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1861 ee->request_code, ee->error_code);
1862 return xerrorxlib(dpy, ee); /* may call exit */
1866 xerrordummy(Display *dpy, XErrorEvent *ee) {
1870 /* Startup Error handler to check if another window manager
1871 * is already running. */
1873 xerrorstart(Display *dpy, XErrorEvent *ee) {
1879 zoom(const char *arg) {
1882 if(!sel || lt->isfloating || sel->isfloating)
1884 if(c == nexttiled(clients))
1885 if(!(c = nexttiled(c->next)))
1894 main(int argc, char *argv[]) {
1895 if(argc == 2 && !strcmp("-v", argv[1]))
1896 eprint("dwm-"VERSION", © 2006-2008 dwm engineers, see LICENSE for details\n");
1898 eprint("usage: dwm [-v]\n");
1900 setlocale(LC_CTYPE, "");
1901 if(!(dpy = XOpenDisplay(0)))
1902 eprint("dwm: cannot open display\n");