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 void destroynotify(XEvent *e);
120 void detach(Client *c);
121 void detachstack(Client *c);
123 void drawsquare(Bool filled, Bool empty, Bool invert, unsigned long col[ColLast]);
124 void drawtext(const char *text, unsigned long col[ColLast], Bool invert);
125 void *emallocz(unsigned int size);
126 void enternotify(XEvent *e);
127 void eprint(const char *errstr, ...);
128 void expose(XEvent *e);
129 void floating(void); /* default floating layout */
130 void focus(Client *c);
131 void focusin(XEvent *e);
132 void focusnext(const char *arg);
133 void focusprev(const char *arg);
134 Client *getclient(Window w);
135 unsigned long getcolor(const char *colstr);
136 long getstate(Window w);
137 Bool gettextprop(Window w, Atom atom, char *text, unsigned int size);
138 void grabbuttons(Client *c, Bool focused);
140 unsigned int idxoftag(const char *t);
141 void initfont(const char *fontstr);
142 Bool isoccupied(unsigned int t);
143 Bool isprotodel(Client *c);
144 Bool isurgent(unsigned int t);
145 Bool isvisible(Client *c);
146 void keypress(XEvent *e);
147 void killclient(const char *arg);
148 void manage(Window w, XWindowAttributes *wa);
149 void mappingnotify(XEvent *e);
150 void maprequest(XEvent *e);
152 void movemouse(Client *c);
153 Client *nexttiled(Client *c);
154 void propertynotify(XEvent *e);
155 void quit(const char *arg);
156 void reapply(const char *arg);
157 void resize(Client *c, int x, int y, int w, int h, Bool sizehints);
158 void resizemouse(Client *c);
162 void setclientstate(Client *c, long state);
163 void setlayout(const char *arg);
165 void spawn(const char *arg);
166 void tag(const char *arg);
167 unsigned int textnw(const char *text, unsigned int len);
168 unsigned int textw(const char *text);
170 void tilehstack(unsigned int n);
171 unsigned int tilemaster(void);
173 void tilevstack(unsigned int n);
174 void togglefloating(const char *arg);
175 void toggletag(const char *arg);
176 void toggleview(const char *arg);
177 void unban(Client *c);
178 void unmanage(Client *c);
179 void unmapnotify(XEvent *e);
180 void updatesizehints(Client *c);
181 void updatetitle(Client *c);
182 void updatewmhints(Client *c);
183 void view(const char *arg);
184 void viewprevtag(const char *arg); /* views previous selected tags */
185 int xerror(Display *dpy, XErrorEvent *ee);
186 int xerrordummy(Display *dpy, XErrorEvent *ee);
187 int xerrorstart(Display *dpy, XErrorEvent *ee);
188 void zoom(const char *arg);
191 char stext[256], buf[256];
192 int screen, sx, sy, sw, sh;
193 int (*xerrorxlib)(Display *, XErrorEvent *);
194 int bx, by, bw, bh, blw, mx, my, mw, mh, mox, moy, mow, moh, tx, ty, tw, th, wx, wy, ww, wh;
195 unsigned int numlockmask = 0;
196 void (*handler[LASTEvent]) (XEvent *) = {
197 [ButtonPress] = buttonpress,
198 [ConfigureRequest] = configurerequest,
199 [ConfigureNotify] = configurenotify,
200 [DestroyNotify] = destroynotify,
201 [EnterNotify] = enternotify,
204 [KeyPress] = keypress,
205 [MappingNotify] = mappingnotify,
206 [MapRequest] = maprequest,
207 [PropertyNotify] = propertynotify,
208 [UnmapNotify] = unmapnotify
210 Atom wmatom[WMLast], netatom[NetLast];
211 Bool otherwm, readin;
215 Client *clients = NULL;
217 Client *stack = NULL;
218 Cursor cursor[CurLast];
224 /* configuration, allows nested code to access above variables */
226 #define TAGSZ (LENGTH(tags) * sizeof(Bool))
227 static Bool tmp[LENGTH(tags)];
229 /* function implementations */
232 applyrules(Client *c) {
234 Bool matched = False;
236 XClassHint ch = { 0 };
239 XGetClassHint(dpy, c->win, &ch);
240 for(i = 0; i < LENGTH(rules); i++) {
242 if(strstr(c->name, r->prop)
243 || (ch.res_class && strstr(ch.res_class, r->prop))
244 || (ch.res_name && strstr(ch.res_name, r->prop)))
246 c->isfloating = r->isfloating;
248 c->tags[idxoftag(r->tag)] = True;
258 memcpy(c->tags, seltags, TAGSZ);
265 for(c = clients; c; c = c->next)
285 attachstack(Client *c) {
294 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
299 buttonpress(XEvent *e) {
302 XButtonPressedEvent *ev = &e->xbutton;
304 if(ev->window == barwin) {
306 for(i = 0; i < LENGTH(tags); i++) {
309 if(ev->button == Button1) {
310 if(ev->state & MODKEY)
315 else if(ev->button == Button3) {
316 if(ev->state & MODKEY)
325 else if((c = getclient(ev->window))) {
327 if(CLEANMASK(ev->state) != MODKEY)
329 if(ev->button == Button1) {
333 else if(ev->button == Button2) {
334 if((floating != lt->arrange) && c->isfloating)
335 togglefloating(NULL);
339 else if(ev->button == Button3 && !c->isfixed) {
349 XSetErrorHandler(xerrorstart);
351 /* this causes an error if some other window manager is running */
352 XSelectInput(dpy, DefaultRootWindow(dpy), SubstructureRedirectMask);
355 eprint("dwm: another window manager is already running\n");
357 XSetErrorHandler(NULL);
358 xerrorxlib = XSetErrorHandler(xerror);
370 XFreeFontSet(dpy, dc.font.set);
372 XFreeFont(dpy, dc.font.xfont);
373 XUngrabKey(dpy, AnyKey, AnyModifier, root);
374 XFreePixmap(dpy, dc.drawable);
376 XFreeCursor(dpy, cursor[CurNormal]);
377 XFreeCursor(dpy, cursor[CurResize]);
378 XFreeCursor(dpy, cursor[CurMove]);
379 XDestroyWindow(dpy, barwin);
381 XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime);
385 configure(Client *c) {
388 ce.type = ConfigureNotify;
396 ce.border_width = c->border;
398 ce.override_redirect = False;
399 XSendEvent(dpy, c->win, False, StructureNotifyMask, (XEvent *)&ce);
403 configurenotify(XEvent *e) {
404 XConfigureEvent *ev = &e->xconfigure;
406 if(ev->window == root && (ev->width != sw || ev->height != sh)) {
409 XFreePixmap(dpy, dc.drawable);
410 dc.drawable = XCreatePixmap(dpy, root, bw, bh, DefaultDepth(dpy, screen));
411 XMoveResizeWindow(dpy, barwin, bx, by, bw, bh);
417 configurerequest(XEvent *e) {
419 XConfigureRequestEvent *ev = &e->xconfigurerequest;
422 if((c = getclient(ev->window))) {
423 if(ev->value_mask & CWBorderWidth)
424 c->border = ev->border_width;
425 if(c->isfixed || c->isfloating || lt->isfloating) {
426 if(ev->value_mask & CWX)
428 if(ev->value_mask & CWY)
430 if(ev->value_mask & CWWidth)
432 if(ev->value_mask & CWHeight)
434 if((c->x - sx + c->w) > sw && c->isfloating)
435 c->x = sx + (sw / 2 - c->w / 2); /* center in x direction */
436 if((c->y - sy + c->h) > sh && c->isfloating)
437 c->y = sy + (sh / 2 - c->h / 2); /* center in y direction */
438 if((ev->value_mask & (CWX|CWY))
439 && !(ev->value_mask & (CWWidth|CWHeight)))
442 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h);
450 wc.width = ev->width;
451 wc.height = ev->height;
452 wc.border_width = ev->border_width;
453 wc.sibling = ev->above;
454 wc.stack_mode = ev->detail;
455 XConfigureWindow(dpy, ev->window, ev->value_mask, &wc);
461 destroynotify(XEvent *e) {
463 XDestroyWindowEvent *ev = &e->xdestroywindow;
465 if((c = getclient(ev->window)))
472 c->prev->next = c->next;
474 c->next->prev = c->prev;
477 c->next = c->prev = NULL;
481 detachstack(Client *c) {
484 for(tc=&stack; *tc && *tc != c; tc=&(*tc)->snext);
494 for(c = stack; c && !isvisible(c); c = c->snext);
495 for(i = 0; i < LENGTH(tags); i++) {
496 dc.w = textw(tags[i]);
498 drawtext(tags[i], dc.sel, isurgent(i));
499 drawsquare(c && c->tags[i], isoccupied(i), isurgent(i), dc.sel);
502 drawtext(tags[i], dc.norm, isurgent(i));
503 drawsquare(c && c->tags[i], isoccupied(i), isurgent(i), dc.norm);
508 drawtext(lt->symbol, dc.norm, False);
516 drawtext(stext, dc.norm, False);
517 if((dc.w = dc.x - x) > bh) {
520 drawtext(c->name, dc.sel, False);
521 drawsquare(False, c->isfloating, False, dc.sel);
524 drawtext(NULL, dc.norm, False);
526 XCopyArea(dpy, dc.drawable, barwin, dc.gc, 0, 0, bw, bh, 0, 0);
531 drawsquare(Bool filled, Bool empty, Bool invert, unsigned long col[ColLast]) {
534 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
536 gcv.foreground = col[invert ? ColBG : ColFG];
537 XChangeGC(dpy, dc.gc, GCForeground, &gcv);
538 x = (dc.font.ascent + dc.font.descent + 2) / 4;
542 r.width = r.height = x + 1;
543 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
546 r.width = r.height = x;
547 XDrawRectangles(dpy, dc.drawable, dc.gc, &r, 1);
552 drawtext(const char *text, unsigned long col[ColLast], Bool invert) {
554 unsigned int len, olen;
555 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
557 XSetForeground(dpy, dc.gc, col[invert ? ColFG : ColBG]);
558 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
562 olen = len = strlen(text);
563 if(len >= sizeof buf)
564 len = sizeof buf - 1;
565 memcpy(buf, text, len);
567 h = dc.font.ascent + dc.font.descent;
568 y = dc.y + (dc.h / 2) - (h / 2) + dc.font.ascent;
570 /* shorten text if necessary */
571 while(len && (w = textnw(buf, len)) > dc.w - h)
582 return; /* too long */
583 XSetForeground(dpy, dc.gc, col[invert ? ColBG : ColFG]);
585 XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
587 XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
591 emallocz(unsigned int size) {
592 void *res = calloc(1, size);
595 eprint("fatal: could not malloc() %u bytes\n", size);
600 enternotify(XEvent *e) {
602 XCrossingEvent *ev = &e->xcrossing;
604 if((ev->mode != NotifyNormal || ev->detail == NotifyInferior) && ev->window != root)
606 if((c = getclient(ev->window)))
613 eprint(const char *errstr, ...) {
616 va_start(ap, errstr);
617 vfprintf(stderr, errstr, ap);
624 XExposeEvent *ev = &e->xexpose;
626 if(ev->count == 0 && (ev->window == barwin))
631 floating(void) { /* default floating layout */
634 for(c = clients; c; c = c->next)
636 resize(c, c->x, c->y, c->w, c->h, True);
641 if(!c || (c && !isvisible(c)))
642 for(c = stack; c && !isvisible(c); c = c->snext);
643 if(sel && sel != c) {
644 grabbuttons(sel, False);
645 XSetWindowBorder(dpy, sel->win, dc.norm[ColBorder]);
650 grabbuttons(c, True);
654 XSetWindowBorder(dpy, c->win, dc.sel[ColBorder]);
655 XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
658 XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
663 focusin(XEvent *e) { /* there are some broken focus acquiring clients */
664 XFocusChangeEvent *ev = &e->xfocus;
666 if(sel && ev->window != sel->win)
667 XSetInputFocus(dpy, sel->win, RevertToPointerRoot, CurrentTime);
671 focusnext(const char *arg) {
676 for(c = sel->next; c && !isvisible(c); c = c->next);
678 for(c = clients; c && !isvisible(c); c = c->next);
686 focusprev(const char *arg) {
691 for(c = sel->prev; c && !isvisible(c); c = c->prev);
693 for(c = clients; c && c->next; c = c->next);
694 for(; c && !isvisible(c); c = c->prev);
703 getclient(Window w) {
706 for(c = clients; c && c->win != w; c = c->next);
711 getcolor(const char *colstr) {
712 Colormap cmap = DefaultColormap(dpy, screen);
715 if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
716 eprint("error, cannot allocate color '%s'\n", colstr);
724 unsigned char *p = NULL;
725 unsigned long n, extra;
728 status = XGetWindowProperty(dpy, w, wmatom[WMState], 0L, 2L, False, wmatom[WMState],
729 &real, &format, &n, &extra, (unsigned char **)&p);
730 if(status != Success)
739 gettextprop(Window w, Atom atom, char *text, unsigned int size) {
744 if(!text || size == 0)
747 XGetTextProperty(dpy, w, &name, atom);
750 if(name.encoding == XA_STRING)
751 strncpy(text, (char *)name.value, size - 1);
753 if(XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success
755 strncpy(text, *list, size - 1);
756 XFreeStringList(list);
759 text[size - 1] = '\0';
765 grabbuttons(Client *c, Bool focused) {
766 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
769 XGrabButton(dpy, Button1, MODKEY, c->win, False, BUTTONMASK,
770 GrabModeAsync, GrabModeSync, None, None);
771 XGrabButton(dpy, Button1, MODKEY|LockMask, c->win, False, BUTTONMASK,
772 GrabModeAsync, GrabModeSync, None, None);
773 XGrabButton(dpy, Button1, MODKEY|numlockmask, c->win, False, BUTTONMASK,
774 GrabModeAsync, GrabModeSync, None, None);
775 XGrabButton(dpy, Button1, MODKEY|numlockmask|LockMask, c->win, False, BUTTONMASK,
776 GrabModeAsync, GrabModeSync, None, None);
778 XGrabButton(dpy, Button2, MODKEY, c->win, False, BUTTONMASK,
779 GrabModeAsync, GrabModeSync, None, None);
780 XGrabButton(dpy, Button2, MODKEY|LockMask, c->win, False, BUTTONMASK,
781 GrabModeAsync, GrabModeSync, None, None);
782 XGrabButton(dpy, Button2, MODKEY|numlockmask, c->win, False, BUTTONMASK,
783 GrabModeAsync, GrabModeSync, None, None);
784 XGrabButton(dpy, Button2, MODKEY|numlockmask|LockMask, c->win, False, BUTTONMASK,
785 GrabModeAsync, GrabModeSync, None, None);
787 XGrabButton(dpy, Button3, MODKEY, c->win, False, BUTTONMASK,
788 GrabModeAsync, GrabModeSync, None, None);
789 XGrabButton(dpy, Button3, MODKEY|LockMask, c->win, False, BUTTONMASK,
790 GrabModeAsync, GrabModeSync, None, None);
791 XGrabButton(dpy, Button3, MODKEY|numlockmask, c->win, False, BUTTONMASK,
792 GrabModeAsync, GrabModeSync, None, None);
793 XGrabButton(dpy, Button3, MODKEY|numlockmask|LockMask, c->win, False, BUTTONMASK,
794 GrabModeAsync, GrabModeSync, None, None);
797 XGrabButton(dpy, AnyButton, AnyModifier, c->win, False, BUTTONMASK,
798 GrabModeAsync, GrabModeSync, None, None);
805 XModifierKeymap *modmap;
807 /* init modifier map */
808 modmap = XGetModifierMapping(dpy);
809 for(i = 0; i < 8; i++)
810 for(j = 0; j < modmap->max_keypermod; j++) {
811 if(modmap->modifiermap[i * modmap->max_keypermod + j] == XKeysymToKeycode(dpy, XK_Num_Lock))
812 numlockmask = (1 << i);
814 XFreeModifiermap(modmap);
816 XUngrabKey(dpy, AnyKey, AnyModifier, root);
817 for(i = 0; i < LENGTH(keys); i++) {
818 code = XKeysymToKeycode(dpy, keys[i].keysym);
819 XGrabKey(dpy, code, keys[i].mod, root, True,
820 GrabModeAsync, GrabModeAsync);
821 XGrabKey(dpy, code, keys[i].mod|LockMask, root, True,
822 GrabModeAsync, GrabModeAsync);
823 XGrabKey(dpy, code, keys[i].mod|numlockmask, root, True,
824 GrabModeAsync, GrabModeAsync);
825 XGrabKey(dpy, code, keys[i].mod|numlockmask|LockMask, root, True,
826 GrabModeAsync, GrabModeAsync);
831 idxoftag(const char *t) {
834 for(i = 0; (i < LENGTH(tags)) && (tags[i] != t); i++);
835 return (i < LENGTH(tags)) ? i : 0;
839 initfont(const char *fontstr) {
840 char *def, **missing;
845 XFreeFontSet(dpy, dc.font.set);
846 dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
849 fprintf(stderr, "dwm: missing fontset: %s\n", missing[n]);
850 XFreeStringList(missing);
853 XFontSetExtents *font_extents;
854 XFontStruct **xfonts;
856 dc.font.ascent = dc.font.descent = 0;
857 font_extents = XExtentsOfFontSet(dc.font.set);
858 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
859 for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
860 if(dc.font.ascent < (*xfonts)->ascent)
861 dc.font.ascent = (*xfonts)->ascent;
862 if(dc.font.descent < (*xfonts)->descent)
863 dc.font.descent = (*xfonts)->descent;
869 XFreeFont(dpy, dc.font.xfont);
870 dc.font.xfont = NULL;
871 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr))
872 && !(dc.font.xfont = XLoadQueryFont(dpy, "fixed")))
873 eprint("error, cannot load font: '%s'\n", fontstr);
874 dc.font.ascent = dc.font.xfont->ascent;
875 dc.font.descent = dc.font.xfont->descent;
877 dc.font.height = dc.font.ascent + dc.font.descent;
881 isoccupied(unsigned int t) {
884 for(c = clients; c; c = c->next)
891 isprotodel(Client *c) {
896 if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
897 for(i = 0; !ret && i < n; i++)
898 if(protocols[i] == wmatom[WMDelete])
906 isurgent(unsigned int t) {
909 for(c = clients; c; c = c->next)
910 if(c->isurgent && c->tags[t])
916 isvisible(Client *c) {
919 for(i = 0; i < LENGTH(tags); i++)
920 if(c->tags[i] && seltags[i])
926 keypress(XEvent *e) {
932 keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
933 for(i = 0; i < LENGTH(keys); i++)
934 if(keysym == keys[i].keysym
935 && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state))
938 keys[i].func(keys[i].arg);
943 killclient(const char *arg) {
948 if(isprotodel(sel)) {
949 ev.type = ClientMessage;
950 ev.xclient.window = sel->win;
951 ev.xclient.message_type = wmatom[WMProtocols];
952 ev.xclient.format = 32;
953 ev.xclient.data.l[0] = wmatom[WMDelete];
954 ev.xclient.data.l[1] = CurrentTime;
955 XSendEvent(dpy, sel->win, False, NoEventMask, &ev);
958 XKillClient(dpy, sel->win);
962 manage(Window w, XWindowAttributes *wa) {
963 Client *c, *t = NULL;
968 c = emallocz(sizeof(Client));
969 c->tags = emallocz(TAGSZ);
977 c->oldborder = wa->border_width;
978 if(c->w == sw && c->h == sh) {
981 c->border = wa->border_width;
984 if(c->x + c->w + 2 * c->border > wx + ww)
985 c->x = wx + ww - c->w - 2 * c->border;
986 if(c->y + c->h + 2 * c->border > wy + wh)
987 c->y = wy + wh - c->h - 2 * c->border;
992 c->border = BORDERPX;
995 wc.border_width = c->border;
996 XConfigureWindow(dpy, w, CWBorderWidth, &wc);
997 XSetWindowBorder(dpy, w, dc.norm[ColBorder]);
998 configure(c); /* propagates border_width, if size doesn't change */
1000 XSelectInput(dpy, w, EnterWindowMask|FocusChangeMask|PropertyChangeMask|StructureNotifyMask);
1001 grabbuttons(c, False);
1003 if((rettrans = XGetTransientForHint(dpy, w, &trans) == Success))
1004 for(t = clients; t && t->win != trans; t = t->next);
1006 memcpy(c->tags, t->tags, TAGSZ);
1010 c->isfloating = (rettrans == Success) || c->isfixed;
1013 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h); /* some windows require this */
1015 XMapWindow(dpy, c->win);
1016 setclientstate(c, NormalState);
1021 mappingnotify(XEvent *e) {
1022 XMappingEvent *ev = &e->xmapping;
1024 XRefreshKeyboardMapping(ev);
1025 if(ev->request == MappingKeyboard)
1030 maprequest(XEvent *e) {
1031 static XWindowAttributes wa;
1032 XMapRequestEvent *ev = &e->xmaprequest;
1034 if(!XGetWindowAttributes(dpy, ev->window, &wa))
1036 if(wa.override_redirect)
1038 if(!getclient(ev->window))
1039 manage(ev->window, &wa);
1046 for(c = clients; c; c = c->next)
1048 resize(c, mox, moy, mow, moh, RESIZEHINTS);
1052 movemouse(Client *c) {
1053 int x1, y1, ocx, ocy, di, nx, ny;
1060 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1061 None, cursor[CurMove], CurrentTime) != GrabSuccess)
1063 XQueryPointer(dpy, root, &dummy, &dummy, &x1, &y1, &di, &di, &dui);
1065 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
1068 XUngrabPointer(dpy, CurrentTime);
1070 case ConfigureRequest:
1073 handler[ev.type](&ev);
1077 nx = ocx + (ev.xmotion.x - x1);
1078 ny = ocy + (ev.xmotion.y - y1);
1079 if(abs(wx - nx) < SNAP)
1081 else if(abs((wx + ww) - (nx + c->w + 2 * c->border)) < SNAP)
1082 nx = wx + ww - c->w - 2 * c->border;
1083 if(abs(wy - ny) < SNAP)
1085 else if(abs((wy + wh) - (ny + c->h + 2 * c->border)) < SNAP)
1086 ny = wy + wh - c->h - 2 * c->border;
1087 if(!c->isfloating && !lt->isfloating && (abs(nx - c->x) > SNAP || abs(ny - c->y) > SNAP))
1088 togglefloating(NULL);
1089 if((lt->isfloating) || c->isfloating)
1090 resize(c, nx, ny, c->w, c->h, False);
1097 nexttiled(Client *c) {
1098 for(; c && (c->isfloating || !isvisible(c)); c = c->next);
1103 propertynotify(XEvent *e) {
1106 XPropertyEvent *ev = &e->xproperty;
1108 if(ev->state == PropertyDelete)
1109 return; /* ignore */
1110 if((c = getclient(ev->window))) {
1113 case XA_WM_TRANSIENT_FOR:
1114 XGetTransientForHint(dpy, c->win, &trans);
1115 if(!c->isfloating && (c->isfloating = (getclient(trans) != NULL)))
1118 case XA_WM_NORMAL_HINTS:
1126 if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
1135 quit(const char *arg) {
1136 readin = running = False;
1140 reapply(const char *arg) {
1141 static Bool zerotags[LENGTH(tags)] = { 0 };
1144 for(c = clients; c; c = c->next) {
1145 memcpy(c->tags, zerotags, sizeof zerotags);
1152 resize(Client *c, int x, int y, int w, int h, Bool sizehints) {
1156 /* set minimum possible */
1162 /* temporarily remove base dimensions */
1166 /* adjust for aspect limits */
1167 if (c->minay > 0 && c->maxay > 0 && c->minax > 0 && c->maxax > 0) {
1168 if (w * c->maxay > h * c->maxax)
1169 w = h * c->maxax / c->maxay;
1170 else if (w * c->minay < h * c->minax)
1171 h = w * c->minay / c->minax;
1174 /* adjust for increment value */
1180 /* restore base dimensions */
1184 if(c->minw > 0 && w < c->minw)
1186 if(c->minh > 0 && h < c->minh)
1188 if(c->maxw > 0 && w > c->maxw)
1190 if(c->maxh > 0 && h > c->maxh)
1193 if(w <= 0 || h <= 0)
1196 x = sw - w - 2 * c->border;
1198 y = sh - h - 2 * c->border;
1199 if(x + w + 2 * c->border < sx)
1201 if(y + h + 2 * c->border < sy)
1203 if(c->x != x || c->y != y || c->w != w || c->h != h) {
1206 c->w = wc.width = w;
1207 c->h = wc.height = h;
1208 wc.border_width = c->border;
1209 XConfigureWindow(dpy, c->win,
1210 CWX|CWY|CWWidth|CWHeight|CWBorderWidth, &wc);
1217 resizemouse(Client *c) {
1224 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1225 None, cursor[CurResize], CurrentTime) != GrabSuccess)
1227 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->border - 1, c->h + c->border - 1);
1229 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask , &ev);
1232 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0,
1233 c->w + c->border - 1, c->h + c->border - 1);
1234 XUngrabPointer(dpy, CurrentTime);
1235 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1237 case ConfigureRequest:
1240 handler[ev.type](&ev);
1244 if((nw = ev.xmotion.x - ocx - 2 * c->border + 1) <= 0)
1246 if((nh = ev.xmotion.y - ocy - 2 * c->border + 1) <= 0)
1248 if(!c->isfloating && !lt->isfloating && (abs(nw - c->w) > SNAP || abs(nh - c->h) > SNAP))
1249 togglefloating(NULL);
1250 if((lt->isfloating) || c->isfloating)
1251 resize(c, c->x, c->y, nw, nh, True);
1266 if(sel->isfloating || lt->isfloating)
1267 XRaiseWindow(dpy, sel->win);
1268 if(!lt->isfloating) {
1269 wc.stack_mode = Below;
1270 wc.sibling = barwin;
1271 if(!sel->isfloating) {
1272 XConfigureWindow(dpy, sel->win, CWSibling|CWStackMode, &wc);
1273 wc.sibling = sel->win;
1275 for(c = nexttiled(clients); c; c = nexttiled(c->next)) {
1278 XConfigureWindow(dpy, c->win, CWSibling|CWStackMode, &wc);
1279 wc.sibling = c->win;
1283 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1289 char sbuf[sizeof stext];
1292 unsigned int len, offset;
1295 /* main event loop, also reads status text from stdin */
1297 xfd = ConnectionNumber(dpy);
1300 len = sizeof stext - 1;
1301 sbuf[len] = stext[len] = '\0'; /* 0-terminator is never touched */
1305 FD_SET(STDIN_FILENO, &rd);
1307 if(select(xfd + 1, &rd, NULL, NULL, NULL) == -1) {
1310 eprint("select failed\n");
1312 if(FD_ISSET(STDIN_FILENO, &rd)) {
1313 switch((r = read(STDIN_FILENO, sbuf + offset, len - offset))) {
1315 strncpy(stext, strerror(errno), len);
1319 strncpy(stext, "EOF", 4);
1323 for(p = sbuf + offset; r > 0; p++, r--, offset++)
1324 if(*p == '\n' || *p == '\0') {
1326 strncpy(stext, sbuf, len);
1327 p += r - 1; /* p is sbuf + offset + r - 1 */
1328 for(r = 0; *(p - r) && *(p - r) != '\n'; r++);
1331 memmove(sbuf, p - r + 1, r);
1338 while(XPending(dpy)) {
1339 XNextEvent(dpy, &ev);
1340 if(handler[ev.type])
1341 (handler[ev.type])(&ev); /* call handler */
1348 unsigned int i, num;
1349 Window *wins, d1, d2;
1350 XWindowAttributes wa;
1353 if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1354 for(i = 0; i < num; i++) {
1355 if(!XGetWindowAttributes(dpy, wins[i], &wa)
1356 || wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1358 if(wa.map_state == IsViewable || getstate(wins[i]) == IconicState)
1359 manage(wins[i], &wa);
1361 for(i = 0; i < num; i++) { /* now the transients */
1362 if(!XGetWindowAttributes(dpy, wins[i], &wa))
1364 if(XGetTransientForHint(dpy, wins[i], &d1)
1365 && (wa.map_state == IsViewable || getstate(wins[i]) == IconicState))
1366 manage(wins[i], &wa);
1374 setclientstate(Client *c, long state) {
1375 long data[] = {state, None};
1377 XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1378 PropModeReplace, (unsigned char *)data, 2);
1382 setlayout(const char *arg) {
1383 static Layout *revert = 0;
1388 for(i = 0; i < LENGTH(layouts); i++)
1389 if(!strcmp(arg, layouts[i].symbol))
1391 if(i == LENGTH(layouts))
1393 if(revert && &layouts[i] == lt)
1408 XSetWindowAttributes wa;
1411 screen = DefaultScreen(dpy);
1412 root = RootWindow(dpy, screen);
1415 sw = DisplayWidth(dpy, screen);
1416 sh = DisplayHeight(dpy, screen);
1419 wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1420 wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1421 wmatom[WMName] = XInternAtom(dpy, "WM_NAME", False);
1422 wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1423 netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1424 netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1427 wa.cursor = cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1428 cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1429 cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1431 /* init appearance */
1432 dc.norm[ColBorder] = getcolor(NORMBORDERCOLOR);
1433 dc.norm[ColBG] = getcolor(NORMBGCOLOR);
1434 dc.norm[ColFG] = getcolor(NORMFGCOLOR);
1435 dc.sel[ColBorder] = getcolor(SELBORDERCOLOR);
1436 dc.sel[ColBG] = getcolor(SELBGCOLOR);
1437 dc.sel[ColFG] = getcolor(SELFGCOLOR);
1439 dc.h = bh = dc.font.height + 2;
1440 dc.drawable = XCreatePixmap(dpy, root, DisplayWidth(dpy, screen), bh, DefaultDepth(dpy, screen));
1441 dc.gc = XCreateGC(dpy, root, 0, 0);
1442 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
1444 XSetFont(dpy, dc.gc, dc.font.xfont->fid);
1447 seltags = emallocz(TAGSZ);
1448 prevtags = emallocz(TAGSZ);
1449 seltags[0] = prevtags[0] = True;
1484 for(blw = i = 0; i < LENGTH(layouts); i++) {
1485 i = textw(layouts[i].symbol);
1490 wa.override_redirect = 1;
1491 wa.background_pixmap = ParentRelative;
1492 wa.event_mask = ButtonPressMask|ExposureMask;
1496 barwin = XCreateWindow(dpy, root, bx, by, bw, bh, 0, DefaultDepth(dpy, screen),
1497 CopyFromParent, DefaultVisual(dpy, screen),
1498 CWOverrideRedirect|CWBackPixmap|CWEventMask, &wa);
1499 XDefineCursor(dpy, barwin, cursor[CurNormal]);
1500 XMapRaised(dpy, barwin);
1501 strcpy(stext, "dwm-"VERSION);
1504 /* EWMH support per view */
1505 XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1506 PropModeReplace, (unsigned char *) netatom, NetLast);
1508 /* select for events */
1509 wa.event_mask = SubstructureRedirectMask|SubstructureNotifyMask
1510 |EnterWindowMask|LeaveWindowMask|StructureNotifyMask;
1511 XChangeWindowAttributes(dpy, root, CWEventMask|CWCursor, &wa);
1512 XSelectInput(dpy, root, wa.event_mask);
1520 spawn(const char *arg) {
1521 static char *shell = NULL;
1523 if(!shell && !(shell = getenv("SHELL")))
1527 /* The double-fork construct avoids zombie processes and keeps the code
1528 * clean from stupid signal handlers. */
1532 close(ConnectionNumber(dpy));
1534 execl(shell, shell, "-c", arg, (char *)NULL);
1535 fprintf(stderr, "dwm: execl '%s -c %s'", shell, arg);
1544 tag(const char *arg) {
1549 for(i = 0; i < LENGTH(tags); i++)
1550 sel->tags[i] = (NULL == arg);
1551 sel->tags[idxoftag(arg)] = True;
1556 textnw(const char *text, unsigned int len) {
1560 XmbTextExtents(dc.font.set, text, len, NULL, &r);
1563 return XTextWidth(dc.font.xfont, text, len);
1567 textw(const char *text) {
1568 return textnw(text, strlen(text)) + dc.font.height;
1572 tileresize(Client *c, int x, int y, int w, int h) {
1573 resize(c, x, y, w, h, RESIZEHINTS);
1574 if((RESIZEHINTS) && ((c->h < bh) || (c->h > h) || (c->w < bh) || (c->w > w)))
1575 /* client doesn't accept size constraints */
1576 resize(c, x, y, w, h, False);
1581 tilehstack(tilemaster());
1585 tilehstack(unsigned int n) {
1597 for(i = 0, c = nexttiled(clients); c; c = nexttiled(c->next), i++)
1599 if(i > 1 && i == n) /* remainder */
1600 tileresize(c, x, ty, (tx + tw) - x - 2 * c->border,
1601 th - 2 * c->border);
1603 tileresize(c, x, ty, w - 2 * c->border,
1604 th - 2 * c->border);
1606 x = c->x + c->w + 2 * c->border;
1615 for(n = 0, mc = c = nexttiled(clients); c; c = nexttiled(c->next))
1620 tileresize(mc, mox, moy, mow - 2 * mc->border, moh - 2 * mc->border);
1622 tileresize(mc, mx, my, mw - 2 * mc->border, mh - 2 * mc->border);
1628 tilevstack(tilemaster());
1632 tilevstack(unsigned int n) {
1644 for(i = 0, c = nexttiled(clients); c; c = nexttiled(c->next), i++)
1646 if(i > 1 && i == n) /* remainder */
1647 tileresize(c, tx, y, tw - 2 * c->border,
1648 (ty + th) - y - 2 * c->border);
1650 tileresize(c, tx, y, tw - 2 * c->border,
1653 y = c->y + c->h + 2 * c->border;
1658 togglefloating(const char *arg) {
1661 sel->isfloating = !sel->isfloating;
1663 resize(sel, sel->x, sel->y, sel->w, sel->h, True);
1668 toggletag(const char *arg) {
1674 sel->tags[i] = !sel->tags[i];
1675 for(j = 0; j < LENGTH(tags) && !sel->tags[j]; j++);
1676 if(j == LENGTH(tags))
1677 sel->tags[i] = True; /* at least one tag must be enabled */
1682 toggleview(const char *arg) {
1686 seltags[i] = !seltags[i];
1687 for(j = 0; j < LENGTH(tags) && !seltags[j]; j++);
1688 if(j == LENGTH(tags))
1689 seltags[i] = True; /* at least one tag must be viewed */
1697 XMoveWindow(dpy, c->win, c->x, c->y);
1698 c->isbanned = False;
1702 unmanage(Client *c) {
1705 wc.border_width = c->oldborder;
1706 /* The server grab construct avoids race conditions. */
1708 XSetErrorHandler(xerrordummy);
1709 XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
1714 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1715 setclientstate(c, WithdrawnState);
1719 XSetErrorHandler(xerror);
1725 unmapnotify(XEvent *e) {
1727 XUnmapEvent *ev = &e->xunmap;
1729 if((c = getclient(ev->window)))
1734 updatesizehints(Client *c) {
1738 if(!XGetWMNormalHints(dpy, c->win, &size, &msize) || !size.flags)
1740 c->flags = size.flags;
1741 if(c->flags & PBaseSize) {
1742 c->basew = size.base_width;
1743 c->baseh = size.base_height;
1745 else if(c->flags & PMinSize) {
1746 c->basew = size.min_width;
1747 c->baseh = size.min_height;
1750 c->basew = c->baseh = 0;
1751 if(c->flags & PResizeInc) {
1752 c->incw = size.width_inc;
1753 c->inch = size.height_inc;
1756 c->incw = c->inch = 0;
1757 if(c->flags & PMaxSize) {
1758 c->maxw = size.max_width;
1759 c->maxh = size.max_height;
1762 c->maxw = c->maxh = 0;
1763 if(c->flags & PMinSize) {
1764 c->minw = size.min_width;
1765 c->minh = size.min_height;
1767 else if(c->flags & PBaseSize) {
1768 c->minw = size.base_width;
1769 c->minh = size.base_height;
1772 c->minw = c->minh = 0;
1773 if(c->flags & PAspect) {
1774 c->minax = size.min_aspect.x;
1775 c->maxax = size.max_aspect.x;
1776 c->minay = size.min_aspect.y;
1777 c->maxay = size.max_aspect.y;
1780 c->minax = c->maxax = c->minay = c->maxay = 0;
1781 c->isfixed = (c->maxw && c->minw && c->maxh && c->minh
1782 && c->maxw == c->minw && c->maxh == c->minh);
1786 updatetitle(Client *c) {
1787 if(!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
1788 gettextprop(c->win, wmatom[WMName], c->name, sizeof c->name);
1792 updatewmhints(Client *c) {
1795 if((wmh = XGetWMHints(dpy, c->win))) {
1797 sel->isurgent = False;
1799 c->isurgent = (wmh->flags & XUrgencyHint) ? True : False;
1806 view(const char *arg) {
1809 for(i = 0; i < LENGTH(tags); i++)
1810 tmp[i] = (NULL == arg);
1811 tmp[idxoftag(arg)] = True;
1813 if(memcmp(seltags, tmp, TAGSZ) != 0) {
1814 memcpy(prevtags, seltags, TAGSZ);
1815 memcpy(seltags, tmp, TAGSZ);
1821 viewprevtag(const char *arg) {
1823 memcpy(tmp, seltags, TAGSZ);
1824 memcpy(seltags, prevtags, TAGSZ);
1825 memcpy(prevtags, tmp, TAGSZ);
1829 /* There's no way to check accesses to destroyed windows, thus those cases are
1830 * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
1831 * default error handler, which may call exit. */
1833 xerror(Display *dpy, XErrorEvent *ee) {
1834 if(ee->error_code == BadWindow
1835 || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1836 || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1837 || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1838 || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1839 || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1840 || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1841 || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1843 fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1844 ee->request_code, ee->error_code);
1845 return xerrorxlib(dpy, ee); /* may call exit */
1849 xerrordummy(Display *dpy, XErrorEvent *ee) {
1853 /* Startup Error handler to check if another window manager
1854 * is already running. */
1856 xerrorstart(Display *dpy, XErrorEvent *ee) {
1862 zoom(const char *arg) {
1865 if(!sel || lt->isfloating || sel->isfloating)
1867 if(c == nexttiled(clients))
1868 if(!(c = nexttiled(c->next)))
1877 main(int argc, char *argv[]) {
1878 if(argc == 2 && !strcmp("-v", argv[1]))
1879 eprint("dwm-"VERSION", © 2006-2008 dwm engineers, see LICENSE for details\n");
1881 eprint("usage: dwm [-v]\n");
1883 setlocale(LC_CTYPE, "");
1884 if(!(dpy = XOpenDisplay(0)))
1885 eprint("dwm: cannot open display\n");