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);
107 /* function declarations */
108 void applyrules(Client *c);
110 void attach(Client *c);
111 void attachstack(Client *c);
113 void buttonpress(XEvent *e);
114 void checkotherwm(void);
116 void configure(Client *c);
117 void configurenotify(XEvent *e);
118 void configurerequest(XEvent *e);
119 unsigned int counttiled(void);
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 setdefaultgeoms(void);
165 void setlayout(const char *arg);
167 void spawn(const char *arg);
168 void tag(const char *arg);
169 unsigned int textnw(const char *text, unsigned int len);
170 unsigned int textw(const char *text);
172 void tilehstack(unsigned int n);
173 Client *tilemaster(unsigned int n);
174 void tileresize(Client *c, int x, int y, int w, int h);
176 void tilevstack(unsigned int n);
177 void togglefloating(const char *arg);
178 void toggletag(const char *arg);
179 void toggleview(const char *arg);
180 void unban(Client *c);
181 void unmanage(Client *c);
182 void unmapnotify(XEvent *e);
183 void updatebarpos(void);
184 void updatesizehints(Client *c);
185 void updatetitle(Client *c);
186 void updatewmhints(Client *c);
187 void view(const char *arg);
188 void viewprevtag(const char *arg); /* views previous selected tags */
189 int xerror(Display *dpy, XErrorEvent *ee);
190 int xerrordummy(Display *dpy, XErrorEvent *ee);
191 int xerrorstart(Display *dpy, XErrorEvent *ee);
192 void zoom(const char *arg);
195 char stext[256], buf[256];
196 int screen, sx, sy, sw, sh;
197 int (*xerrorxlib)(Display *, XErrorEvent *);
198 int bx, by, bw, bh, blw, mx, my, mw, mh, mox, moy, mow, moh, tx, ty, tw, th, wx, wy, ww, wh;
199 unsigned int numlockmask = 0;
200 void (*handler[LASTEvent]) (XEvent *) = {
201 [ButtonPress] = buttonpress,
202 [ConfigureRequest] = configurerequest,
203 [ConfigureNotify] = configurenotify,
204 [DestroyNotify] = destroynotify,
205 [EnterNotify] = enternotify,
208 [KeyPress] = keypress,
209 [MappingNotify] = mappingnotify,
210 [MapRequest] = maprequest,
211 [PropertyNotify] = propertynotify,
212 [UnmapNotify] = unmapnotify
214 Atom wmatom[WMLast], netatom[NetLast];
215 Bool otherwm, readin;
219 Client *clients = NULL;
221 Client *stack = NULL;
222 Cursor cursor[CurLast];
227 void (*setgeoms)(void) = setdefaultgeoms;
229 /* configuration, allows nested code to access above variables */
231 #define TAGSZ (LENGTH(tags) * sizeof(Bool))
232 static Bool tmp[LENGTH(tags)];
234 /* function implementations */
237 applyrules(Client *c) {
239 Bool matched = False;
241 XClassHint ch = { 0 };
244 XGetClassHint(dpy, c->win, &ch);
245 for(i = 0; i < LENGTH(rules); i++) {
247 if(strstr(c->name, r->prop)
248 || (ch.res_class && strstr(ch.res_class, r->prop))
249 || (ch.res_name && strstr(ch.res_name, r->prop)))
251 c->isfloating = r->isfloating;
253 c->tags[idxoftag(r->tag)] = True;
263 memcpy(c->tags, seltags, TAGSZ);
270 for(c = clients; c; c = c->next)
290 attachstack(Client *c) {
299 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
304 buttonpress(XEvent *e) {
307 XButtonPressedEvent *ev = &e->xbutton;
309 if(ev->window == barwin) {
311 for(i = 0; i < LENGTH(tags); i++) {
314 if(ev->button == Button1) {
315 if(ev->state & MODKEY)
320 else if(ev->button == Button3) {
321 if(ev->state & MODKEY)
330 else if((c = getclient(ev->window))) {
332 if(CLEANMASK(ev->state) != MODKEY)
334 if(ev->button == Button1) {
338 else if(ev->button == Button2) {
339 if((floating != lt->arrange) && c->isfloating)
340 togglefloating(NULL);
344 else if(ev->button == Button3 && !c->isfixed) {
354 XSetErrorHandler(xerrorstart);
356 /* this causes an error if some other window manager is running */
357 XSelectInput(dpy, DefaultRootWindow(dpy), SubstructureRedirectMask);
360 eprint("dwm: another window manager is already running\n");
362 XSetErrorHandler(NULL);
363 xerrorxlib = XSetErrorHandler(xerror);
375 XFreeFontSet(dpy, dc.font.set);
377 XFreeFont(dpy, dc.font.xfont);
378 XUngrabKey(dpy, AnyKey, AnyModifier, root);
379 XFreePixmap(dpy, dc.drawable);
381 XFreeCursor(dpy, cursor[CurNormal]);
382 XFreeCursor(dpy, cursor[CurResize]);
383 XFreeCursor(dpy, cursor[CurMove]);
384 XDestroyWindow(dpy, barwin);
386 XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime);
390 configure(Client *c) {
393 ce.type = ConfigureNotify;
401 ce.border_width = c->border;
403 ce.override_redirect = False;
404 XSendEvent(dpy, c->win, False, StructureNotifyMask, (XEvent *)&ce);
408 configurenotify(XEvent *e) {
409 XConfigureEvent *ev = &e->xconfigure;
411 if(ev->window == root && (ev->width != sw || ev->height != sh)) {
419 configurerequest(XEvent *e) {
421 XConfigureRequestEvent *ev = &e->xconfigurerequest;
424 if((c = getclient(ev->window))) {
425 if(ev->value_mask & CWBorderWidth)
426 c->border = ev->border_width;
427 if(c->isfixed || c->isfloating || lt->isfloating) {
428 if(ev->value_mask & CWX)
430 if(ev->value_mask & CWY)
432 if(ev->value_mask & CWWidth)
434 if(ev->value_mask & CWHeight)
436 if((c->x - sx + c->w) > sw && c->isfloating)
437 c->x = sx + (sw / 2 - c->w / 2); /* center in x direction */
438 if((c->y - sy + c->h) > sh && c->isfloating)
439 c->y = sy + (sh / 2 - c->h / 2); /* center in y direction */
440 if((ev->value_mask & (CWX|CWY))
441 && !(ev->value_mask & (CWWidth|CWHeight)))
444 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h);
452 wc.width = ev->width;
453 wc.height = ev->height;
454 wc.border_width = ev->border_width;
455 wc.sibling = ev->above;
456 wc.stack_mode = ev->detail;
457 XConfigureWindow(dpy, ev->window, ev->value_mask, &wc);
467 for(n = 0, c = nexttiled(clients); c; c = nexttiled(c->next), n++);
472 destroynotify(XEvent *e) {
474 XDestroyWindowEvent *ev = &e->xdestroywindow;
476 if((c = getclient(ev->window)))
483 c->prev->next = c->next;
485 c->next->prev = c->prev;
488 c->next = c->prev = NULL;
492 detachstack(Client *c) {
495 for(tc=&stack; *tc && *tc != c; tc=&(*tc)->snext);
505 for(c = stack; c && !isvisible(c); c = c->snext);
506 for(i = 0; i < LENGTH(tags); i++) {
507 dc.w = textw(tags[i]);
509 drawtext(tags[i], dc.sel, isurgent(i));
510 drawsquare(c && c->tags[i], isoccupied(i), isurgent(i), dc.sel);
513 drawtext(tags[i], dc.norm, isurgent(i));
514 drawsquare(c && c->tags[i], isoccupied(i), isurgent(i), dc.norm);
519 drawtext(lt->symbol, dc.norm, False);
527 drawtext(stext, dc.norm, False);
528 if((dc.w = dc.x - x) > bh) {
531 drawtext(c->name, dc.sel, False);
532 drawsquare(False, c->isfloating, False, dc.sel);
535 drawtext(NULL, dc.norm, False);
537 XCopyArea(dpy, dc.drawable, barwin, dc.gc, 0, 0, bw, bh, 0, 0);
542 drawsquare(Bool filled, Bool empty, Bool invert, unsigned long col[ColLast]) {
545 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
547 gcv.foreground = col[invert ? ColBG : ColFG];
548 XChangeGC(dpy, dc.gc, GCForeground, &gcv);
549 x = (dc.font.ascent + dc.font.descent + 2) / 4;
553 r.width = r.height = x + 1;
554 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
557 r.width = r.height = x;
558 XDrawRectangles(dpy, dc.drawable, dc.gc, &r, 1);
563 drawtext(const char *text, unsigned long col[ColLast], Bool invert) {
565 unsigned int len, olen;
566 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
568 XSetForeground(dpy, dc.gc, col[invert ? ColFG : ColBG]);
569 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
573 olen = len = strlen(text);
574 if(len >= sizeof buf)
575 len = sizeof buf - 1;
576 memcpy(buf, text, len);
578 h = dc.font.ascent + dc.font.descent;
579 y = dc.y + (dc.h / 2) - (h / 2) + dc.font.ascent;
581 /* shorten text if necessary */
582 while(len && (w = textnw(buf, len)) > dc.w - h)
593 return; /* too long */
594 XSetForeground(dpy, dc.gc, col[invert ? ColBG : ColFG]);
596 XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
598 XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
602 emallocz(unsigned int size) {
603 void *res = calloc(1, size);
606 eprint("fatal: could not malloc() %u bytes\n", size);
611 enternotify(XEvent *e) {
613 XCrossingEvent *ev = &e->xcrossing;
615 if((ev->mode != NotifyNormal || ev->detail == NotifyInferior) && ev->window != root)
617 if((c = getclient(ev->window)))
624 eprint(const char *errstr, ...) {
627 va_start(ap, errstr);
628 vfprintf(stderr, errstr, ap);
635 XExposeEvent *ev = &e->xexpose;
637 if(ev->count == 0 && (ev->window == barwin))
642 floating(void) { /* default floating layout */
645 for(c = clients; c; c = c->next)
647 resize(c, c->x, c->y, c->w, c->h, True);
652 if(!c || (c && !isvisible(c)))
653 for(c = stack; c && !isvisible(c); c = c->snext);
654 if(sel && sel != c) {
655 grabbuttons(sel, False);
656 XSetWindowBorder(dpy, sel->win, dc.norm[ColBorder]);
661 grabbuttons(c, True);
665 XSetWindowBorder(dpy, c->win, dc.sel[ColBorder]);
666 XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
669 XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
674 focusin(XEvent *e) { /* there are some broken focus acquiring clients */
675 XFocusChangeEvent *ev = &e->xfocus;
677 if(sel && ev->window != sel->win)
678 XSetInputFocus(dpy, sel->win, RevertToPointerRoot, CurrentTime);
682 focusnext(const char *arg) {
687 for(c = sel->next; c && !isvisible(c); c = c->next);
689 for(c = clients; c && !isvisible(c); c = c->next);
697 focusprev(const char *arg) {
702 for(c = sel->prev; c && !isvisible(c); c = c->prev);
704 for(c = clients; c && c->next; c = c->next);
705 for(; c && !isvisible(c); c = c->prev);
714 getclient(Window w) {
717 for(c = clients; c && c->win != w; c = c->next);
722 getcolor(const char *colstr) {
723 Colormap cmap = DefaultColormap(dpy, screen);
726 if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
727 eprint("error, cannot allocate color '%s'\n", colstr);
735 unsigned char *p = NULL;
736 unsigned long n, extra;
739 status = XGetWindowProperty(dpy, w, wmatom[WMState], 0L, 2L, False, wmatom[WMState],
740 &real, &format, &n, &extra, (unsigned char **)&p);
741 if(status != Success)
750 gettextprop(Window w, Atom atom, char *text, unsigned int size) {
755 if(!text || size == 0)
758 XGetTextProperty(dpy, w, &name, atom);
761 if(name.encoding == XA_STRING)
762 strncpy(text, (char *)name.value, size - 1);
764 if(XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success
766 strncpy(text, *list, size - 1);
767 XFreeStringList(list);
770 text[size - 1] = '\0';
776 grabbuttons(Client *c, Bool focused) {
777 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
780 XGrabButton(dpy, Button1, MODKEY, c->win, False, BUTTONMASK,
781 GrabModeAsync, GrabModeSync, None, None);
782 XGrabButton(dpy, Button1, MODKEY|LockMask, c->win, False, BUTTONMASK,
783 GrabModeAsync, GrabModeSync, None, None);
784 XGrabButton(dpy, Button1, MODKEY|numlockmask, c->win, False, BUTTONMASK,
785 GrabModeAsync, GrabModeSync, None, None);
786 XGrabButton(dpy, Button1, MODKEY|numlockmask|LockMask, c->win, False, BUTTONMASK,
787 GrabModeAsync, GrabModeSync, None, None);
789 XGrabButton(dpy, Button2, MODKEY, c->win, False, BUTTONMASK,
790 GrabModeAsync, GrabModeSync, None, None);
791 XGrabButton(dpy, Button2, MODKEY|LockMask, c->win, False, BUTTONMASK,
792 GrabModeAsync, GrabModeSync, None, None);
793 XGrabButton(dpy, Button2, MODKEY|numlockmask, c->win, False, BUTTONMASK,
794 GrabModeAsync, GrabModeSync, None, None);
795 XGrabButton(dpy, Button2, MODKEY|numlockmask|LockMask, c->win, False, BUTTONMASK,
796 GrabModeAsync, GrabModeSync, None, None);
798 XGrabButton(dpy, Button3, MODKEY, c->win, False, BUTTONMASK,
799 GrabModeAsync, GrabModeSync, None, None);
800 XGrabButton(dpy, Button3, MODKEY|LockMask, c->win, False, BUTTONMASK,
801 GrabModeAsync, GrabModeSync, None, None);
802 XGrabButton(dpy, Button3, MODKEY|numlockmask, c->win, False, BUTTONMASK,
803 GrabModeAsync, GrabModeSync, None, None);
804 XGrabButton(dpy, Button3, MODKEY|numlockmask|LockMask, c->win, False, BUTTONMASK,
805 GrabModeAsync, GrabModeSync, None, None);
808 XGrabButton(dpy, AnyButton, AnyModifier, c->win, False, BUTTONMASK,
809 GrabModeAsync, GrabModeSync, None, None);
816 XModifierKeymap *modmap;
818 /* init modifier map */
819 modmap = XGetModifierMapping(dpy);
820 for(i = 0; i < 8; i++)
821 for(j = 0; j < modmap->max_keypermod; j++) {
822 if(modmap->modifiermap[i * modmap->max_keypermod + j] == XKeysymToKeycode(dpy, XK_Num_Lock))
823 numlockmask = (1 << i);
825 XFreeModifiermap(modmap);
827 XUngrabKey(dpy, AnyKey, AnyModifier, root);
828 for(i = 0; i < LENGTH(keys); i++) {
829 code = XKeysymToKeycode(dpy, keys[i].keysym);
830 XGrabKey(dpy, code, keys[i].mod, root, True,
831 GrabModeAsync, GrabModeAsync);
832 XGrabKey(dpy, code, keys[i].mod|LockMask, root, True,
833 GrabModeAsync, GrabModeAsync);
834 XGrabKey(dpy, code, keys[i].mod|numlockmask, root, True,
835 GrabModeAsync, GrabModeAsync);
836 XGrabKey(dpy, code, keys[i].mod|numlockmask|LockMask, root, True,
837 GrabModeAsync, GrabModeAsync);
842 idxoftag(const char *t) {
845 for(i = 0; (i < LENGTH(tags)) && (tags[i] != t); i++);
846 return (i < LENGTH(tags)) ? i : 0;
850 initfont(const char *fontstr) {
851 char *def, **missing;
856 XFreeFontSet(dpy, dc.font.set);
857 dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
860 fprintf(stderr, "dwm: missing fontset: %s\n", missing[n]);
861 XFreeStringList(missing);
864 XFontSetExtents *font_extents;
865 XFontStruct **xfonts;
867 dc.font.ascent = dc.font.descent = 0;
868 font_extents = XExtentsOfFontSet(dc.font.set);
869 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
870 for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
871 if(dc.font.ascent < (*xfonts)->ascent)
872 dc.font.ascent = (*xfonts)->ascent;
873 if(dc.font.descent < (*xfonts)->descent)
874 dc.font.descent = (*xfonts)->descent;
880 XFreeFont(dpy, dc.font.xfont);
881 dc.font.xfont = NULL;
882 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr))
883 && !(dc.font.xfont = XLoadQueryFont(dpy, "fixed")))
884 eprint("error, cannot load font: '%s'\n", fontstr);
885 dc.font.ascent = dc.font.xfont->ascent;
886 dc.font.descent = dc.font.xfont->descent;
888 dc.font.height = dc.font.ascent + dc.font.descent;
892 isoccupied(unsigned int t) {
895 for(c = clients; c; c = c->next)
902 isprotodel(Client *c) {
907 if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
908 for(i = 0; !ret && i < n; i++)
909 if(protocols[i] == wmatom[WMDelete])
917 isurgent(unsigned int t) {
920 for(c = clients; c; c = c->next)
921 if(c->isurgent && c->tags[t])
927 isvisible(Client *c) {
930 for(i = 0; i < LENGTH(tags); i++)
931 if(c->tags[i] && seltags[i])
937 keypress(XEvent *e) {
943 keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
944 for(i = 0; i < LENGTH(keys); i++)
945 if(keysym == keys[i].keysym
946 && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state))
949 keys[i].func(keys[i].arg);
954 killclient(const char *arg) {
959 if(isprotodel(sel)) {
960 ev.type = ClientMessage;
961 ev.xclient.window = sel->win;
962 ev.xclient.message_type = wmatom[WMProtocols];
963 ev.xclient.format = 32;
964 ev.xclient.data.l[0] = wmatom[WMDelete];
965 ev.xclient.data.l[1] = CurrentTime;
966 XSendEvent(dpy, sel->win, False, NoEventMask, &ev);
969 XKillClient(dpy, sel->win);
973 manage(Window w, XWindowAttributes *wa) {
974 Client *c, *t = NULL;
979 c = emallocz(sizeof(Client));
980 c->tags = emallocz(TAGSZ);
988 c->oldborder = wa->border_width;
989 if(c->w == sw && c->h == sh) {
992 c->border = wa->border_width;
995 if(c->x + c->w + 2 * c->border > wx + ww)
996 c->x = wx + ww - c->w - 2 * c->border;
997 if(c->y + c->h + 2 * c->border > wy + wh)
998 c->y = wy + wh - c->h - 2 * c->border;
1003 c->border = BORDERPX;
1006 wc.border_width = c->border;
1007 XConfigureWindow(dpy, w, CWBorderWidth, &wc);
1008 XSetWindowBorder(dpy, w, dc.norm[ColBorder]);
1009 configure(c); /* propagates border_width, if size doesn't change */
1011 XSelectInput(dpy, w, EnterWindowMask|FocusChangeMask|PropertyChangeMask|StructureNotifyMask);
1012 grabbuttons(c, False);
1014 if((rettrans = XGetTransientForHint(dpy, w, &trans) == Success))
1015 for(t = clients; t && t->win != trans; t = t->next);
1017 memcpy(c->tags, t->tags, TAGSZ);
1021 c->isfloating = (rettrans == Success) || c->isfixed;
1024 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h); /* some windows require this */
1026 XMapWindow(dpy, c->win);
1027 setclientstate(c, NormalState);
1032 mappingnotify(XEvent *e) {
1033 XMappingEvent *ev = &e->xmapping;
1035 XRefreshKeyboardMapping(ev);
1036 if(ev->request == MappingKeyboard)
1041 maprequest(XEvent *e) {
1042 static XWindowAttributes wa;
1043 XMapRequestEvent *ev = &e->xmaprequest;
1045 if(!XGetWindowAttributes(dpy, ev->window, &wa))
1047 if(wa.override_redirect)
1049 if(!getclient(ev->window))
1050 manage(ev->window, &wa);
1057 for(c = clients; c; c = c->next)
1059 resize(c, mox, moy, mow, moh, RESIZEHINTS);
1063 movemouse(Client *c) {
1064 int x1, y1, ocx, ocy, di, nx, ny;
1071 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1072 None, cursor[CurMove], CurrentTime) != GrabSuccess)
1074 XQueryPointer(dpy, root, &dummy, &dummy, &x1, &y1, &di, &di, &dui);
1076 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
1079 XUngrabPointer(dpy, CurrentTime);
1081 case ConfigureRequest:
1084 handler[ev.type](&ev);
1088 nx = ocx + (ev.xmotion.x - x1);
1089 ny = ocy + (ev.xmotion.y - y1);
1090 if(abs(wx - nx) < SNAP)
1092 else if(abs((wx + ww) - (nx + c->w + 2 * c->border)) < SNAP)
1093 nx = wx + ww - c->w - 2 * c->border;
1094 if(abs(wy - ny) < SNAP)
1096 else if(abs((wy + wh) - (ny + c->h + 2 * c->border)) < SNAP)
1097 ny = wy + wh - c->h - 2 * c->border;
1098 if(!c->isfloating && !lt->isfloating && (abs(nx - c->x) > SNAP || abs(ny - c->y) > SNAP))
1099 togglefloating(NULL);
1100 if((lt->isfloating) || c->isfloating)
1101 resize(c, nx, ny, c->w, c->h, False);
1108 nexttiled(Client *c) {
1109 for(; c && (c->isfloating || !isvisible(c)); c = c->next);
1114 propertynotify(XEvent *e) {
1117 XPropertyEvent *ev = &e->xproperty;
1119 if(ev->state == PropertyDelete)
1120 return; /* ignore */
1121 if((c = getclient(ev->window))) {
1124 case XA_WM_TRANSIENT_FOR:
1125 XGetTransientForHint(dpy, c->win, &trans);
1126 if(!c->isfloating && (c->isfloating = (getclient(trans) != NULL)))
1129 case XA_WM_NORMAL_HINTS:
1137 if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
1146 quit(const char *arg) {
1147 readin = running = False;
1151 reapply(const char *arg) {
1152 static Bool zerotags[LENGTH(tags)] = { 0 };
1155 for(c = clients; c; c = c->next) {
1156 memcpy(c->tags, zerotags, sizeof zerotags);
1163 resize(Client *c, int x, int y, int w, int h, Bool sizehints) {
1167 /* set minimum possible */
1173 /* temporarily remove base dimensions */
1177 /* adjust for aspect limits */
1178 if (c->minay > 0 && c->maxay > 0 && c->minax > 0 && c->maxax > 0) {
1179 if (w * c->maxay > h * c->maxax)
1180 w = h * c->maxax / c->maxay;
1181 else if (w * c->minay < h * c->minax)
1182 h = w * c->minay / c->minax;
1185 /* adjust for increment value */
1191 /* restore base dimensions */
1195 if(c->minw > 0 && w < c->minw)
1197 if(c->minh > 0 && h < c->minh)
1199 if(c->maxw > 0 && w > c->maxw)
1201 if(c->maxh > 0 && h > c->maxh)
1204 if(w <= 0 || h <= 0)
1207 x = sw - w - 2 * c->border;
1209 y = sh - h - 2 * c->border;
1210 if(x + w + 2 * c->border < sx)
1212 if(y + h + 2 * c->border < sy)
1214 if(c->x != x || c->y != y || c->w != w || c->h != h) {
1217 c->w = wc.width = w;
1218 c->h = wc.height = h;
1219 wc.border_width = c->border;
1220 XConfigureWindow(dpy, c->win,
1221 CWX|CWY|CWWidth|CWHeight|CWBorderWidth, &wc);
1228 resizemouse(Client *c) {
1235 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1236 None, cursor[CurResize], CurrentTime) != GrabSuccess)
1238 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->border - 1, c->h + c->border - 1);
1240 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask , &ev);
1243 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0,
1244 c->w + c->border - 1, c->h + c->border - 1);
1245 XUngrabPointer(dpy, CurrentTime);
1246 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1248 case ConfigureRequest:
1251 handler[ev.type](&ev);
1255 if((nw = ev.xmotion.x - ocx - 2 * c->border + 1) <= 0)
1257 if((nh = ev.xmotion.y - ocy - 2 * c->border + 1) <= 0)
1259 if(!c->isfloating && !lt->isfloating && (abs(nw - c->w) > SNAP || abs(nh - c->h) > SNAP))
1260 togglefloating(NULL);
1261 if((lt->isfloating) || c->isfloating)
1262 resize(c, c->x, c->y, nw, nh, True);
1277 if(sel->isfloating || lt->isfloating)
1278 XRaiseWindow(dpy, sel->win);
1279 if(!lt->isfloating) {
1280 wc.stack_mode = Below;
1281 wc.sibling = barwin;
1282 if(!sel->isfloating) {
1283 XConfigureWindow(dpy, sel->win, CWSibling|CWStackMode, &wc);
1284 wc.sibling = sel->win;
1286 for(c = nexttiled(clients); c; c = nexttiled(c->next)) {
1289 XConfigureWindow(dpy, c->win, CWSibling|CWStackMode, &wc);
1290 wc.sibling = c->win;
1294 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1300 char sbuf[sizeof stext];
1303 unsigned int len, offset;
1306 /* main event loop, also reads status text from stdin */
1308 xfd = ConnectionNumber(dpy);
1311 len = sizeof stext - 1;
1312 sbuf[len] = stext[len] = '\0'; /* 0-terminator is never touched */
1316 FD_SET(STDIN_FILENO, &rd);
1318 if(select(xfd + 1, &rd, NULL, NULL, NULL) == -1) {
1321 eprint("select failed\n");
1323 if(FD_ISSET(STDIN_FILENO, &rd)) {
1324 switch((r = read(STDIN_FILENO, sbuf + offset, len - offset))) {
1326 strncpy(stext, strerror(errno), len);
1330 strncpy(stext, "EOF", 4);
1334 for(p = sbuf + offset; r > 0; p++, r--, offset++)
1335 if(*p == '\n' || *p == '\0') {
1337 strncpy(stext, sbuf, len);
1338 p += r - 1; /* p is sbuf + offset + r - 1 */
1339 for(r = 0; *(p - r) && *(p - r) != '\n'; r++);
1342 memmove(sbuf, p - r + 1, r);
1349 while(XPending(dpy)) {
1350 XNextEvent(dpy, &ev);
1351 if(handler[ev.type])
1352 (handler[ev.type])(&ev); /* call handler */
1359 unsigned int i, num;
1360 Window *wins, d1, d2;
1361 XWindowAttributes wa;
1364 if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1365 for(i = 0; i < num; i++) {
1366 if(!XGetWindowAttributes(dpy, wins[i], &wa)
1367 || wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1369 if(wa.map_state == IsViewable || getstate(wins[i]) == IconicState)
1370 manage(wins[i], &wa);
1372 for(i = 0; i < num; i++) { /* now the transients */
1373 if(!XGetWindowAttributes(dpy, wins[i], &wa))
1375 if(XGetTransientForHint(dpy, wins[i], &d1)
1376 && (wa.map_state == IsViewable || getstate(wins[i]) == IconicState))
1377 manage(wins[i], &wa);
1385 setclientstate(Client *c, long state) {
1386 long data[] = {state, None};
1388 XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1389 PropModeReplace, (unsigned char *)data, 2);
1393 setdefaultgeoms(void) {
1395 /* screen dimensions */
1398 sw = DisplayWidth(dpy, screen);
1399 sh = DisplayHeight(dpy, screen);
1405 bh = dc.font.height + 2;
1416 mw = ((float)sw) * 0.55;
1433 setlayout(const char *arg) {
1434 static Layout *revert = 0;
1439 for(i = 0; i < LENGTH(layouts); i++)
1440 if(!strcmp(arg, layouts[i].symbol))
1442 if(i == LENGTH(layouts))
1444 if(revert && &layouts[i] == lt)
1459 XSetWindowAttributes wa;
1462 screen = DefaultScreen(dpy);
1463 root = RootWindow(dpy, screen);
1466 /* apply default geometries */
1470 wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1471 wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1472 wmatom[WMName] = XInternAtom(dpy, "WM_NAME", False);
1473 wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1474 netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1475 netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1478 wa.cursor = cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1479 cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1480 cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1482 /* init appearance */
1483 dc.norm[ColBorder] = getcolor(NORMBORDERCOLOR);
1484 dc.norm[ColBG] = getcolor(NORMBGCOLOR);
1485 dc.norm[ColFG] = getcolor(NORMFGCOLOR);
1486 dc.sel[ColBorder] = getcolor(SELBORDERCOLOR);
1487 dc.sel[ColBG] = getcolor(SELBGCOLOR);
1488 dc.sel[ColFG] = getcolor(SELFGCOLOR);
1491 dc.drawable = XCreatePixmap(dpy, root, DisplayWidth(dpy, screen), bh, DefaultDepth(dpy, screen));
1492 dc.gc = XCreateGC(dpy, root, 0, 0);
1493 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
1495 XSetFont(dpy, dc.gc, dc.font.xfont->fid);
1498 seltags = emallocz(TAGSZ);
1499 prevtags = emallocz(TAGSZ);
1500 seltags[0] = prevtags[0] = True;
1506 for(blw = i = 0; i < LENGTH(layouts); i++) {
1507 i = textw(layouts[i].symbol);
1512 wa.override_redirect = 1;
1513 wa.background_pixmap = ParentRelative;
1514 wa.event_mask = ButtonPressMask|ExposureMask;
1516 barwin = XCreateWindow(dpy, root, bx, by, bw, bh, 0, DefaultDepth(dpy, screen),
1517 CopyFromParent, DefaultVisual(dpy, screen),
1518 CWOverrideRedirect|CWBackPixmap|CWEventMask, &wa);
1519 XDefineCursor(dpy, barwin, cursor[CurNormal]);
1520 XMapRaised(dpy, barwin);
1521 strcpy(stext, "dwm-"VERSION);
1524 /* EWMH support per view */
1525 XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1526 PropModeReplace, (unsigned char *) netatom, NetLast);
1528 /* select for events */
1529 wa.event_mask = SubstructureRedirectMask|SubstructureNotifyMask
1530 |EnterWindowMask|LeaveWindowMask|StructureNotifyMask;
1531 XChangeWindowAttributes(dpy, root, CWEventMask|CWCursor, &wa);
1532 XSelectInput(dpy, root, wa.event_mask);
1540 spawn(const char *arg) {
1541 static char *shell = NULL;
1543 if(!shell && !(shell = getenv("SHELL")))
1547 /* The double-fork construct avoids zombie processes and keeps the code
1548 * clean from stupid signal handlers. */
1552 close(ConnectionNumber(dpy));
1554 execl(shell, shell, "-c", arg, (char *)NULL);
1555 fprintf(stderr, "dwm: execl '%s -c %s'", shell, arg);
1564 tag(const char *arg) {
1569 for(i = 0; i < LENGTH(tags); i++)
1570 sel->tags[i] = (NULL == arg);
1571 sel->tags[idxoftag(arg)] = True;
1576 textnw(const char *text, unsigned int len) {
1580 XmbTextExtents(dc.font.set, text, len, NULL, &r);
1583 return XTextWidth(dc.font.xfont, text, len);
1587 textw(const char *text) {
1588 return textnw(text, strlen(text)) + dc.font.height;
1594 unsigned int i, n = counttiled();
1608 for(i = 0, c = nexttiled(c->next); c; c = nexttiled(c->next), i++) {
1609 if(i + 1 == n) /* remainder */
1610 tileresize(c, x, ty, (tx + tw) - x - 2 * c->border, th - 2 * c->border);
1612 tileresize(c, x, ty, w - 2 * c->border, th - 2 * c->border);
1614 x = c->x + c->w + 2 * c->border;
1619 tilemaster(unsigned int n) {
1620 Client *c = nexttiled(clients);
1623 tileresize(c, mox, moy, mow - 2 * c->border, moh - 2 * c->border);
1625 tileresize(c, mx, my, mw - 2 * c->border, mh - 2 * c->border);
1630 tileresize(Client *c, int x, int y, int w, int h) {
1631 resize(c, x, y, w, h, RESIZEHINTS);
1632 if((RESIZEHINTS) && ((c->h < bh) || (c->h > h) || (c->w < bh) || (c->w > w)))
1633 /* client doesn't accept size constraints */
1634 resize(c, x, y, w, h, False);
1640 unsigned int i, n = counttiled();
1654 for(i = 0, c = nexttiled(c->next); c; c = nexttiled(c->next), i++) {
1655 if(i + 1 == n) /* remainder */
1656 tileresize(c, tx, y, tw - 2 * c->border, (ty + th) - y - 2 * c->border);
1658 tileresize(c, tx, y, tw - 2 * c->border, h - 2 * c->border);
1660 y = c->y + c->h + 2 * c->border;
1665 togglefloating(const char *arg) {
1668 sel->isfloating = !sel->isfloating;
1670 resize(sel, sel->x, sel->y, sel->w, sel->h, True);
1675 toggletag(const char *arg) {
1681 sel->tags[i] = !sel->tags[i];
1682 for(j = 0; j < LENGTH(tags) && !sel->tags[j]; j++);
1683 if(j == LENGTH(tags))
1684 sel->tags[i] = True; /* at least one tag must be enabled */
1689 toggleview(const char *arg) {
1693 seltags[i] = !seltags[i];
1694 for(j = 0; j < LENGTH(tags) && !seltags[j]; j++);
1695 if(j == LENGTH(tags))
1696 seltags[i] = True; /* at least one tag must be viewed */
1704 XMoveWindow(dpy, c->win, c->x, c->y);
1705 c->isbanned = False;
1709 unmanage(Client *c) {
1712 wc.border_width = c->oldborder;
1713 /* The server grab construct avoids race conditions. */
1715 XSetErrorHandler(xerrordummy);
1716 XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
1721 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1722 setclientstate(c, WithdrawnState);
1726 XSetErrorHandler(xerror);
1732 unmapnotify(XEvent *e) {
1734 XUnmapEvent *ev = &e->xunmap;
1736 if((c = getclient(ev->window)))
1741 updatebarpos(void) {
1743 if(dc.drawable != 0)
1744 XFreePixmap(dpy, dc.drawable);
1745 dc.drawable = XCreatePixmap(dpy, root, bw, bh, DefaultDepth(dpy, screen));
1746 XMoveResizeWindow(dpy, barwin, bx, by, bw, bh);
1750 updatesizehints(Client *c) {
1754 if(!XGetWMNormalHints(dpy, c->win, &size, &msize) || !size.flags)
1756 c->flags = size.flags;
1757 if(c->flags & PBaseSize) {
1758 c->basew = size.base_width;
1759 c->baseh = size.base_height;
1761 else if(c->flags & PMinSize) {
1762 c->basew = size.min_width;
1763 c->baseh = size.min_height;
1766 c->basew = c->baseh = 0;
1767 if(c->flags & PResizeInc) {
1768 c->incw = size.width_inc;
1769 c->inch = size.height_inc;
1772 c->incw = c->inch = 0;
1773 if(c->flags & PMaxSize) {
1774 c->maxw = size.max_width;
1775 c->maxh = size.max_height;
1778 c->maxw = c->maxh = 0;
1779 if(c->flags & PMinSize) {
1780 c->minw = size.min_width;
1781 c->minh = size.min_height;
1783 else if(c->flags & PBaseSize) {
1784 c->minw = size.base_width;
1785 c->minh = size.base_height;
1788 c->minw = c->minh = 0;
1789 if(c->flags & PAspect) {
1790 c->minax = size.min_aspect.x;
1791 c->maxax = size.max_aspect.x;
1792 c->minay = size.min_aspect.y;
1793 c->maxay = size.max_aspect.y;
1796 c->minax = c->maxax = c->minay = c->maxay = 0;
1797 c->isfixed = (c->maxw && c->minw && c->maxh && c->minh
1798 && c->maxw == c->minw && c->maxh == c->minh);
1802 updatetitle(Client *c) {
1803 if(!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
1804 gettextprop(c->win, wmatom[WMName], c->name, sizeof c->name);
1808 updatewmhints(Client *c) {
1811 if((wmh = XGetWMHints(dpy, c->win))) {
1813 sel->isurgent = False;
1815 c->isurgent = (wmh->flags & XUrgencyHint) ? True : False;
1822 view(const char *arg) {
1825 for(i = 0; i < LENGTH(tags); i++)
1826 tmp[i] = (NULL == arg);
1827 tmp[idxoftag(arg)] = True;
1829 if(memcmp(seltags, tmp, TAGSZ) != 0) {
1830 memcpy(prevtags, seltags, TAGSZ);
1831 memcpy(seltags, tmp, TAGSZ);
1837 viewprevtag(const char *arg) {
1839 memcpy(tmp, seltags, TAGSZ);
1840 memcpy(seltags, prevtags, TAGSZ);
1841 memcpy(prevtags, tmp, TAGSZ);
1845 /* There's no way to check accesses to destroyed windows, thus those cases are
1846 * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
1847 * default error handler, which may call exit. */
1849 xerror(Display *dpy, XErrorEvent *ee) {
1850 if(ee->error_code == BadWindow
1851 || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1852 || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1853 || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1854 || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1855 || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1856 || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1857 || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1859 fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1860 ee->request_code, ee->error_code);
1861 return xerrorxlib(dpy, ee); /* may call exit */
1865 xerrordummy(Display *dpy, XErrorEvent *ee) {
1869 /* Startup Error handler to check if another window manager
1870 * is already running. */
1872 xerrorstart(Display *dpy, XErrorEvent *ee) {
1878 zoom(const char *arg) {
1881 if(!sel || lt->isfloating || sel->isfloating)
1883 if(c == nexttiled(clients))
1884 if(!(c = nexttiled(c->next)))
1893 main(int argc, char *argv[]) {
1894 if(argc == 2 && !strcmp("-v", argv[1]))
1895 eprint("dwm-"VERSION", © 2006-2008 dwm engineers, see LICENSE for details\n");
1897 eprint("usage: dwm [-v]\n");
1899 setlocale(LC_CTYPE, "");
1900 if(!(dpy = XOpenDisplay(0)))
1901 eprint("dwm: cannot open display\n");