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 updatesizehints(Client *c);
182 void updatetitle(Client *c);
183 void updatewmhints(Client *c);
184 void view(const char *arg);
185 void viewprevtag(const char *arg); /* views previous selected tags */
186 int xerror(Display *dpy, XErrorEvent *ee);
187 int xerrordummy(Display *dpy, XErrorEvent *ee);
188 int xerrorstart(Display *dpy, XErrorEvent *ee);
189 void zoom(const char *arg);
192 char stext[256], buf[256];
193 int screen, sx, sy, sw, sh;
194 int (*xerrorxlib)(Display *, XErrorEvent *);
195 int bx, by, bw, bh, blw, mx, my, mw, mh, mox, moy, mow, moh, tx, ty, tw, th, wx, wy, ww, wh;
196 unsigned int numlockmask = 0;
197 void (*handler[LASTEvent]) (XEvent *) = {
198 [ButtonPress] = buttonpress,
199 [ConfigureRequest] = configurerequest,
200 [ConfigureNotify] = configurenotify,
201 [DestroyNotify] = destroynotify,
202 [EnterNotify] = enternotify,
205 [KeyPress] = keypress,
206 [MappingNotify] = mappingnotify,
207 [MapRequest] = maprequest,
208 [PropertyNotify] = propertynotify,
209 [UnmapNotify] = unmapnotify
211 Atom wmatom[WMLast], netatom[NetLast];
212 Bool otherwm, readin;
216 Client *clients = NULL;
218 Client *stack = NULL;
219 Cursor cursor[CurLast];
224 void (*setgeoms)(void) = setdefaultgeoms;
226 /* configuration, allows nested code to access above variables */
228 #define TAGSZ (LENGTH(tags) * sizeof(Bool))
229 static Bool tmp[LENGTH(tags)];
231 /* function implementations */
234 applyrules(Client *c) {
236 Bool matched = False;
238 XClassHint ch = { 0 };
241 XGetClassHint(dpy, c->win, &ch);
242 for(i = 0; i < LENGTH(rules); i++) {
244 if(strstr(c->name, r->prop)
245 || (ch.res_class && strstr(ch.res_class, r->prop))
246 || (ch.res_name && strstr(ch.res_name, r->prop)))
248 c->isfloating = r->isfloating;
250 c->tags[idxoftag(r->tag)] = True;
260 memcpy(c->tags, seltags, TAGSZ);
267 for(c = clients; c; c = c->next)
287 attachstack(Client *c) {
296 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
301 buttonpress(XEvent *e) {
304 XButtonPressedEvent *ev = &e->xbutton;
306 if(ev->window == barwin) {
308 for(i = 0; i < LENGTH(tags); i++) {
311 if(ev->button == Button1) {
312 if(ev->state & MODKEY)
317 else if(ev->button == Button3) {
318 if(ev->state & MODKEY)
327 else if((c = getclient(ev->window))) {
329 if(CLEANMASK(ev->state) != MODKEY)
331 if(ev->button == Button1) {
335 else if(ev->button == Button2) {
336 if((floating != lt->arrange) && c->isfloating)
337 togglefloating(NULL);
341 else if(ev->button == Button3 && !c->isfixed) {
351 XSetErrorHandler(xerrorstart);
353 /* this causes an error if some other window manager is running */
354 XSelectInput(dpy, DefaultRootWindow(dpy), SubstructureRedirectMask);
357 eprint("dwm: another window manager is already running\n");
359 XSetErrorHandler(NULL);
360 xerrorxlib = XSetErrorHandler(xerror);
372 XFreeFontSet(dpy, dc.font.set);
374 XFreeFont(dpy, dc.font.xfont);
375 XUngrabKey(dpy, AnyKey, AnyModifier, root);
376 XFreePixmap(dpy, dc.drawable);
378 XFreeCursor(dpy, cursor[CurNormal]);
379 XFreeCursor(dpy, cursor[CurResize]);
380 XFreeCursor(dpy, cursor[CurMove]);
381 XDestroyWindow(dpy, barwin);
383 XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime);
387 configure(Client *c) {
390 ce.type = ConfigureNotify;
398 ce.border_width = c->border;
400 ce.override_redirect = False;
401 XSendEvent(dpy, c->win, False, StructureNotifyMask, (XEvent *)&ce);
405 configurenotify(XEvent *e) {
406 XConfigureEvent *ev = &e->xconfigure;
408 if(ev->window == root && (ev->width != sw || ev->height != sh)) {
415 configurerequest(XEvent *e) {
417 XConfigureRequestEvent *ev = &e->xconfigurerequest;
420 if((c = getclient(ev->window))) {
421 if(ev->value_mask & CWBorderWidth)
422 c->border = ev->border_width;
423 if(c->isfixed || c->isfloating || lt->isfloating) {
424 if(ev->value_mask & CWX)
426 if(ev->value_mask & CWY)
428 if(ev->value_mask & CWWidth)
430 if(ev->value_mask & CWHeight)
432 if((c->x - sx + c->w) > sw && c->isfloating)
433 c->x = sx + (sw / 2 - c->w / 2); /* center in x direction */
434 if((c->y - sy + c->h) > sh && c->isfloating)
435 c->y = sy + (sh / 2 - c->h / 2); /* center in y direction */
436 if((ev->value_mask & (CWX|CWY))
437 && !(ev->value_mask & (CWWidth|CWHeight)))
440 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h);
448 wc.width = ev->width;
449 wc.height = ev->height;
450 wc.border_width = ev->border_width;
451 wc.sibling = ev->above;
452 wc.stack_mode = ev->detail;
453 XConfigureWindow(dpy, ev->window, ev->value_mask, &wc);
459 destroynotify(XEvent *e) {
461 XDestroyWindowEvent *ev = &e->xdestroywindow;
463 if((c = getclient(ev->window)))
470 c->prev->next = c->next;
472 c->next->prev = c->prev;
475 c->next = c->prev = NULL;
479 detachstack(Client *c) {
482 for(tc=&stack; *tc && *tc != c; tc=&(*tc)->snext);
492 for(c = stack; c && !isvisible(c); c = c->snext);
493 for(i = 0; i < LENGTH(tags); i++) {
494 dc.w = textw(tags[i]);
496 drawtext(tags[i], dc.sel, isurgent(i));
497 drawsquare(c && c->tags[i], isoccupied(i), isurgent(i), dc.sel);
500 drawtext(tags[i], dc.norm, isurgent(i));
501 drawsquare(c && c->tags[i], isoccupied(i), isurgent(i), dc.norm);
506 drawtext(lt->symbol, dc.norm, False);
514 drawtext(stext, dc.norm, False);
515 if((dc.w = dc.x - x) > bh) {
518 drawtext(c->name, dc.sel, False);
519 drawsquare(False, c->isfloating, False, dc.sel);
522 drawtext(NULL, dc.norm, False);
524 XCopyArea(dpy, dc.drawable, barwin, dc.gc, 0, 0, bw, bh, 0, 0);
529 drawsquare(Bool filled, Bool empty, Bool invert, unsigned long col[ColLast]) {
532 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
534 gcv.foreground = col[invert ? ColBG : ColFG];
535 XChangeGC(dpy, dc.gc, GCForeground, &gcv);
536 x = (dc.font.ascent + dc.font.descent + 2) / 4;
540 r.width = r.height = x + 1;
541 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
544 r.width = r.height = x;
545 XDrawRectangles(dpy, dc.drawable, dc.gc, &r, 1);
550 drawtext(const char *text, unsigned long col[ColLast], Bool invert) {
552 unsigned int len, olen;
553 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
555 XSetForeground(dpy, dc.gc, col[invert ? ColFG : ColBG]);
556 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
560 olen = len = strlen(text);
561 if(len >= sizeof buf)
562 len = sizeof buf - 1;
563 memcpy(buf, text, len);
565 h = dc.font.ascent + dc.font.descent;
566 y = dc.y + (dc.h / 2) - (h / 2) + dc.font.ascent;
568 /* shorten text if necessary */
569 while(len && (w = textnw(buf, len)) > dc.w - h)
580 return; /* too long */
581 XSetForeground(dpy, dc.gc, col[invert ? ColBG : ColFG]);
583 XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
585 XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
589 emallocz(unsigned int size) {
590 void *res = calloc(1, size);
593 eprint("fatal: could not malloc() %u bytes\n", size);
598 enternotify(XEvent *e) {
600 XCrossingEvent *ev = &e->xcrossing;
602 if((ev->mode != NotifyNormal || ev->detail == NotifyInferior) && ev->window != root)
604 if((c = getclient(ev->window)))
611 eprint(const char *errstr, ...) {
614 va_start(ap, errstr);
615 vfprintf(stderr, errstr, ap);
622 XExposeEvent *ev = &e->xexpose;
624 if(ev->count == 0 && (ev->window == barwin))
629 floating(void) { /* default floating layout */
632 for(c = clients; c; c = c->next)
634 resize(c, c->x, c->y, c->w, c->h, True);
639 if(!c || (c && !isvisible(c)))
640 for(c = stack; c && !isvisible(c); c = c->snext);
641 if(sel && sel != c) {
642 grabbuttons(sel, False);
643 XSetWindowBorder(dpy, sel->win, dc.norm[ColBorder]);
648 grabbuttons(c, True);
652 XSetWindowBorder(dpy, c->win, dc.sel[ColBorder]);
653 XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
656 XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
661 focusin(XEvent *e) { /* there are some broken focus acquiring clients */
662 XFocusChangeEvent *ev = &e->xfocus;
664 if(sel && ev->window != sel->win)
665 XSetInputFocus(dpy, sel->win, RevertToPointerRoot, CurrentTime);
669 focusnext(const char *arg) {
674 for(c = sel->next; c && !isvisible(c); c = c->next);
676 for(c = clients; c && !isvisible(c); c = c->next);
684 focusprev(const char *arg) {
689 for(c = sel->prev; c && !isvisible(c); c = c->prev);
691 for(c = clients; c && c->next; c = c->next);
692 for(; c && !isvisible(c); c = c->prev);
701 getclient(Window w) {
704 for(c = clients; c && c->win != w; c = c->next);
709 getcolor(const char *colstr) {
710 Colormap cmap = DefaultColormap(dpy, screen);
713 if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
714 eprint("error, cannot allocate color '%s'\n", colstr);
722 unsigned char *p = NULL;
723 unsigned long n, extra;
726 status = XGetWindowProperty(dpy, w, wmatom[WMState], 0L, 2L, False, wmatom[WMState],
727 &real, &format, &n, &extra, (unsigned char **)&p);
728 if(status != Success)
737 gettextprop(Window w, Atom atom, char *text, unsigned int size) {
742 if(!text || size == 0)
745 XGetTextProperty(dpy, w, &name, atom);
748 if(name.encoding == XA_STRING)
749 strncpy(text, (char *)name.value, size - 1);
751 if(XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success
753 strncpy(text, *list, size - 1);
754 XFreeStringList(list);
757 text[size - 1] = '\0';
763 grabbuttons(Client *c, Bool focused) {
764 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
767 XGrabButton(dpy, Button1, MODKEY, c->win, False, BUTTONMASK,
768 GrabModeAsync, GrabModeSync, None, None);
769 XGrabButton(dpy, Button1, MODKEY|LockMask, c->win, False, BUTTONMASK,
770 GrabModeAsync, GrabModeSync, None, None);
771 XGrabButton(dpy, Button1, MODKEY|numlockmask, c->win, False, BUTTONMASK,
772 GrabModeAsync, GrabModeSync, None, None);
773 XGrabButton(dpy, Button1, MODKEY|numlockmask|LockMask, c->win, False, BUTTONMASK,
774 GrabModeAsync, GrabModeSync, None, None);
776 XGrabButton(dpy, Button2, MODKEY, c->win, False, BUTTONMASK,
777 GrabModeAsync, GrabModeSync, None, None);
778 XGrabButton(dpy, Button2, MODKEY|LockMask, c->win, False, BUTTONMASK,
779 GrabModeAsync, GrabModeSync, None, None);
780 XGrabButton(dpy, Button2, MODKEY|numlockmask, c->win, False, BUTTONMASK,
781 GrabModeAsync, GrabModeSync, None, None);
782 XGrabButton(dpy, Button2, MODKEY|numlockmask|LockMask, c->win, False, BUTTONMASK,
783 GrabModeAsync, GrabModeSync, None, None);
785 XGrabButton(dpy, Button3, MODKEY, c->win, False, BUTTONMASK,
786 GrabModeAsync, GrabModeSync, None, None);
787 XGrabButton(dpy, Button3, MODKEY|LockMask, c->win, False, BUTTONMASK,
788 GrabModeAsync, GrabModeSync, None, None);
789 XGrabButton(dpy, Button3, MODKEY|numlockmask, c->win, False, BUTTONMASK,
790 GrabModeAsync, GrabModeSync, None, None);
791 XGrabButton(dpy, Button3, MODKEY|numlockmask|LockMask, c->win, False, BUTTONMASK,
792 GrabModeAsync, GrabModeSync, None, None);
795 XGrabButton(dpy, AnyButton, AnyModifier, c->win, False, BUTTONMASK,
796 GrabModeAsync, GrabModeSync, None, None);
803 XModifierKeymap *modmap;
805 /* init modifier map */
806 modmap = XGetModifierMapping(dpy);
807 for(i = 0; i < 8; i++)
808 for(j = 0; j < modmap->max_keypermod; j++) {
809 if(modmap->modifiermap[i * modmap->max_keypermod + j] == XKeysymToKeycode(dpy, XK_Num_Lock))
810 numlockmask = (1 << i);
812 XFreeModifiermap(modmap);
814 XUngrabKey(dpy, AnyKey, AnyModifier, root);
815 for(i = 0; i < LENGTH(keys); i++) {
816 code = XKeysymToKeycode(dpy, keys[i].keysym);
817 XGrabKey(dpy, code, keys[i].mod, root, True,
818 GrabModeAsync, GrabModeAsync);
819 XGrabKey(dpy, code, keys[i].mod|LockMask, root, True,
820 GrabModeAsync, GrabModeAsync);
821 XGrabKey(dpy, code, keys[i].mod|numlockmask, root, True,
822 GrabModeAsync, GrabModeAsync);
823 XGrabKey(dpy, code, keys[i].mod|numlockmask|LockMask, root, True,
824 GrabModeAsync, GrabModeAsync);
829 idxoftag(const char *t) {
832 for(i = 0; (i < LENGTH(tags)) && (tags[i] != t); i++);
833 return (i < LENGTH(tags)) ? i : 0;
837 initfont(const char *fontstr) {
838 char *def, **missing;
843 XFreeFontSet(dpy, dc.font.set);
844 dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
847 fprintf(stderr, "dwm: missing fontset: %s\n", missing[n]);
848 XFreeStringList(missing);
851 XFontSetExtents *font_extents;
852 XFontStruct **xfonts;
854 dc.font.ascent = dc.font.descent = 0;
855 font_extents = XExtentsOfFontSet(dc.font.set);
856 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
857 for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
858 if(dc.font.ascent < (*xfonts)->ascent)
859 dc.font.ascent = (*xfonts)->ascent;
860 if(dc.font.descent < (*xfonts)->descent)
861 dc.font.descent = (*xfonts)->descent;
867 XFreeFont(dpy, dc.font.xfont);
868 dc.font.xfont = NULL;
869 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr))
870 && !(dc.font.xfont = XLoadQueryFont(dpy, "fixed")))
871 eprint("error, cannot load font: '%s'\n", fontstr);
872 dc.font.ascent = dc.font.xfont->ascent;
873 dc.font.descent = dc.font.xfont->descent;
875 dc.font.height = dc.font.ascent + dc.font.descent;
879 isoccupied(unsigned int t) {
882 for(c = clients; c; c = c->next)
889 isprotodel(Client *c) {
894 if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
895 for(i = 0; !ret && i < n; i++)
896 if(protocols[i] == wmatom[WMDelete])
904 isurgent(unsigned int t) {
907 for(c = clients; c; c = c->next)
908 if(c->isurgent && c->tags[t])
914 isvisible(Client *c) {
917 for(i = 0; i < LENGTH(tags); i++)
918 if(c->tags[i] && seltags[i])
924 keypress(XEvent *e) {
930 keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
931 for(i = 0; i < LENGTH(keys); i++)
932 if(keysym == keys[i].keysym
933 && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state))
936 keys[i].func(keys[i].arg);
941 killclient(const char *arg) {
946 if(isprotodel(sel)) {
947 ev.type = ClientMessage;
948 ev.xclient.window = sel->win;
949 ev.xclient.message_type = wmatom[WMProtocols];
950 ev.xclient.format = 32;
951 ev.xclient.data.l[0] = wmatom[WMDelete];
952 ev.xclient.data.l[1] = CurrentTime;
953 XSendEvent(dpy, sel->win, False, NoEventMask, &ev);
956 XKillClient(dpy, sel->win);
960 manage(Window w, XWindowAttributes *wa) {
961 Client *c, *t = NULL;
966 c = emallocz(sizeof(Client));
967 c->tags = emallocz(TAGSZ);
975 c->oldborder = wa->border_width;
976 if(c->w == sw && c->h == sh) {
979 c->border = wa->border_width;
982 if(c->x + c->w + 2 * c->border > wx + ww)
983 c->x = wx + ww - c->w - 2 * c->border;
984 if(c->y + c->h + 2 * c->border > wy + wh)
985 c->y = wy + wh - c->h - 2 * c->border;
990 c->border = BORDERPX;
993 wc.border_width = c->border;
994 XConfigureWindow(dpy, w, CWBorderWidth, &wc);
995 XSetWindowBorder(dpy, w, dc.norm[ColBorder]);
996 configure(c); /* propagates border_width, if size doesn't change */
998 XSelectInput(dpy, w, EnterWindowMask|FocusChangeMask|PropertyChangeMask|StructureNotifyMask);
999 grabbuttons(c, False);
1001 if((rettrans = XGetTransientForHint(dpy, w, &trans) == Success))
1002 for(t = clients; t && t->win != trans; t = t->next);
1004 memcpy(c->tags, t->tags, TAGSZ);
1008 c->isfloating = (rettrans == Success) || c->isfixed;
1011 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h); /* some windows require this */
1013 XMapWindow(dpy, c->win);
1014 setclientstate(c, NormalState);
1019 mappingnotify(XEvent *e) {
1020 XMappingEvent *ev = &e->xmapping;
1022 XRefreshKeyboardMapping(ev);
1023 if(ev->request == MappingKeyboard)
1028 maprequest(XEvent *e) {
1029 static XWindowAttributes wa;
1030 XMapRequestEvent *ev = &e->xmaprequest;
1032 if(!XGetWindowAttributes(dpy, ev->window, &wa))
1034 if(wa.override_redirect)
1036 if(!getclient(ev->window))
1037 manage(ev->window, &wa);
1044 for(c = clients; c; c = c->next)
1046 resize(c, mox, moy, mow, moh, RESIZEHINTS);
1050 movemouse(Client *c) {
1051 int x1, y1, ocx, ocy, di, nx, ny;
1058 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1059 None, cursor[CurMove], CurrentTime) != GrabSuccess)
1061 XQueryPointer(dpy, root, &dummy, &dummy, &x1, &y1, &di, &di, &dui);
1063 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
1066 XUngrabPointer(dpy, CurrentTime);
1068 case ConfigureRequest:
1071 handler[ev.type](&ev);
1075 nx = ocx + (ev.xmotion.x - x1);
1076 ny = ocy + (ev.xmotion.y - y1);
1077 if(abs(wx - nx) < SNAP)
1079 else if(abs((wx + ww) - (nx + c->w + 2 * c->border)) < SNAP)
1080 nx = wx + ww - c->w - 2 * c->border;
1081 if(abs(wy - ny) < SNAP)
1083 else if(abs((wy + wh) - (ny + c->h + 2 * c->border)) < SNAP)
1084 ny = wy + wh - c->h - 2 * c->border;
1085 if(!c->isfloating && !lt->isfloating && (abs(nx - c->x) > SNAP || abs(ny - c->y) > SNAP))
1086 togglefloating(NULL);
1087 if((lt->isfloating) || c->isfloating)
1088 resize(c, nx, ny, c->w, c->h, False);
1095 nexttiled(Client *c) {
1096 for(; c && (c->isfloating || !isvisible(c)); c = c->next);
1101 propertynotify(XEvent *e) {
1104 XPropertyEvent *ev = &e->xproperty;
1106 if(ev->state == PropertyDelete)
1107 return; /* ignore */
1108 if((c = getclient(ev->window))) {
1111 case XA_WM_TRANSIENT_FOR:
1112 XGetTransientForHint(dpy, c->win, &trans);
1113 if(!c->isfloating && (c->isfloating = (getclient(trans) != NULL)))
1116 case XA_WM_NORMAL_HINTS:
1124 if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
1133 quit(const char *arg) {
1134 readin = running = False;
1138 reapply(const char *arg) {
1139 static Bool zerotags[LENGTH(tags)] = { 0 };
1142 for(c = clients; c; c = c->next) {
1143 memcpy(c->tags, zerotags, sizeof zerotags);
1150 resize(Client *c, int x, int y, int w, int h, Bool sizehints) {
1154 /* set minimum possible */
1160 /* temporarily remove base dimensions */
1164 /* adjust for aspect limits */
1165 if (c->minay > 0 && c->maxay > 0 && c->minax > 0 && c->maxax > 0) {
1166 if (w * c->maxay > h * c->maxax)
1167 w = h * c->maxax / c->maxay;
1168 else if (w * c->minay < h * c->minax)
1169 h = w * c->minay / c->minax;
1172 /* adjust for increment value */
1178 /* restore base dimensions */
1182 if(c->minw > 0 && w < c->minw)
1184 if(c->minh > 0 && h < c->minh)
1186 if(c->maxw > 0 && w > c->maxw)
1188 if(c->maxh > 0 && h > c->maxh)
1191 if(w <= 0 || h <= 0)
1194 x = sw - w - 2 * c->border;
1196 y = sh - h - 2 * c->border;
1197 if(x + w + 2 * c->border < sx)
1199 if(y + h + 2 * c->border < sy)
1201 if(c->x != x || c->y != y || c->w != w || c->h != h) {
1204 c->w = wc.width = w;
1205 c->h = wc.height = h;
1206 wc.border_width = c->border;
1207 XConfigureWindow(dpy, c->win,
1208 CWX|CWY|CWWidth|CWHeight|CWBorderWidth, &wc);
1215 resizemouse(Client *c) {
1222 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1223 None, cursor[CurResize], CurrentTime) != GrabSuccess)
1225 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->border - 1, c->h + c->border - 1);
1227 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask , &ev);
1230 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0,
1231 c->w + c->border - 1, c->h + c->border - 1);
1232 XUngrabPointer(dpy, CurrentTime);
1233 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1235 case ConfigureRequest:
1238 handler[ev.type](&ev);
1242 if((nw = ev.xmotion.x - ocx - 2 * c->border + 1) <= 0)
1244 if((nh = ev.xmotion.y - ocy - 2 * c->border + 1) <= 0)
1246 if(!c->isfloating && !lt->isfloating && (abs(nw - c->w) > SNAP || abs(nh - c->h) > SNAP))
1247 togglefloating(NULL);
1248 if((lt->isfloating) || c->isfloating)
1249 resize(c, c->x, c->y, nw, nh, True);
1264 if(sel->isfloating || lt->isfloating)
1265 XRaiseWindow(dpy, sel->win);
1266 if(!lt->isfloating) {
1267 wc.stack_mode = Below;
1268 wc.sibling = barwin;
1269 if(!sel->isfloating) {
1270 XConfigureWindow(dpy, sel->win, CWSibling|CWStackMode, &wc);
1271 wc.sibling = sel->win;
1273 for(c = nexttiled(clients); c; c = nexttiled(c->next)) {
1276 XConfigureWindow(dpy, c->win, CWSibling|CWStackMode, &wc);
1277 wc.sibling = c->win;
1281 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1287 char sbuf[sizeof stext];
1290 unsigned int len, offset;
1293 /* main event loop, also reads status text from stdin */
1295 xfd = ConnectionNumber(dpy);
1298 len = sizeof stext - 1;
1299 sbuf[len] = stext[len] = '\0'; /* 0-terminator is never touched */
1303 FD_SET(STDIN_FILENO, &rd);
1305 if(select(xfd + 1, &rd, NULL, NULL, NULL) == -1) {
1308 eprint("select failed\n");
1310 if(FD_ISSET(STDIN_FILENO, &rd)) {
1311 switch((r = read(STDIN_FILENO, sbuf + offset, len - offset))) {
1313 strncpy(stext, strerror(errno), len);
1317 strncpy(stext, "EOF", 4);
1321 for(p = sbuf + offset; r > 0; p++, r--, offset++)
1322 if(*p == '\n' || *p == '\0') {
1324 strncpy(stext, sbuf, len);
1325 p += r - 1; /* p is sbuf + offset + r - 1 */
1326 for(r = 0; *(p - r) && *(p - r) != '\n'; r++);
1329 memmove(sbuf, p - r + 1, r);
1336 while(XPending(dpy)) {
1337 XNextEvent(dpy, &ev);
1338 if(handler[ev.type])
1339 (handler[ev.type])(&ev); /* call handler */
1346 unsigned int i, num;
1347 Window *wins, d1, d2;
1348 XWindowAttributes wa;
1351 if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1352 for(i = 0; i < num; i++) {
1353 if(!XGetWindowAttributes(dpy, wins[i], &wa)
1354 || wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1356 if(wa.map_state == IsViewable || getstate(wins[i]) == IconicState)
1357 manage(wins[i], &wa);
1359 for(i = 0; i < num; i++) { /* now the transients */
1360 if(!XGetWindowAttributes(dpy, wins[i], &wa))
1362 if(XGetTransientForHint(dpy, wins[i], &d1)
1363 && (wa.map_state == IsViewable || getstate(wins[i]) == IconicState))
1364 manage(wins[i], &wa);
1372 setclientstate(Client *c, long state) {
1373 long data[] = {state, None};
1375 XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1376 PropModeReplace, (unsigned char *)data, 2);
1380 setdefaultgeoms(void) {
1382 /* screen dimensions */
1385 sw = DisplayWidth(dpy, screen);
1386 sh = DisplayHeight(dpy, screen);
1392 bh = dc.font.height + 2;
1403 mw = ((float)sw) * 0.55;
1418 if(dc.drawable != 0)
1419 XFreePixmap(dpy, dc.drawable);
1420 dc.drawable = XCreatePixmap(dpy, root, bw, bh, DefaultDepth(dpy, screen));
1421 XMoveResizeWindow(dpy, barwin, bx, by, bw, bh);
1425 setlayout(const char *arg) {
1426 static Layout *revert = 0;
1431 for(i = 0; i < LENGTH(layouts); i++)
1432 if(!strcmp(arg, layouts[i].symbol))
1434 if(i == LENGTH(layouts))
1436 if(revert && &layouts[i] == lt)
1451 XSetWindowAttributes wa;
1454 screen = DefaultScreen(dpy);
1455 root = RootWindow(dpy, screen);
1458 /* apply default geometries */
1462 wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1463 wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1464 wmatom[WMName] = XInternAtom(dpy, "WM_NAME", False);
1465 wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1466 netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1467 netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1470 wa.cursor = cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1471 cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1472 cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1474 /* init appearance */
1475 dc.norm[ColBorder] = getcolor(NORMBORDERCOLOR);
1476 dc.norm[ColBG] = getcolor(NORMBGCOLOR);
1477 dc.norm[ColFG] = getcolor(NORMFGCOLOR);
1478 dc.sel[ColBorder] = getcolor(SELBORDERCOLOR);
1479 dc.sel[ColBG] = getcolor(SELBGCOLOR);
1480 dc.sel[ColFG] = getcolor(SELFGCOLOR);
1483 dc.drawable = XCreatePixmap(dpy, root, DisplayWidth(dpy, screen), bh, DefaultDepth(dpy, screen));
1484 dc.gc = XCreateGC(dpy, root, 0, 0);
1485 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
1487 XSetFont(dpy, dc.gc, dc.font.xfont->fid);
1490 seltags = emallocz(TAGSZ);
1491 prevtags = emallocz(TAGSZ);
1492 seltags[0] = prevtags[0] = True;
1498 for(blw = i = 0; i < LENGTH(layouts); i++) {
1499 i = textw(layouts[i].symbol);
1504 wa.override_redirect = 1;
1505 wa.background_pixmap = ParentRelative;
1506 wa.event_mask = ButtonPressMask|ExposureMask;
1508 barwin = XCreateWindow(dpy, root, bx, by, bw, bh, 0, DefaultDepth(dpy, screen),
1509 CopyFromParent, DefaultVisual(dpy, screen),
1510 CWOverrideRedirect|CWBackPixmap|CWEventMask, &wa);
1511 XDefineCursor(dpy, barwin, cursor[CurNormal]);
1512 XMapRaised(dpy, barwin);
1513 strcpy(stext, "dwm-"VERSION);
1516 /* EWMH support per view */
1517 XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1518 PropModeReplace, (unsigned char *) netatom, NetLast);
1520 /* select for events */
1521 wa.event_mask = SubstructureRedirectMask|SubstructureNotifyMask
1522 |EnterWindowMask|LeaveWindowMask|StructureNotifyMask;
1523 XChangeWindowAttributes(dpy, root, CWEventMask|CWCursor, &wa);
1524 XSelectInput(dpy, root, wa.event_mask);
1532 spawn(const char *arg) {
1533 static char *shell = NULL;
1535 if(!shell && !(shell = getenv("SHELL")))
1539 /* The double-fork construct avoids zombie processes and keeps the code
1540 * clean from stupid signal handlers. */
1544 close(ConnectionNumber(dpy));
1546 execl(shell, shell, "-c", arg, (char *)NULL);
1547 fprintf(stderr, "dwm: execl '%s -c %s'", shell, arg);
1556 tag(const char *arg) {
1561 for(i = 0; i < LENGTH(tags); i++)
1562 sel->tags[i] = (NULL == arg);
1563 sel->tags[idxoftag(arg)] = True;
1568 textnw(const char *text, unsigned int len) {
1572 XmbTextExtents(dc.font.set, text, len, NULL, &r);
1575 return XTextWidth(dc.font.xfont, text, len);
1579 textw(const char *text) {
1580 return textnw(text, strlen(text)) + dc.font.height;
1584 tileresize(Client *c, int x, int y, int w, int h) {
1585 resize(c, x, y, w, h, RESIZEHINTS);
1586 if((RESIZEHINTS) && ((c->h < bh) || (c->h > h) || (c->w < bh) || (c->w > w)))
1587 /* client doesn't accept size constraints */
1588 resize(c, x, y, w, h, False);
1593 tilehstack(tilemaster());
1597 tilehstack(unsigned int n) {
1609 for(i = 0, c = nexttiled(clients); c; c = nexttiled(c->next), i++)
1611 if(i > 1 && i == n) /* remainder */
1612 tileresize(c, x, ty, (tx + tw) - x - 2 * c->border,
1613 th - 2 * c->border);
1615 tileresize(c, x, ty, w - 2 * c->border,
1616 th - 2 * c->border);
1618 x = c->x + c->w + 2 * c->border;
1627 for(n = 0, mc = c = nexttiled(clients); c; c = nexttiled(c->next))
1632 tileresize(mc, mox, moy, mow - 2 * mc->border, moh - 2 * mc->border);
1634 tileresize(mc, mx, my, mw - 2 * mc->border, mh - 2 * mc->border);
1640 tilevstack(tilemaster());
1644 tilevstack(unsigned int n) {
1656 for(i = 0, c = nexttiled(clients); c; c = nexttiled(c->next), i++)
1658 if(i > 1 && i == n) /* remainder */
1659 tileresize(c, tx, y, tw - 2 * c->border,
1660 (ty + th) - y - 2 * c->border);
1662 tileresize(c, tx, y, tw - 2 * c->border,
1665 y = c->y + c->h + 2 * c->border;
1670 togglefloating(const char *arg) {
1673 sel->isfloating = !sel->isfloating;
1675 resize(sel, sel->x, sel->y, sel->w, sel->h, True);
1680 toggletag(const char *arg) {
1686 sel->tags[i] = !sel->tags[i];
1687 for(j = 0; j < LENGTH(tags) && !sel->tags[j]; j++);
1688 if(j == LENGTH(tags))
1689 sel->tags[i] = True; /* at least one tag must be enabled */
1694 toggleview(const char *arg) {
1698 seltags[i] = !seltags[i];
1699 for(j = 0; j < LENGTH(tags) && !seltags[j]; j++);
1700 if(j == LENGTH(tags))
1701 seltags[i] = True; /* at least one tag must be viewed */
1709 XMoveWindow(dpy, c->win, c->x, c->y);
1710 c->isbanned = False;
1714 unmanage(Client *c) {
1717 wc.border_width = c->oldborder;
1718 /* The server grab construct avoids race conditions. */
1720 XSetErrorHandler(xerrordummy);
1721 XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
1726 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1727 setclientstate(c, WithdrawnState);
1731 XSetErrorHandler(xerror);
1737 unmapnotify(XEvent *e) {
1739 XUnmapEvent *ev = &e->xunmap;
1741 if((c = getclient(ev->window)))
1746 updatesizehints(Client *c) {
1750 if(!XGetWMNormalHints(dpy, c->win, &size, &msize) || !size.flags)
1752 c->flags = size.flags;
1753 if(c->flags & PBaseSize) {
1754 c->basew = size.base_width;
1755 c->baseh = size.base_height;
1757 else if(c->flags & PMinSize) {
1758 c->basew = size.min_width;
1759 c->baseh = size.min_height;
1762 c->basew = c->baseh = 0;
1763 if(c->flags & PResizeInc) {
1764 c->incw = size.width_inc;
1765 c->inch = size.height_inc;
1768 c->incw = c->inch = 0;
1769 if(c->flags & PMaxSize) {
1770 c->maxw = size.max_width;
1771 c->maxh = size.max_height;
1774 c->maxw = c->maxh = 0;
1775 if(c->flags & PMinSize) {
1776 c->minw = size.min_width;
1777 c->minh = size.min_height;
1779 else if(c->flags & PBaseSize) {
1780 c->minw = size.base_width;
1781 c->minh = size.base_height;
1784 c->minw = c->minh = 0;
1785 if(c->flags & PAspect) {
1786 c->minax = size.min_aspect.x;
1787 c->maxax = size.max_aspect.x;
1788 c->minay = size.min_aspect.y;
1789 c->maxay = size.max_aspect.y;
1792 c->minax = c->maxax = c->minay = c->maxay = 0;
1793 c->isfixed = (c->maxw && c->minw && c->maxh && c->minh
1794 && c->maxw == c->minw && c->maxh == c->minh);
1798 updatetitle(Client *c) {
1799 if(!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
1800 gettextprop(c->win, wmatom[WMName], c->name, sizeof c->name);
1804 updatewmhints(Client *c) {
1807 if((wmh = XGetWMHints(dpy, c->win))) {
1809 sel->isurgent = False;
1811 c->isurgent = (wmh->flags & XUrgencyHint) ? True : False;
1818 view(const char *arg) {
1821 for(i = 0; i < LENGTH(tags); i++)
1822 tmp[i] = (NULL == arg);
1823 tmp[idxoftag(arg)] = True;
1825 if(memcmp(seltags, tmp, TAGSZ) != 0) {
1826 memcpy(prevtags, seltags, TAGSZ);
1827 memcpy(seltags, tmp, TAGSZ);
1833 viewprevtag(const char *arg) {
1835 memcpy(tmp, seltags, TAGSZ);
1836 memcpy(seltags, prevtags, TAGSZ);
1837 memcpy(prevtags, tmp, TAGSZ);
1841 /* There's no way to check accesses to destroyed windows, thus those cases are
1842 * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
1843 * default error handler, which may call exit. */
1845 xerror(Display *dpy, XErrorEvent *ee) {
1846 if(ee->error_code == BadWindow
1847 || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1848 || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1849 || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1850 || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1851 || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1852 || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1853 || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1855 fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1856 ee->request_code, ee->error_code);
1857 return xerrorxlib(dpy, ee); /* may call exit */
1861 xerrordummy(Display *dpy, XErrorEvent *ee) {
1865 /* Startup Error handler to check if another window manager
1866 * is already running. */
1868 xerrorstart(Display *dpy, XErrorEvent *ee) {
1874 zoom(const char *arg) {
1877 if(!sel || lt->isfloating || sel->isfloating)
1879 if(c == nexttiled(clients))
1880 if(!(c = nexttiled(c->next)))
1889 main(int argc, char *argv[]) {
1890 if(argc == 2 && !strcmp("-v", argv[1]))
1891 eprint("dwm-"VERSION", © 2006-2008 dwm engineers, see LICENSE for details\n");
1893 eprint("usage: dwm [-v]\n");
1895 setlocale(LC_CTYPE, "");
1896 if(!(dpy = XOpenDisplay(0)))
1897 eprint("dwm: cannot open display\n");