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 setdefaultgeoms(void);
164 void setlayout(const char *arg);
166 void spawn(const char *arg);
167 void tag(const char *arg);
168 unsigned int textnw(const char *text, unsigned int len);
169 unsigned int textw(const char *text);
171 void tilehstack(unsigned int n);
172 unsigned int tilemaster(void);
174 void tilevstack(unsigned int n);
175 void togglefloating(const char *arg);
176 void toggletag(const char *arg);
177 void toggleview(const char *arg);
178 void unban(Client *c);
179 void unmanage(Client *c);
180 void unmapnotify(XEvent *e);
181 void updatebarpos(void);
182 void updatesizehints(Client *c);
183 void updatetitle(Client *c);
184 void updatewmhints(Client *c);
185 void view(const char *arg);
186 void viewprevtag(const char *arg); /* views previous selected tags */
187 int xerror(Display *dpy, XErrorEvent *ee);
188 int xerrordummy(Display *dpy, XErrorEvent *ee);
189 int xerrorstart(Display *dpy, XErrorEvent *ee);
190 void zoom(const char *arg);
193 char stext[256], buf[256];
194 int screen, sx, sy, sw, sh;
195 int (*xerrorxlib)(Display *, XErrorEvent *);
196 int bx, by, bw, bh, blw, mx, my, mw, mh, mox, moy, mow, moh, tx, ty, tw, th, wx, wy, ww, wh;
197 unsigned int numlockmask = 0;
198 void (*handler[LASTEvent]) (XEvent *) = {
199 [ButtonPress] = buttonpress,
200 [ConfigureRequest] = configurerequest,
201 [ConfigureNotify] = configurenotify,
202 [DestroyNotify] = destroynotify,
203 [EnterNotify] = enternotify,
206 [KeyPress] = keypress,
207 [MappingNotify] = mappingnotify,
208 [MapRequest] = maprequest,
209 [PropertyNotify] = propertynotify,
210 [UnmapNotify] = unmapnotify
212 Atom wmatom[WMLast], netatom[NetLast];
213 Bool otherwm, readin;
217 Client *clients = NULL;
219 Client *stack = NULL;
220 Cursor cursor[CurLast];
225 void (*setgeoms)(void) = setdefaultgeoms;
227 /* configuration, allows nested code to access above variables */
229 #define TAGSZ (LENGTH(tags) * sizeof(Bool))
230 static Bool tmp[LENGTH(tags)];
232 /* function implementations */
235 applyrules(Client *c) {
237 Bool matched = False;
239 XClassHint ch = { 0 };
242 XGetClassHint(dpy, c->win, &ch);
243 for(i = 0; i < LENGTH(rules); i++) {
245 if(strstr(c->name, r->prop)
246 || (ch.res_class && strstr(ch.res_class, r->prop))
247 || (ch.res_name && strstr(ch.res_name, r->prop)))
249 c->isfloating = r->isfloating;
251 c->tags[idxoftag(r->tag)] = True;
261 memcpy(c->tags, seltags, TAGSZ);
268 for(c = clients; c; c = c->next)
288 attachstack(Client *c) {
297 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
302 buttonpress(XEvent *e) {
305 XButtonPressedEvent *ev = &e->xbutton;
307 if(ev->window == barwin) {
309 for(i = 0; i < LENGTH(tags); i++) {
312 if(ev->button == Button1) {
313 if(ev->state & MODKEY)
318 else if(ev->button == Button3) {
319 if(ev->state & MODKEY)
328 else if((c = getclient(ev->window))) {
330 if(CLEANMASK(ev->state) != MODKEY)
332 if(ev->button == Button1) {
336 else if(ev->button == Button2) {
337 if((floating != lt->arrange) && c->isfloating)
338 togglefloating(NULL);
342 else if(ev->button == Button3 && !c->isfixed) {
352 XSetErrorHandler(xerrorstart);
354 /* this causes an error if some other window manager is running */
355 XSelectInput(dpy, DefaultRootWindow(dpy), SubstructureRedirectMask);
358 eprint("dwm: another window manager is already running\n");
360 XSetErrorHandler(NULL);
361 xerrorxlib = XSetErrorHandler(xerror);
373 XFreeFontSet(dpy, dc.font.set);
375 XFreeFont(dpy, dc.font.xfont);
376 XUngrabKey(dpy, AnyKey, AnyModifier, root);
377 XFreePixmap(dpy, dc.drawable);
379 XFreeCursor(dpy, cursor[CurNormal]);
380 XFreeCursor(dpy, cursor[CurResize]);
381 XFreeCursor(dpy, cursor[CurMove]);
382 XDestroyWindow(dpy, barwin);
384 XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime);
388 configure(Client *c) {
391 ce.type = ConfigureNotify;
399 ce.border_width = c->border;
401 ce.override_redirect = False;
402 XSendEvent(dpy, c->win, False, StructureNotifyMask, (XEvent *)&ce);
406 configurenotify(XEvent *e) {
407 XConfigureEvent *ev = &e->xconfigure;
409 if(ev->window == root && (ev->width != sw || ev->height != sh)) {
416 configurerequest(XEvent *e) {
418 XConfigureRequestEvent *ev = &e->xconfigurerequest;
421 if((c = getclient(ev->window))) {
422 if(ev->value_mask & CWBorderWidth)
423 c->border = ev->border_width;
424 if(c->isfixed || c->isfloating || lt->isfloating) {
425 if(ev->value_mask & CWX)
427 if(ev->value_mask & CWY)
429 if(ev->value_mask & CWWidth)
431 if(ev->value_mask & CWHeight)
433 if((c->x - sx + c->w) > sw && c->isfloating)
434 c->x = sx + (sw / 2 - c->w / 2); /* center in x direction */
435 if((c->y - sy + c->h) > sh && c->isfloating)
436 c->y = sy + (sh / 2 - c->h / 2); /* center in y direction */
437 if((ev->value_mask & (CWX|CWY))
438 && !(ev->value_mask & (CWWidth|CWHeight)))
441 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h);
449 wc.width = ev->width;
450 wc.height = ev->height;
451 wc.border_width = ev->border_width;
452 wc.sibling = ev->above;
453 wc.stack_mode = ev->detail;
454 XConfigureWindow(dpy, ev->window, ev->value_mask, &wc);
460 destroynotify(XEvent *e) {
462 XDestroyWindowEvent *ev = &e->xdestroywindow;
464 if((c = getclient(ev->window)))
471 c->prev->next = c->next;
473 c->next->prev = c->prev;
476 c->next = c->prev = NULL;
480 detachstack(Client *c) {
483 for(tc=&stack; *tc && *tc != c; tc=&(*tc)->snext);
493 for(c = stack; c && !isvisible(c); c = c->snext);
494 for(i = 0; i < LENGTH(tags); i++) {
495 dc.w = textw(tags[i]);
497 drawtext(tags[i], dc.sel, isurgent(i));
498 drawsquare(c && c->tags[i], isoccupied(i), isurgent(i), dc.sel);
501 drawtext(tags[i], dc.norm, isurgent(i));
502 drawsquare(c && c->tags[i], isoccupied(i), isurgent(i), dc.norm);
507 drawtext(lt->symbol, dc.norm, False);
515 drawtext(stext, dc.norm, False);
516 if((dc.w = dc.x - x) > bh) {
519 drawtext(c->name, dc.sel, False);
520 drawsquare(False, c->isfloating, False, dc.sel);
523 drawtext(NULL, dc.norm, False);
525 XCopyArea(dpy, dc.drawable, barwin, dc.gc, 0, 0, bw, bh, 0, 0);
530 drawsquare(Bool filled, Bool empty, Bool invert, unsigned long col[ColLast]) {
533 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
535 gcv.foreground = col[invert ? ColBG : ColFG];
536 XChangeGC(dpy, dc.gc, GCForeground, &gcv);
537 x = (dc.font.ascent + dc.font.descent + 2) / 4;
541 r.width = r.height = x + 1;
542 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
545 r.width = r.height = x;
546 XDrawRectangles(dpy, dc.drawable, dc.gc, &r, 1);
551 drawtext(const char *text, unsigned long col[ColLast], Bool invert) {
553 unsigned int len, olen;
554 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
556 XSetForeground(dpy, dc.gc, col[invert ? ColFG : ColBG]);
557 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
561 olen = len = strlen(text);
562 if(len >= sizeof buf)
563 len = sizeof buf - 1;
564 memcpy(buf, text, len);
566 h = dc.font.ascent + dc.font.descent;
567 y = dc.y + (dc.h / 2) - (h / 2) + dc.font.ascent;
569 /* shorten text if necessary */
570 while(len && (w = textnw(buf, len)) > dc.w - h)
581 return; /* too long */
582 XSetForeground(dpy, dc.gc, col[invert ? ColBG : ColFG]);
584 XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
586 XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
590 emallocz(unsigned int size) {
591 void *res = calloc(1, size);
594 eprint("fatal: could not malloc() %u bytes\n", size);
599 enternotify(XEvent *e) {
601 XCrossingEvent *ev = &e->xcrossing;
603 if((ev->mode != NotifyNormal || ev->detail == NotifyInferior) && ev->window != root)
605 if((c = getclient(ev->window)))
612 eprint(const char *errstr, ...) {
615 va_start(ap, errstr);
616 vfprintf(stderr, errstr, ap);
623 XExposeEvent *ev = &e->xexpose;
625 if(ev->count == 0 && (ev->window == barwin))
630 floating(void) { /* default floating layout */
633 for(c = clients; c; c = c->next)
635 resize(c, c->x, c->y, c->w, c->h, True);
640 if(!c || (c && !isvisible(c)))
641 for(c = stack; c && !isvisible(c); c = c->snext);
642 if(sel && sel != c) {
643 grabbuttons(sel, False);
644 XSetWindowBorder(dpy, sel->win, dc.norm[ColBorder]);
649 grabbuttons(c, True);
653 XSetWindowBorder(dpy, c->win, dc.sel[ColBorder]);
654 XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
657 XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
662 focusin(XEvent *e) { /* there are some broken focus acquiring clients */
663 XFocusChangeEvent *ev = &e->xfocus;
665 if(sel && ev->window != sel->win)
666 XSetInputFocus(dpy, sel->win, RevertToPointerRoot, CurrentTime);
670 focusnext(const char *arg) {
675 for(c = sel->next; c && !isvisible(c); c = c->next);
677 for(c = clients; c && !isvisible(c); c = c->next);
685 focusprev(const char *arg) {
690 for(c = sel->prev; c && !isvisible(c); c = c->prev);
692 for(c = clients; c && c->next; c = c->next);
693 for(; c && !isvisible(c); c = c->prev);
702 getclient(Window w) {
705 for(c = clients; c && c->win != w; c = c->next);
710 getcolor(const char *colstr) {
711 Colormap cmap = DefaultColormap(dpy, screen);
714 if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
715 eprint("error, cannot allocate color '%s'\n", colstr);
723 unsigned char *p = NULL;
724 unsigned long n, extra;
727 status = XGetWindowProperty(dpy, w, wmatom[WMState], 0L, 2L, False, wmatom[WMState],
728 &real, &format, &n, &extra, (unsigned char **)&p);
729 if(status != Success)
738 gettextprop(Window w, Atom atom, char *text, unsigned int size) {
743 if(!text || size == 0)
746 XGetTextProperty(dpy, w, &name, atom);
749 if(name.encoding == XA_STRING)
750 strncpy(text, (char *)name.value, size - 1);
752 if(XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success
754 strncpy(text, *list, size - 1);
755 XFreeStringList(list);
758 text[size - 1] = '\0';
764 grabbuttons(Client *c, Bool focused) {
765 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
768 XGrabButton(dpy, Button1, MODKEY, c->win, False, BUTTONMASK,
769 GrabModeAsync, GrabModeSync, None, None);
770 XGrabButton(dpy, Button1, MODKEY|LockMask, c->win, False, BUTTONMASK,
771 GrabModeAsync, GrabModeSync, None, None);
772 XGrabButton(dpy, Button1, MODKEY|numlockmask, c->win, False, BUTTONMASK,
773 GrabModeAsync, GrabModeSync, None, None);
774 XGrabButton(dpy, Button1, MODKEY|numlockmask|LockMask, c->win, False, BUTTONMASK,
775 GrabModeAsync, GrabModeSync, None, None);
777 XGrabButton(dpy, Button2, MODKEY, c->win, False, BUTTONMASK,
778 GrabModeAsync, GrabModeSync, None, None);
779 XGrabButton(dpy, Button2, MODKEY|LockMask, c->win, False, BUTTONMASK,
780 GrabModeAsync, GrabModeSync, None, None);
781 XGrabButton(dpy, Button2, MODKEY|numlockmask, c->win, False, BUTTONMASK,
782 GrabModeAsync, GrabModeSync, None, None);
783 XGrabButton(dpy, Button2, MODKEY|numlockmask|LockMask, c->win, False, BUTTONMASK,
784 GrabModeAsync, GrabModeSync, None, None);
786 XGrabButton(dpy, Button3, MODKEY, c->win, False, BUTTONMASK,
787 GrabModeAsync, GrabModeSync, None, None);
788 XGrabButton(dpy, Button3, MODKEY|LockMask, c->win, False, BUTTONMASK,
789 GrabModeAsync, GrabModeSync, None, None);
790 XGrabButton(dpy, Button3, MODKEY|numlockmask, c->win, False, BUTTONMASK,
791 GrabModeAsync, GrabModeSync, None, None);
792 XGrabButton(dpy, Button3, MODKEY|numlockmask|LockMask, c->win, False, BUTTONMASK,
793 GrabModeAsync, GrabModeSync, None, None);
796 XGrabButton(dpy, AnyButton, AnyModifier, c->win, False, BUTTONMASK,
797 GrabModeAsync, GrabModeSync, None, None);
804 XModifierKeymap *modmap;
806 /* init modifier map */
807 modmap = XGetModifierMapping(dpy);
808 for(i = 0; i < 8; i++)
809 for(j = 0; j < modmap->max_keypermod; j++) {
810 if(modmap->modifiermap[i * modmap->max_keypermod + j] == XKeysymToKeycode(dpy, XK_Num_Lock))
811 numlockmask = (1 << i);
813 XFreeModifiermap(modmap);
815 XUngrabKey(dpy, AnyKey, AnyModifier, root);
816 for(i = 0; i < LENGTH(keys); i++) {
817 code = XKeysymToKeycode(dpy, keys[i].keysym);
818 XGrabKey(dpy, code, keys[i].mod, root, True,
819 GrabModeAsync, GrabModeAsync);
820 XGrabKey(dpy, code, keys[i].mod|LockMask, root, True,
821 GrabModeAsync, GrabModeAsync);
822 XGrabKey(dpy, code, keys[i].mod|numlockmask, root, True,
823 GrabModeAsync, GrabModeAsync);
824 XGrabKey(dpy, code, keys[i].mod|numlockmask|LockMask, root, True,
825 GrabModeAsync, GrabModeAsync);
830 idxoftag(const char *t) {
833 for(i = 0; (i < LENGTH(tags)) && (tags[i] != t); i++);
834 return (i < LENGTH(tags)) ? i : 0;
838 initfont(const char *fontstr) {
839 char *def, **missing;
844 XFreeFontSet(dpy, dc.font.set);
845 dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
848 fprintf(stderr, "dwm: missing fontset: %s\n", missing[n]);
849 XFreeStringList(missing);
852 XFontSetExtents *font_extents;
853 XFontStruct **xfonts;
855 dc.font.ascent = dc.font.descent = 0;
856 font_extents = XExtentsOfFontSet(dc.font.set);
857 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
858 for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
859 if(dc.font.ascent < (*xfonts)->ascent)
860 dc.font.ascent = (*xfonts)->ascent;
861 if(dc.font.descent < (*xfonts)->descent)
862 dc.font.descent = (*xfonts)->descent;
868 XFreeFont(dpy, dc.font.xfont);
869 dc.font.xfont = NULL;
870 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr))
871 && !(dc.font.xfont = XLoadQueryFont(dpy, "fixed")))
872 eprint("error, cannot load font: '%s'\n", fontstr);
873 dc.font.ascent = dc.font.xfont->ascent;
874 dc.font.descent = dc.font.xfont->descent;
876 dc.font.height = dc.font.ascent + dc.font.descent;
880 isoccupied(unsigned int t) {
883 for(c = clients; c; c = c->next)
890 isprotodel(Client *c) {
895 if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
896 for(i = 0; !ret && i < n; i++)
897 if(protocols[i] == wmatom[WMDelete])
905 isurgent(unsigned int t) {
908 for(c = clients; c; c = c->next)
909 if(c->isurgent && c->tags[t])
915 isvisible(Client *c) {
918 for(i = 0; i < LENGTH(tags); i++)
919 if(c->tags[i] && seltags[i])
925 keypress(XEvent *e) {
931 keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
932 for(i = 0; i < LENGTH(keys); i++)
933 if(keysym == keys[i].keysym
934 && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state))
937 keys[i].func(keys[i].arg);
942 killclient(const char *arg) {
947 if(isprotodel(sel)) {
948 ev.type = ClientMessage;
949 ev.xclient.window = sel->win;
950 ev.xclient.message_type = wmatom[WMProtocols];
951 ev.xclient.format = 32;
952 ev.xclient.data.l[0] = wmatom[WMDelete];
953 ev.xclient.data.l[1] = CurrentTime;
954 XSendEvent(dpy, sel->win, False, NoEventMask, &ev);
957 XKillClient(dpy, sel->win);
961 manage(Window w, XWindowAttributes *wa) {
962 Client *c, *t = NULL;
967 c = emallocz(sizeof(Client));
968 c->tags = emallocz(TAGSZ);
976 c->oldborder = wa->border_width;
977 if(c->w == sw && c->h == sh) {
980 c->border = wa->border_width;
983 if(c->x + c->w + 2 * c->border > wx + ww)
984 c->x = wx + ww - c->w - 2 * c->border;
985 if(c->y + c->h + 2 * c->border > wy + wh)
986 c->y = wy + wh - c->h - 2 * c->border;
991 c->border = BORDERPX;
994 wc.border_width = c->border;
995 XConfigureWindow(dpy, w, CWBorderWidth, &wc);
996 XSetWindowBorder(dpy, w, dc.norm[ColBorder]);
997 configure(c); /* propagates border_width, if size doesn't change */
999 XSelectInput(dpy, w, EnterWindowMask|FocusChangeMask|PropertyChangeMask|StructureNotifyMask);
1000 grabbuttons(c, False);
1002 if((rettrans = XGetTransientForHint(dpy, w, &trans) == Success))
1003 for(t = clients; t && t->win != trans; t = t->next);
1005 memcpy(c->tags, t->tags, TAGSZ);
1009 c->isfloating = (rettrans == Success) || c->isfixed;
1012 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h); /* some windows require this */
1014 XMapWindow(dpy, c->win);
1015 setclientstate(c, NormalState);
1020 mappingnotify(XEvent *e) {
1021 XMappingEvent *ev = &e->xmapping;
1023 XRefreshKeyboardMapping(ev);
1024 if(ev->request == MappingKeyboard)
1029 maprequest(XEvent *e) {
1030 static XWindowAttributes wa;
1031 XMapRequestEvent *ev = &e->xmaprequest;
1033 if(!XGetWindowAttributes(dpy, ev->window, &wa))
1035 if(wa.override_redirect)
1037 if(!getclient(ev->window))
1038 manage(ev->window, &wa);
1045 for(c = clients; c; c = c->next)
1047 resize(c, mox, moy, mow, moh, RESIZEHINTS);
1051 movemouse(Client *c) {
1052 int x1, y1, ocx, ocy, di, nx, ny;
1059 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1060 None, cursor[CurMove], CurrentTime) != GrabSuccess)
1062 XQueryPointer(dpy, root, &dummy, &dummy, &x1, &y1, &di, &di, &dui);
1064 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
1067 XUngrabPointer(dpy, CurrentTime);
1069 case ConfigureRequest:
1072 handler[ev.type](&ev);
1076 nx = ocx + (ev.xmotion.x - x1);
1077 ny = ocy + (ev.xmotion.y - y1);
1078 if(abs(wx - nx) < SNAP)
1080 else if(abs((wx + ww) - (nx + c->w + 2 * c->border)) < SNAP)
1081 nx = wx + ww - c->w - 2 * c->border;
1082 if(abs(wy - ny) < SNAP)
1084 else if(abs((wy + wh) - (ny + c->h + 2 * c->border)) < SNAP)
1085 ny = wy + wh - c->h - 2 * c->border;
1086 if(!c->isfloating && !lt->isfloating && (abs(nx - c->x) > SNAP || abs(ny - c->y) > SNAP))
1087 togglefloating(NULL);
1088 if((lt->isfloating) || c->isfloating)
1089 resize(c, nx, ny, c->w, c->h, False);
1096 nexttiled(Client *c) {
1097 for(; c && (c->isfloating || !isvisible(c)); c = c->next);
1102 propertynotify(XEvent *e) {
1105 XPropertyEvent *ev = &e->xproperty;
1107 if(ev->state == PropertyDelete)
1108 return; /* ignore */
1109 if((c = getclient(ev->window))) {
1112 case XA_WM_TRANSIENT_FOR:
1113 XGetTransientForHint(dpy, c->win, &trans);
1114 if(!c->isfloating && (c->isfloating = (getclient(trans) != NULL)))
1117 case XA_WM_NORMAL_HINTS:
1125 if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
1134 quit(const char *arg) {
1135 readin = running = False;
1139 reapply(const char *arg) {
1140 static Bool zerotags[LENGTH(tags)] = { 0 };
1143 for(c = clients; c; c = c->next) {
1144 memcpy(c->tags, zerotags, sizeof zerotags);
1151 resize(Client *c, int x, int y, int w, int h, Bool sizehints) {
1155 /* set minimum possible */
1161 /* temporarily remove base dimensions */
1165 /* adjust for aspect limits */
1166 if (c->minay > 0 && c->maxay > 0 && c->minax > 0 && c->maxax > 0) {
1167 if (w * c->maxay > h * c->maxax)
1168 w = h * c->maxax / c->maxay;
1169 else if (w * c->minay < h * c->minax)
1170 h = w * c->minay / c->minax;
1173 /* adjust for increment value */
1179 /* restore base dimensions */
1183 if(c->minw > 0 && w < c->minw)
1185 if(c->minh > 0 && h < c->minh)
1187 if(c->maxw > 0 && w > c->maxw)
1189 if(c->maxh > 0 && h > c->maxh)
1192 if(w <= 0 || h <= 0)
1195 x = sw - w - 2 * c->border;
1197 y = sh - h - 2 * c->border;
1198 if(x + w + 2 * c->border < sx)
1200 if(y + h + 2 * c->border < sy)
1202 if(c->x != x || c->y != y || c->w != w || c->h != h) {
1205 c->w = wc.width = w;
1206 c->h = wc.height = h;
1207 wc.border_width = c->border;
1208 XConfigureWindow(dpy, c->win,
1209 CWX|CWY|CWWidth|CWHeight|CWBorderWidth, &wc);
1216 resizemouse(Client *c) {
1223 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1224 None, cursor[CurResize], CurrentTime) != GrabSuccess)
1226 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->border - 1, c->h + c->border - 1);
1228 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask , &ev);
1231 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0,
1232 c->w + c->border - 1, c->h + c->border - 1);
1233 XUngrabPointer(dpy, CurrentTime);
1234 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1236 case ConfigureRequest:
1239 handler[ev.type](&ev);
1243 if((nw = ev.xmotion.x - ocx - 2 * c->border + 1) <= 0)
1245 if((nh = ev.xmotion.y - ocy - 2 * c->border + 1) <= 0)
1247 if(!c->isfloating && !lt->isfloating && (abs(nw - c->w) > SNAP || abs(nh - c->h) > SNAP))
1248 togglefloating(NULL);
1249 if((lt->isfloating) || c->isfloating)
1250 resize(c, c->x, c->y, nw, nh, True);
1265 if(sel->isfloating || lt->isfloating)
1266 XRaiseWindow(dpy, sel->win);
1267 if(!lt->isfloating) {
1268 wc.stack_mode = Below;
1269 wc.sibling = barwin;
1270 if(!sel->isfloating) {
1271 XConfigureWindow(dpy, sel->win, CWSibling|CWStackMode, &wc);
1272 wc.sibling = sel->win;
1274 for(c = nexttiled(clients); c; c = nexttiled(c->next)) {
1277 XConfigureWindow(dpy, c->win, CWSibling|CWStackMode, &wc);
1278 wc.sibling = c->win;
1282 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1288 char sbuf[sizeof stext];
1291 unsigned int len, offset;
1294 /* main event loop, also reads status text from stdin */
1296 xfd = ConnectionNumber(dpy);
1299 len = sizeof stext - 1;
1300 sbuf[len] = stext[len] = '\0'; /* 0-terminator is never touched */
1304 FD_SET(STDIN_FILENO, &rd);
1306 if(select(xfd + 1, &rd, NULL, NULL, NULL) == -1) {
1309 eprint("select failed\n");
1311 if(FD_ISSET(STDIN_FILENO, &rd)) {
1312 switch((r = read(STDIN_FILENO, sbuf + offset, len - offset))) {
1314 strncpy(stext, strerror(errno), len);
1318 strncpy(stext, "EOF", 4);
1322 for(p = sbuf + offset; r > 0; p++, r--, offset++)
1323 if(*p == '\n' || *p == '\0') {
1325 strncpy(stext, sbuf, len);
1326 p += r - 1; /* p is sbuf + offset + r - 1 */
1327 for(r = 0; *(p - r) && *(p - r) != '\n'; r++);
1330 memmove(sbuf, p - r + 1, r);
1337 while(XPending(dpy)) {
1338 XNextEvent(dpy, &ev);
1339 if(handler[ev.type])
1340 (handler[ev.type])(&ev); /* call handler */
1347 unsigned int i, num;
1348 Window *wins, d1, d2;
1349 XWindowAttributes wa;
1352 if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1353 for(i = 0; i < num; i++) {
1354 if(!XGetWindowAttributes(dpy, wins[i], &wa)
1355 || wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1357 if(wa.map_state == IsViewable || getstate(wins[i]) == IconicState)
1358 manage(wins[i], &wa);
1360 for(i = 0; i < num; i++) { /* now the transients */
1361 if(!XGetWindowAttributes(dpy, wins[i], &wa))
1363 if(XGetTransientForHint(dpy, wins[i], &d1)
1364 && (wa.map_state == IsViewable || getstate(wins[i]) == IconicState))
1365 manage(wins[i], &wa);
1373 setclientstate(Client *c, long state) {
1374 long data[] = {state, None};
1376 XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1377 PropModeReplace, (unsigned char *)data, 2);
1381 setdefaultgeoms(void) {
1383 /* screen dimensions */
1386 sw = DisplayWidth(dpy, screen);
1387 sh = DisplayHeight(dpy, screen);
1393 bh = dc.font.height + 2;
1404 mw = ((float)sw) * 0.55;
1423 setlayout(const char *arg) {
1424 static Layout *revert = 0;
1429 for(i = 0; i < LENGTH(layouts); i++)
1430 if(!strcmp(arg, layouts[i].symbol))
1432 if(i == LENGTH(layouts))
1434 if(revert && &layouts[i] == lt)
1449 XSetWindowAttributes wa;
1452 screen = DefaultScreen(dpy);
1453 root = RootWindow(dpy, screen);
1456 /* apply default geometries */
1460 wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1461 wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1462 wmatom[WMName] = XInternAtom(dpy, "WM_NAME", False);
1463 wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1464 netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1465 netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1468 wa.cursor = cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1469 cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1470 cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1472 /* init appearance */
1473 dc.norm[ColBorder] = getcolor(NORMBORDERCOLOR);
1474 dc.norm[ColBG] = getcolor(NORMBGCOLOR);
1475 dc.norm[ColFG] = getcolor(NORMFGCOLOR);
1476 dc.sel[ColBorder] = getcolor(SELBORDERCOLOR);
1477 dc.sel[ColBG] = getcolor(SELBGCOLOR);
1478 dc.sel[ColFG] = getcolor(SELFGCOLOR);
1481 dc.drawable = XCreatePixmap(dpy, root, DisplayWidth(dpy, screen), bh, DefaultDepth(dpy, screen));
1482 dc.gc = XCreateGC(dpy, root, 0, 0);
1483 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
1485 XSetFont(dpy, dc.gc, dc.font.xfont->fid);
1488 seltags = emallocz(TAGSZ);
1489 prevtags = emallocz(TAGSZ);
1490 seltags[0] = prevtags[0] = True;
1496 for(blw = i = 0; i < LENGTH(layouts); i++) {
1497 i = textw(layouts[i].symbol);
1502 wa.override_redirect = 1;
1503 wa.background_pixmap = ParentRelative;
1504 wa.event_mask = ButtonPressMask|ExposureMask;
1506 barwin = XCreateWindow(dpy, root, bx, by, bw, bh, 0, DefaultDepth(dpy, screen),
1507 CopyFromParent, DefaultVisual(dpy, screen),
1508 CWOverrideRedirect|CWBackPixmap|CWEventMask, &wa);
1509 XDefineCursor(dpy, barwin, cursor[CurNormal]);
1510 XMapRaised(dpy, barwin);
1511 strcpy(stext, "dwm-"VERSION);
1514 /* EWMH support per view */
1515 XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1516 PropModeReplace, (unsigned char *) netatom, NetLast);
1518 /* select for events */
1519 wa.event_mask = SubstructureRedirectMask|SubstructureNotifyMask
1520 |EnterWindowMask|LeaveWindowMask|StructureNotifyMask;
1521 XChangeWindowAttributes(dpy, root, CWEventMask|CWCursor, &wa);
1522 XSelectInput(dpy, root, wa.event_mask);
1530 spawn(const char *arg) {
1531 static char *shell = NULL;
1533 if(!shell && !(shell = getenv("SHELL")))
1537 /* The double-fork construct avoids zombie processes and keeps the code
1538 * clean from stupid signal handlers. */
1542 close(ConnectionNumber(dpy));
1544 execl(shell, shell, "-c", arg, (char *)NULL);
1545 fprintf(stderr, "dwm: execl '%s -c %s'", shell, arg);
1554 tag(const char *arg) {
1559 for(i = 0; i < LENGTH(tags); i++)
1560 sel->tags[i] = (NULL == arg);
1561 sel->tags[idxoftag(arg)] = True;
1566 textnw(const char *text, unsigned int len) {
1570 XmbTextExtents(dc.font.set, text, len, NULL, &r);
1573 return XTextWidth(dc.font.xfont, text, len);
1577 textw(const char *text) {
1578 return textnw(text, strlen(text)) + dc.font.height;
1582 tileresize(Client *c, int x, int y, int w, int h) {
1583 resize(c, x, y, w, h, RESIZEHINTS);
1584 if((RESIZEHINTS) && ((c->h < bh) || (c->h > h) || (c->w < bh) || (c->w > w)))
1585 /* client doesn't accept size constraints */
1586 resize(c, x, y, w, h, False);
1591 tilehstack(tilemaster());
1595 tilehstack(unsigned int n) {
1607 for(i = 0, c = nexttiled(clients); c; c = nexttiled(c->next), i++)
1609 if(i > 1 && i == n) /* remainder */
1610 tileresize(c, x, ty, (tx + tw) - x - 2 * c->border,
1611 th - 2 * c->border);
1613 tileresize(c, x, ty, w - 2 * c->border,
1614 th - 2 * c->border);
1616 x = c->x + c->w + 2 * c->border;
1625 for(n = 0, mc = c = nexttiled(clients); c; c = nexttiled(c->next))
1630 tileresize(mc, mox, moy, mow - 2 * mc->border, moh - 2 * mc->border);
1632 tileresize(mc, mx, my, mw - 2 * mc->border, mh - 2 * mc->border);
1638 tilevstack(tilemaster());
1642 tilevstack(unsigned int n) {
1654 for(i = 0, c = nexttiled(clients); c; c = nexttiled(c->next), i++)
1656 if(i > 1 && i == n) /* remainder */
1657 tileresize(c, tx, y, tw - 2 * c->border,
1658 (ty + th) - y - 2 * c->border);
1660 tileresize(c, tx, y, tw - 2 * c->border,
1663 y = c->y + c->h + 2 * c->border;
1668 togglefloating(const char *arg) {
1671 sel->isfloating = !sel->isfloating;
1673 resize(sel, sel->x, sel->y, sel->w, sel->h, True);
1678 toggletag(const char *arg) {
1684 sel->tags[i] = !sel->tags[i];
1685 for(j = 0; j < LENGTH(tags) && !sel->tags[j]; j++);
1686 if(j == LENGTH(tags))
1687 sel->tags[i] = True; /* at least one tag must be enabled */
1692 toggleview(const char *arg) {
1696 seltags[i] = !seltags[i];
1697 for(j = 0; j < LENGTH(tags) && !seltags[j]; j++);
1698 if(j == LENGTH(tags))
1699 seltags[i] = True; /* at least one tag must be viewed */
1707 XMoveWindow(dpy, c->win, c->x, c->y);
1708 c->isbanned = False;
1712 unmanage(Client *c) {
1715 wc.border_width = c->oldborder;
1716 /* The server grab construct avoids race conditions. */
1718 XSetErrorHandler(xerrordummy);
1719 XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
1724 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1725 setclientstate(c, WithdrawnState);
1729 XSetErrorHandler(xerror);
1735 unmapnotify(XEvent *e) {
1737 XUnmapEvent *ev = &e->xunmap;
1739 if((c = getclient(ev->window)))
1744 updatebarpos(void) {
1746 if(dc.drawable != 0)
1747 XFreePixmap(dpy, dc.drawable);
1748 dc.drawable = XCreatePixmap(dpy, root, bw, bh, DefaultDepth(dpy, screen));
1749 XMoveResizeWindow(dpy, barwin, bx, by, bw, bh);
1753 updatesizehints(Client *c) {
1757 if(!XGetWMNormalHints(dpy, c->win, &size, &msize) || !size.flags)
1759 c->flags = size.flags;
1760 if(c->flags & PBaseSize) {
1761 c->basew = size.base_width;
1762 c->baseh = size.base_height;
1764 else if(c->flags & PMinSize) {
1765 c->basew = size.min_width;
1766 c->baseh = size.min_height;
1769 c->basew = c->baseh = 0;
1770 if(c->flags & PResizeInc) {
1771 c->incw = size.width_inc;
1772 c->inch = size.height_inc;
1775 c->incw = c->inch = 0;
1776 if(c->flags & PMaxSize) {
1777 c->maxw = size.max_width;
1778 c->maxh = size.max_height;
1781 c->maxw = c->maxh = 0;
1782 if(c->flags & PMinSize) {
1783 c->minw = size.min_width;
1784 c->minh = size.min_height;
1786 else if(c->flags & PBaseSize) {
1787 c->minw = size.base_width;
1788 c->minh = size.base_height;
1791 c->minw = c->minh = 0;
1792 if(c->flags & PAspect) {
1793 c->minax = size.min_aspect.x;
1794 c->maxax = size.max_aspect.x;
1795 c->minay = size.min_aspect.y;
1796 c->maxay = size.max_aspect.y;
1799 c->minax = c->maxax = c->minay = c->maxay = 0;
1800 c->isfixed = (c->maxw && c->minw && c->maxh && c->minh
1801 && c->maxw == c->minw && c->maxh == c->minh);
1805 updatetitle(Client *c) {
1806 if(!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
1807 gettextprop(c->win, wmatom[WMName], c->name, sizeof c->name);
1811 updatewmhints(Client *c) {
1814 if((wmh = XGetWMHints(dpy, c->win))) {
1816 sel->isurgent = False;
1818 c->isurgent = (wmh->flags & XUrgencyHint) ? True : False;
1825 view(const char *arg) {
1828 for(i = 0; i < LENGTH(tags); i++)
1829 tmp[i] = (NULL == arg);
1830 tmp[idxoftag(arg)] = True;
1832 if(memcmp(seltags, tmp, TAGSZ) != 0) {
1833 memcpy(prevtags, seltags, TAGSZ);
1834 memcpy(seltags, tmp, TAGSZ);
1840 viewprevtag(const char *arg) {
1842 memcpy(tmp, seltags, TAGSZ);
1843 memcpy(seltags, prevtags, TAGSZ);
1844 memcpy(prevtags, tmp, TAGSZ);
1848 /* There's no way to check accesses to destroyed windows, thus those cases are
1849 * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
1850 * default error handler, which may call exit. */
1852 xerror(Display *dpy, XErrorEvent *ee) {
1853 if(ee->error_code == BadWindow
1854 || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1855 || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1856 || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1857 || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1858 || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1859 || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1860 || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1862 fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1863 ee->request_code, ee->error_code);
1864 return xerrorxlib(dpy, ee); /* may call exit */
1868 xerrordummy(Display *dpy, XErrorEvent *ee) {
1872 /* Startup Error handler to check if another window manager
1873 * is already running. */
1875 xerrorstart(Display *dpy, XErrorEvent *ee) {
1881 zoom(const char *arg) {
1884 if(!sel || lt->isfloating || sel->isfloating)
1886 if(c == nexttiled(clients))
1887 if(!(c = nexttiled(c->next)))
1896 main(int argc, char *argv[]) {
1897 if(argc == 2 && !strcmp("-v", argv[1]))
1898 eprint("dwm-"VERSION", © 2006-2008 dwm engineers, see LICENSE for details\n");
1900 eprint("usage: dwm [-v]\n");
1902 setlocale(LC_CTYPE, "");
1903 if(!(dpy = XOpenDisplay(0)))
1904 eprint("dwm: cannot open display\n");