4 /* See LICENSE file for copyright and license details.
6 * dynamic window manager is designed like any other X client as well. It is
7 * driven through handling X events. In contrast to other X clients, a window
8 * manager selects for SubstructureRedirectMask on the root window, to receive
9 * events about window (dis-)appearance. Only one X connection at a time is
10 * allowed to select for this event mask.
12 * Calls to fetch an X event from the event queue are blocking. Due reading
13 * status text from standard input, a select()-driven main loop has been
14 * implemented which selects for reads on the X connection and STDIN_FILENO to
15 * handle all data smoothly. The event handlers of dwm are organized in an
16 * array which is accessed whenever a new event has been fetched. This allows
17 * event dispatching in O(1) time.
19 * Each child of the root window is called a client, except windows which have
20 * set the override_redirect flag. Clients are organized in a global
21 * doubly-linked client list, the focus history is remembered through a global
22 * stack list. Each client contains an array of Bools of the same size as the
23 * global tags array to indicate the tags of a client.
25 * Keys and tagging rules are organized as arrays and defined in config.h.
27 * To understand everything else, start reading main().
36 #include <sys/select.h>
37 #include <sys/types.h>
40 #include <X11/cursorfont.h>
41 #include <X11/keysym.h>
42 #include <X11/Xatom.h>
44 #include <X11/Xproto.h>
45 #include <X11/Xutil.h>
48 #define BUTTONMASK (ButtonPressMask|ButtonReleaseMask)
49 #define CLEANMASK(mask) (mask & ~(numlockmask|LockMask))
50 #define LENGTH(x) (sizeof x / sizeof x[0])
52 #define MOUSEMASK (BUTTONMASK|PointerMotionMask)
55 enum { CurNormal, CurResize, CurMove, CurLast }; /* cursor */
56 enum { ColBorder, ColFG, ColBG, ColLast }; /* color */
57 enum { NetSupported, NetWMName, NetLast }; /* EWMH atoms */
58 enum { WMProtocols, WMDelete, WMName, WMState, WMLast };/* default atoms */
61 typedef struct Client Client;
65 int basew, baseh, incw, inch, maxw, maxh, minw, minh;
66 int minax, maxax, minay, maxay;
68 unsigned int border, oldborder;
69 Bool isbanned, isfixed, isfloating, isurgent;
79 unsigned long norm[ColLast];
80 unsigned long sel[ColLast];
90 } DC; /* draw context */
95 void (*func)(const char *arg);
101 void (*arrange)(void);
111 /* function declarations */
112 void applyrules(Client *c);
114 void attach(Client *c);
115 void attachstack(Client *c);
117 void buttonpress(XEvent *e);
118 void checkotherwm(void);
120 void configure(Client *c);
121 void configurenotify(XEvent *e);
122 void configurerequest(XEvent *e);
123 void destroynotify(XEvent *e);
124 void detach(Client *c);
125 void detachstack(Client *c);
127 void drawsquare(Bool filled, Bool empty, Bool invert, unsigned long col[ColLast]);
128 void drawtext(const char *text, unsigned long col[ColLast], Bool invert);
129 void *emallocz(unsigned int size);
130 void enternotify(XEvent *e);
131 void eprint(const char *errstr, ...);
132 void expose(XEvent *e);
133 void floating(void); /* default floating layout */
134 void focus(Client *c);
135 void focusin(XEvent *e);
136 void focusnext(const char *arg);
137 void focusprev(const char *arg);
138 Client *getclient(Window w);
139 unsigned long getcolor(const char *colstr);
140 long getstate(Window w);
141 Bool gettextprop(Window w, Atom atom, char *text, unsigned int size);
142 void grabbuttons(Client *c, Bool focused);
144 unsigned int idxoftag(const char *t);
145 void initfont(const char *fontstr);
146 Bool isoccupied(unsigned int t);
147 Bool isprotodel(Client *c);
148 Bool isurgent(unsigned int t);
149 Bool isvisible(Client *c);
150 void keypress(XEvent *e);
151 void killclient(const char *arg);
152 void manage(Window w, XWindowAttributes *wa);
153 void mappingnotify(XEvent *e);
154 void maprequest(XEvent *e);
156 void movemouse(Client *c);
157 Client *nexttiled(Client *c);
158 void propertynotify(XEvent *e);
159 void quit(const char *arg);
160 void reapply(const char *arg);
161 void resize(Client *c, int x, int y, int w, int h, Bool sizehints);
162 void resizemouse(Client *c);
166 void setclientstate(Client *c, long state);
167 void setlayout(const char *arg);
169 void spawn(const char *arg);
170 void tag(const char *arg);
171 unsigned int textnw(const char *text, unsigned int len);
172 unsigned int textw(const char *text);
174 unsigned int tilemaster(void);
175 void tilevstack(unsigned int n);
176 void togglefloating(const char *arg);
177 void toggletag(const char *arg);
178 void toggleview(const char *arg);
179 void unban(Client *c);
180 void unmanage(Client *c);
181 void unmapnotify(XEvent *e);
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 unsigned int bh, blw = 0;
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];
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)) {
411 XFreePixmap(dpy, dc.drawable);
412 dc.drawable = XCreatePixmap(dpy, root, BW, bh, DefaultDepth(dpy, screen));
413 XMoveResizeWindow(dpy, barwin, BX, BY, BW, bh);
419 configurerequest(XEvent *e) {
421 XConfigureRequestEvent *ev = &e->xconfigurerequest;
424 if((c = getclient(ev->window))) {
425 if(ev->value_mask & CWBorderWidth)
426 c->border = ev->border_width;
427 if(c->isfixed || c->isfloating || lt->isfloating) {
428 if(ev->value_mask & CWX)
430 if(ev->value_mask & CWY)
432 if(ev->value_mask & CWWidth)
434 if(ev->value_mask & CWHeight)
436 if((c->x - sx + c->w) > sw && c->isfloating)
437 c->x = sx + (sw / 2 - c->w / 2); /* center in x direction */
438 if((c->y - sy + c->h) > sh && c->isfloating)
439 c->y = sy + (sh / 2 - c->h / 2); /* center in y direction */
440 if((ev->value_mask & (CWX|CWY))
441 && !(ev->value_mask & (CWWidth|CWHeight)))
444 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h);
452 wc.width = ev->width;
453 wc.height = ev->height;
454 wc.border_width = ev->border_width;
455 wc.sibling = ev->above;
456 wc.stack_mode = ev->detail;
457 XConfigureWindow(dpy, ev->window, ev->value_mask, &wc);
463 destroynotify(XEvent *e) {
465 XDestroyWindowEvent *ev = &e->xdestroywindow;
467 if((c = getclient(ev->window)))
474 c->prev->next = c->next;
476 c->next->prev = c->prev;
479 c->next = c->prev = NULL;
483 detachstack(Client *c) {
486 for(tc=&stack; *tc && *tc != c; tc=&(*tc)->snext);
496 for(c = stack; c && !isvisible(c); c = c->snext);
497 for(i = 0; i < LENGTH(tags); i++) {
498 dc.w = textw(tags[i]);
500 drawtext(tags[i], dc.sel, isurgent(i));
501 drawsquare(c && c->tags[i], isoccupied(i), isurgent(i), dc.sel);
504 drawtext(tags[i], dc.norm, isurgent(i));
505 drawsquare(c && c->tags[i], isoccupied(i), isurgent(i), dc.norm);
510 drawtext(lt->symbol, dc.norm, False);
518 drawtext(stext, dc.norm, False);
519 if((dc.w = dc.x - x) > bh) {
522 drawtext(c->name, dc.sel, False);
523 drawsquare(False, c->isfloating, False, dc.sel);
526 drawtext(NULL, dc.norm, False);
528 XCopyArea(dpy, dc.drawable, barwin, dc.gc, 0, 0, BW, bh, 0, 0);
533 drawsquare(Bool filled, Bool empty, Bool invert, unsigned long col[ColLast]) {
536 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
538 gcv.foreground = col[invert ? ColBG : ColFG];
539 XChangeGC(dpy, dc.gc, GCForeground, &gcv);
540 x = (dc.font.ascent + dc.font.descent + 2) / 4;
544 r.width = r.height = x + 1;
545 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
548 r.width = r.height = x;
549 XDrawRectangles(dpy, dc.drawable, dc.gc, &r, 1);
554 drawtext(const char *text, unsigned long col[ColLast], Bool invert) {
556 unsigned int len, olen;
557 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
559 XSetForeground(dpy, dc.gc, col[invert ? ColFG : ColBG]);
560 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
564 olen = len = strlen(text);
565 if(len >= sizeof buf)
566 len = sizeof buf - 1;
567 memcpy(buf, text, len);
569 h = dc.font.ascent + dc.font.descent;
570 y = dc.y + (dc.h / 2) - (h / 2) + dc.font.ascent;
572 /* shorten text if necessary */
573 while(len && (w = textnw(buf, len)) > dc.w - h)
584 return; /* too long */
585 XSetForeground(dpy, dc.gc, col[invert ? ColBG : ColFG]);
587 XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
589 XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
593 emallocz(unsigned int size) {
594 void *res = calloc(1, size);
597 eprint("fatal: could not malloc() %u bytes\n", size);
602 enternotify(XEvent *e) {
604 XCrossingEvent *ev = &e->xcrossing;
606 if((ev->mode != NotifyNormal || ev->detail == NotifyInferior) && ev->window != root)
608 if((c = getclient(ev->window)))
615 eprint(const char *errstr, ...) {
618 va_start(ap, errstr);
619 vfprintf(stderr, errstr, ap);
626 XExposeEvent *ev = &e->xexpose;
628 if(ev->count == 0 && (ev->window == barwin))
633 floating(void) { /* default floating layout */
636 for(c = clients; c; c = c->next)
638 resize(c, c->x, c->y, c->w, c->h, True);
643 if(!c || (c && !isvisible(c)))
644 for(c = stack; c && !isvisible(c); c = c->snext);
645 if(sel && sel != c) {
646 grabbuttons(sel, False);
647 XSetWindowBorder(dpy, sel->win, dc.norm[ColBorder]);
652 grabbuttons(c, True);
656 XSetWindowBorder(dpy, c->win, dc.sel[ColBorder]);
657 XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
660 XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
665 focusin(XEvent *e) { /* there are some broken focus acquiring clients */
666 XFocusChangeEvent *ev = &e->xfocus;
668 if(sel && ev->window != sel->win)
669 XSetInputFocus(dpy, sel->win, RevertToPointerRoot, CurrentTime);
673 focusnext(const char *arg) {
678 for(c = sel->next; c && !isvisible(c); c = c->next);
680 for(c = clients; c && !isvisible(c); c = c->next);
688 focusprev(const char *arg) {
693 for(c = sel->prev; c && !isvisible(c); c = c->prev);
695 for(c = clients; c && c->next; c = c->next);
696 for(; c && !isvisible(c); c = c->prev);
705 getclient(Window w) {
708 for(c = clients; c && c->win != w; c = c->next);
713 getcolor(const char *colstr) {
714 Colormap cmap = DefaultColormap(dpy, screen);
717 if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
718 eprint("error, cannot allocate color '%s'\n", colstr);
726 unsigned char *p = NULL;
727 unsigned long n, extra;
730 status = XGetWindowProperty(dpy, w, wmatom[WMState], 0L, 2L, False, wmatom[WMState],
731 &real, &format, &n, &extra, (unsigned char **)&p);
732 if(status != Success)
741 gettextprop(Window w, Atom atom, char *text, unsigned int size) {
746 if(!text || size == 0)
749 XGetTextProperty(dpy, w, &name, atom);
752 if(name.encoding == XA_STRING)
753 strncpy(text, (char *)name.value, size - 1);
755 if(XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success
757 strncpy(text, *list, size - 1);
758 XFreeStringList(list);
761 text[size - 1] = '\0';
767 grabbuttons(Client *c, Bool focused) {
768 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
771 XGrabButton(dpy, Button1, MODKEY, c->win, False, BUTTONMASK,
772 GrabModeAsync, GrabModeSync, None, None);
773 XGrabButton(dpy, Button1, MODKEY|LockMask, c->win, False, BUTTONMASK,
774 GrabModeAsync, GrabModeSync, None, None);
775 XGrabButton(dpy, Button1, MODKEY|numlockmask, c->win, False, BUTTONMASK,
776 GrabModeAsync, GrabModeSync, None, None);
777 XGrabButton(dpy, Button1, MODKEY|numlockmask|LockMask, c->win, False, BUTTONMASK,
778 GrabModeAsync, GrabModeSync, None, None);
780 XGrabButton(dpy, Button2, MODKEY, c->win, False, BUTTONMASK,
781 GrabModeAsync, GrabModeSync, None, None);
782 XGrabButton(dpy, Button2, MODKEY|LockMask, c->win, False, BUTTONMASK,
783 GrabModeAsync, GrabModeSync, None, None);
784 XGrabButton(dpy, Button2, MODKEY|numlockmask, c->win, False, BUTTONMASK,
785 GrabModeAsync, GrabModeSync, None, None);
786 XGrabButton(dpy, Button2, MODKEY|numlockmask|LockMask, c->win, False, BUTTONMASK,
787 GrabModeAsync, GrabModeSync, None, None);
789 XGrabButton(dpy, Button3, MODKEY, c->win, False, BUTTONMASK,
790 GrabModeAsync, GrabModeSync, None, None);
791 XGrabButton(dpy, Button3, MODKEY|LockMask, c->win, False, BUTTONMASK,
792 GrabModeAsync, GrabModeSync, None, None);
793 XGrabButton(dpy, Button3, MODKEY|numlockmask, c->win, False, BUTTONMASK,
794 GrabModeAsync, GrabModeSync, None, None);
795 XGrabButton(dpy, Button3, MODKEY|numlockmask|LockMask, c->win, False, BUTTONMASK,
796 GrabModeAsync, GrabModeSync, None, None);
799 XGrabButton(dpy, AnyButton, AnyModifier, c->win, False, BUTTONMASK,
800 GrabModeAsync, GrabModeSync, None, None);
807 XModifierKeymap *modmap;
809 /* init modifier map */
810 modmap = XGetModifierMapping(dpy);
811 for(i = 0; i < 8; i++)
812 for(j = 0; j < modmap->max_keypermod; j++) {
813 if(modmap->modifiermap[i * modmap->max_keypermod + j] == XKeysymToKeycode(dpy, XK_Num_Lock))
814 numlockmask = (1 << i);
816 XFreeModifiermap(modmap);
818 XUngrabKey(dpy, AnyKey, AnyModifier, root);
819 for(i = 0; i < LENGTH(keys); i++) {
820 code = XKeysymToKeycode(dpy, keys[i].keysym);
821 XGrabKey(dpy, code, keys[i].mod, root, True,
822 GrabModeAsync, GrabModeAsync);
823 XGrabKey(dpy, code, keys[i].mod|LockMask, root, True,
824 GrabModeAsync, GrabModeAsync);
825 XGrabKey(dpy, code, keys[i].mod|numlockmask, root, True,
826 GrabModeAsync, GrabModeAsync);
827 XGrabKey(dpy, code, keys[i].mod|numlockmask|LockMask, root, True,
828 GrabModeAsync, GrabModeAsync);
833 idxoftag(const char *t) {
836 for(i = 0; (i < LENGTH(tags)) && (tags[i] != t); i++);
837 return (i < LENGTH(tags)) ? i : 0;
841 initfont(const char *fontstr) {
842 char *def, **missing;
847 XFreeFontSet(dpy, dc.font.set);
848 dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
851 fprintf(stderr, "dwm: missing fontset: %s\n", missing[n]);
852 XFreeStringList(missing);
855 XFontSetExtents *font_extents;
856 XFontStruct **xfonts;
858 dc.font.ascent = dc.font.descent = 0;
859 font_extents = XExtentsOfFontSet(dc.font.set);
860 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
861 for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
862 if(dc.font.ascent < (*xfonts)->ascent)
863 dc.font.ascent = (*xfonts)->ascent;
864 if(dc.font.descent < (*xfonts)->descent)
865 dc.font.descent = (*xfonts)->descent;
871 XFreeFont(dpy, dc.font.xfont);
872 dc.font.xfont = NULL;
873 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr))
874 && !(dc.font.xfont = XLoadQueryFont(dpy, "fixed")))
875 eprint("error, cannot load font: '%s'\n", fontstr);
876 dc.font.ascent = dc.font.xfont->ascent;
877 dc.font.descent = dc.font.xfont->descent;
879 dc.font.height = dc.font.ascent + dc.font.descent;
883 isoccupied(unsigned int t) {
886 for(c = clients; c; c = c->next)
893 isprotodel(Client *c) {
898 if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
899 for(i = 0; !ret && i < n; i++)
900 if(protocols[i] == wmatom[WMDelete])
908 isurgent(unsigned int t) {
911 for(c = clients; c; c = c->next)
912 if(c->isurgent && c->tags[t])
918 isvisible(Client *c) {
921 for(i = 0; i < LENGTH(tags); i++)
922 if(c->tags[i] && seltags[i])
928 keypress(XEvent *e) {
934 keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
935 for(i = 0; i < LENGTH(keys); i++)
936 if(keysym == keys[i].keysym
937 && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state))
940 keys[i].func(keys[i].arg);
945 killclient(const char *arg) {
950 if(isprotodel(sel)) {
951 ev.type = ClientMessage;
952 ev.xclient.window = sel->win;
953 ev.xclient.message_type = wmatom[WMProtocols];
954 ev.xclient.format = 32;
955 ev.xclient.data.l[0] = wmatom[WMDelete];
956 ev.xclient.data.l[1] = CurrentTime;
957 XSendEvent(dpy, sel->win, False, NoEventMask, &ev);
960 XKillClient(dpy, sel->win);
964 manage(Window w, XWindowAttributes *wa) {
965 Client *c, *t = NULL;
970 c = emallocz(sizeof(Client));
971 c->tags = emallocz(TAGSZ);
979 c->oldborder = wa->border_width;
980 if(c->w == sw && c->h == sh) {
983 c->border = wa->border_width;
986 if(c->x + c->w + 2 * c->border > WX + WW)
987 c->x = WX + WW - c->w - 2 * c->border;
988 if(c->y + c->h + 2 * c->border > WY + WH)
989 c->y = WY + WH - c->h - 2 * c->border;
994 c->border = BORDERPX;
997 wc.border_width = c->border;
998 XConfigureWindow(dpy, w, CWBorderWidth, &wc);
999 XSetWindowBorder(dpy, w, dc.norm[ColBorder]);
1000 configure(c); /* propagates border_width, if size doesn't change */
1002 XSelectInput(dpy, w, EnterWindowMask|FocusChangeMask|PropertyChangeMask|StructureNotifyMask);
1003 grabbuttons(c, False);
1005 if((rettrans = XGetTransientForHint(dpy, w, &trans) == Success))
1006 for(t = clients; t && t->win != trans; t = t->next);
1008 memcpy(c->tags, t->tags, TAGSZ);
1012 c->isfloating = (rettrans == Success) || c->isfixed;
1015 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h); /* some windows require this */
1017 XMapWindow(dpy, c->win);
1018 setclientstate(c, NormalState);
1023 mappingnotify(XEvent *e) {
1024 XMappingEvent *ev = &e->xmapping;
1026 XRefreshKeyboardMapping(ev);
1027 if(ev->request == MappingKeyboard)
1032 maprequest(XEvent *e) {
1033 static XWindowAttributes wa;
1034 XMapRequestEvent *ev = &e->xmaprequest;
1036 if(!XGetWindowAttributes(dpy, ev->window, &wa))
1038 if(wa.override_redirect)
1040 if(!getclient(ev->window))
1041 manage(ev->window, &wa);
1048 for(c = clients; c; c = c->next)
1050 resize(c, MOX, MOY, MOW, MOH, RESIZEHINTS);
1054 movemouse(Client *c) {
1055 int x1, y1, ocx, ocy, di, nx, ny;
1062 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1063 None, cursor[CurMove], CurrentTime) != GrabSuccess)
1065 XQueryPointer(dpy, root, &dummy, &dummy, &x1, &y1, &di, &di, &dui);
1067 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
1070 XUngrabPointer(dpy, CurrentTime);
1072 case ConfigureRequest:
1075 handler[ev.type](&ev);
1079 nx = ocx + (ev.xmotion.x - x1);
1080 ny = ocy + (ev.xmotion.y - y1);
1081 if(abs(WX - nx) < SNAP)
1083 else if(abs((WX + WW) - (nx + c->w + 2 * c->border)) < SNAP)
1084 nx = WX + WW - c->w - 2 * c->border;
1085 if(abs(WY - ny) < SNAP)
1087 else if(abs((WY + WH) - (ny + c->h + 2 * c->border)) < SNAP)
1088 ny = WY + WH - c->h - 2 * c->border;
1089 if(!c->isfloating && !lt->isfloating && (abs(nx - c->x) > SNAP || abs(ny - c->y) > SNAP))
1090 togglefloating(NULL);
1091 if((lt->isfloating) || c->isfloating)
1092 resize(c, nx, ny, c->w, c->h, False);
1099 nexttiled(Client *c) {
1100 for(; c && (c->isfloating || !isvisible(c)); c = c->next);
1105 propertynotify(XEvent *e) {
1108 XPropertyEvent *ev = &e->xproperty;
1110 if(ev->state == PropertyDelete)
1111 return; /* ignore */
1112 if((c = getclient(ev->window))) {
1115 case XA_WM_TRANSIENT_FOR:
1116 XGetTransientForHint(dpy, c->win, &trans);
1117 if(!c->isfloating && (c->isfloating = (getclient(trans) != NULL)))
1120 case XA_WM_NORMAL_HINTS:
1128 if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
1137 quit(const char *arg) {
1138 readin = running = False;
1142 reapply(const char *arg) {
1143 static Bool zerotags[LENGTH(tags)] = { 0 };
1146 for(c = clients; c; c = c->next) {
1147 memcpy(c->tags, zerotags, sizeof zerotags);
1154 resize(Client *c, int x, int y, int w, int h, Bool sizehints) {
1158 /* set minimum possible */
1164 /* temporarily remove base dimensions */
1168 /* adjust for aspect limits */
1169 if (c->minay > 0 && c->maxay > 0 && c->minax > 0 && c->maxax > 0) {
1170 if (w * c->maxay > h * c->maxax)
1171 w = h * c->maxax / c->maxay;
1172 else if (w * c->minay < h * c->minax)
1173 h = w * c->minay / c->minax;
1176 /* adjust for increment value */
1182 /* restore base dimensions */
1186 if(c->minw > 0 && w < c->minw)
1188 if(c->minh > 0 && h < c->minh)
1190 if(c->maxw > 0 && w > c->maxw)
1192 if(c->maxh > 0 && h > c->maxh)
1195 if(w <= 0 || h <= 0)
1198 x = sw - w - 2 * c->border;
1200 y = sh - h - 2 * c->border;
1201 if(x + w + 2 * c->border < sx)
1203 if(y + h + 2 * c->border < sy)
1205 if(c->x != x || c->y != y || c->w != w || c->h != h) {
1208 c->w = wc.width = w;
1209 c->h = wc.height = h;
1210 wc.border_width = c->border;
1211 XConfigureWindow(dpy, c->win,
1212 CWX|CWY|CWWidth|CWHeight|CWBorderWidth, &wc);
1219 resizemouse(Client *c) {
1226 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1227 None, cursor[CurResize], CurrentTime) != GrabSuccess)
1229 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->border - 1, c->h + c->border - 1);
1231 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask , &ev);
1234 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0,
1235 c->w + c->border - 1, c->h + c->border - 1);
1236 XUngrabPointer(dpy, CurrentTime);
1237 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1239 case ConfigureRequest:
1242 handler[ev.type](&ev);
1246 if((nw = ev.xmotion.x - ocx - 2 * c->border + 1) <= 0)
1248 if((nh = ev.xmotion.y - ocy - 2 * c->border + 1) <= 0)
1250 if(!c->isfloating && !lt->isfloating && (abs(nw - c->w) > SNAP || abs(nh - c->h) > SNAP))
1251 togglefloating(NULL);
1252 if((lt->isfloating) || c->isfloating)
1253 resize(c, c->x, c->y, nw, nh, True);
1268 if(sel->isfloating || lt->isfloating)
1269 XRaiseWindow(dpy, sel->win);
1270 if(!lt->isfloating) {
1271 wc.stack_mode = Below;
1272 wc.sibling = barwin;
1273 if(!sel->isfloating) {
1274 XConfigureWindow(dpy, sel->win, CWSibling|CWStackMode, &wc);
1275 wc.sibling = sel->win;
1277 for(c = nexttiled(clients); c; c = nexttiled(c->next)) {
1280 XConfigureWindow(dpy, c->win, CWSibling|CWStackMode, &wc);
1281 wc.sibling = c->win;
1285 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1291 char sbuf[sizeof stext];
1294 unsigned int len, offset;
1297 /* main event loop, also reads status text from stdin */
1299 xfd = ConnectionNumber(dpy);
1302 len = sizeof stext - 1;
1303 sbuf[len] = stext[len] = '\0'; /* 0-terminator is never touched */
1307 FD_SET(STDIN_FILENO, &rd);
1309 if(select(xfd + 1, &rd, NULL, NULL, NULL) == -1) {
1312 eprint("select failed\n");
1314 if(FD_ISSET(STDIN_FILENO, &rd)) {
1315 switch((r = read(STDIN_FILENO, sbuf + offset, len - offset))) {
1317 strncpy(stext, strerror(errno), len);
1321 strncpy(stext, "EOF", 4);
1325 for(p = sbuf + offset; r > 0; p++, r--, offset++)
1326 if(*p == '\n' || *p == '\0') {
1328 strncpy(stext, sbuf, len);
1329 p += r - 1; /* p is sbuf + offset + r - 1 */
1330 for(r = 0; *(p - r) && *(p - r) != '\n'; r++);
1333 memmove(sbuf, p - r + 1, r);
1340 while(XPending(dpy)) {
1341 XNextEvent(dpy, &ev);
1342 if(handler[ev.type])
1343 (handler[ev.type])(&ev); /* call handler */
1350 unsigned int i, num;
1351 Window *wins, d1, d2;
1352 XWindowAttributes wa;
1355 if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1356 for(i = 0; i < num; i++) {
1357 if(!XGetWindowAttributes(dpy, wins[i], &wa)
1358 || wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1360 if(wa.map_state == IsViewable || getstate(wins[i]) == IconicState)
1361 manage(wins[i], &wa);
1363 for(i = 0; i < num; i++) { /* now the transients */
1364 if(!XGetWindowAttributes(dpy, wins[i], &wa))
1366 if(XGetTransientForHint(dpy, wins[i], &d1)
1367 && (wa.map_state == IsViewable || getstate(wins[i]) == IconicState))
1368 manage(wins[i], &wa);
1376 setclientstate(Client *c, long state) {
1377 long data[] = {state, None};
1379 XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1380 PropModeReplace, (unsigned char *)data, 2);
1384 setlayout(const char *arg) {
1385 static Layout *revert = 0;
1390 for(i = 0; i < LENGTH(layouts); i++)
1391 if(!strcmp(arg, layouts[i].symbol))
1393 if(i == LENGTH(layouts))
1395 if(revert && &layouts[i] == lt)
1410 XSetWindowAttributes wa;
1413 screen = DefaultScreen(dpy);
1414 root = RootWindow(dpy, screen);
1417 sw = DisplayWidth(dpy, screen);
1418 sh = DisplayHeight(dpy, screen);
1421 wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1422 wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1423 wmatom[WMName] = XInternAtom(dpy, "WM_NAME", False);
1424 wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1425 netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1426 netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1429 wa.cursor = cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1430 cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1431 cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1433 /* init appearance */
1434 dc.norm[ColBorder] = getcolor(NORMBORDERCOLOR);
1435 dc.norm[ColBG] = getcolor(NORMBGCOLOR);
1436 dc.norm[ColFG] = getcolor(NORMFGCOLOR);
1437 dc.sel[ColBorder] = getcolor(SELBORDERCOLOR);
1438 dc.sel[ColBG] = getcolor(SELBGCOLOR);
1439 dc.sel[ColFG] = getcolor(SELFGCOLOR);
1441 dc.h = bh = dc.font.height + 2;
1442 dc.drawable = XCreatePixmap(dpy, root, DisplayWidth(dpy, screen), bh, DefaultDepth(dpy, screen));
1443 dc.gc = XCreateGC(dpy, root, 0, 0);
1444 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
1446 XSetFont(dpy, dc.gc, dc.font.xfont->fid);
1449 seltags = emallocz(TAGSZ);
1450 prevtags = emallocz(TAGSZ);
1451 seltags[0] = prevtags[0] = True;
1457 for(blw = i = 0; i < LENGTH(layouts); i++) {
1458 i = textw(layouts[i].symbol);
1463 wa.override_redirect = 1;
1464 wa.background_pixmap = ParentRelative;
1465 wa.event_mask = ButtonPressMask|ExposureMask;
1467 barwin = XCreateWindow(dpy, root, BX, BY, BW, bh, 0, DefaultDepth(dpy, screen),
1468 CopyFromParent, DefaultVisual(dpy, screen),
1469 CWOverrideRedirect|CWBackPixmap|CWEventMask, &wa);
1470 XDefineCursor(dpy, barwin, cursor[CurNormal]);
1471 XMapRaised(dpy, barwin);
1472 strcpy(stext, "dwm-"VERSION);
1475 /* EWMH support per view */
1476 XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1477 PropModeReplace, (unsigned char *) netatom, NetLast);
1479 /* select for events */
1480 wa.event_mask = SubstructureRedirectMask|SubstructureNotifyMask
1481 |EnterWindowMask|LeaveWindowMask|StructureNotifyMask;
1482 XChangeWindowAttributes(dpy, root, CWEventMask|CWCursor, &wa);
1483 XSelectInput(dpy, root, wa.event_mask);
1491 spawn(const char *arg) {
1492 static char *shell = NULL;
1494 if(!shell && !(shell = getenv("SHELL")))
1498 /* The double-fork construct avoids zombie processes and keeps the code
1499 * clean from stupid signal handlers. */
1503 close(ConnectionNumber(dpy));
1505 execl(shell, shell, "-c", arg, (char *)NULL);
1506 fprintf(stderr, "dwm: execl '%s -c %s'", shell, arg);
1515 tag(const char *arg) {
1520 for(i = 0; i < LENGTH(tags); i++)
1521 sel->tags[i] = (NULL == arg);
1522 sel->tags[idxoftag(arg)] = True;
1527 textnw(const char *text, unsigned int len) {
1531 XmbTextExtents(dc.font.set, text, len, NULL, &r);
1534 return XTextWidth(dc.font.xfont, text, len);
1538 textw(const char *text) {
1539 return textnw(text, strlen(text)) + dc.font.height;
1543 tileresize(Client *c, int x, int y, int w, int h) {
1544 resize(c, x, y, w, h, RESIZEHINTS);
1545 if((RESIZEHINTS) && ((c->h < bh) || (c->h > h) || (c->w < bh) || (c->w > w)))
1546 /* client doesn't accept size constraints */
1547 resize(c, x, y, w, h, False);
1555 for(n = 0, mc = c = nexttiled(clients); c; c = nexttiled(c->next))
1560 tileresize(mc, MOX, MOY, (MOW) - 2 * mc->border, (MOH) - 2 * mc->border);
1562 tileresize(mc, MX, MY, (MW) - 2 * mc->border, (MH) - 2 * mc->border);
1567 tilevstack(unsigned int n) {
1579 for(i = 0, c = nexttiled(clients); c; c = nexttiled(c->next), i++)
1581 if(i > 1 && i == n) /* remainder */
1582 tileresize(c, TX, y, (TW) - 2 * c->border,
1583 ((TY) + (TH)) - y - 2 * c->border);
1585 tileresize(c, TX, y, (TW) - 2 * c->border,
1588 y = c->y + c->h + 2 * c->border;
1594 tilevstack(tilemaster());
1598 togglefloating(const char *arg) {
1601 sel->isfloating = !sel->isfloating;
1603 resize(sel, sel->x, sel->y, sel->w, sel->h, True);
1608 toggletag(const char *arg) {
1614 sel->tags[i] = !sel->tags[i];
1615 for(j = 0; j < LENGTH(tags) && !sel->tags[j]; j++);
1616 if(j == LENGTH(tags))
1617 sel->tags[i] = True; /* at least one tag must be enabled */
1622 toggleview(const char *arg) {
1626 seltags[i] = !seltags[i];
1627 for(j = 0; j < LENGTH(tags) && !seltags[j]; j++);
1628 if(j == LENGTH(tags))
1629 seltags[i] = True; /* at least one tag must be viewed */
1637 XMoveWindow(dpy, c->win, c->x, c->y);
1638 c->isbanned = False;
1642 unmanage(Client *c) {
1645 wc.border_width = c->oldborder;
1646 /* The server grab construct avoids race conditions. */
1648 XSetErrorHandler(xerrordummy);
1649 XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
1654 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1655 setclientstate(c, WithdrawnState);
1659 XSetErrorHandler(xerror);
1665 unmapnotify(XEvent *e) {
1667 XUnmapEvent *ev = &e->xunmap;
1669 if((c = getclient(ev->window)))
1674 updatesizehints(Client *c) {
1678 if(!XGetWMNormalHints(dpy, c->win, &size, &msize) || !size.flags)
1680 c->flags = size.flags;
1681 if(c->flags & PBaseSize) {
1682 c->basew = size.base_width;
1683 c->baseh = size.base_height;
1685 else if(c->flags & PMinSize) {
1686 c->basew = size.min_width;
1687 c->baseh = size.min_height;
1690 c->basew = c->baseh = 0;
1691 if(c->flags & PResizeInc) {
1692 c->incw = size.width_inc;
1693 c->inch = size.height_inc;
1696 c->incw = c->inch = 0;
1697 if(c->flags & PMaxSize) {
1698 c->maxw = size.max_width;
1699 c->maxh = size.max_height;
1702 c->maxw = c->maxh = 0;
1703 if(c->flags & PMinSize) {
1704 c->minw = size.min_width;
1705 c->minh = size.min_height;
1707 else if(c->flags & PBaseSize) {
1708 c->minw = size.base_width;
1709 c->minh = size.base_height;
1712 c->minw = c->minh = 0;
1713 if(c->flags & PAspect) {
1714 c->minax = size.min_aspect.x;
1715 c->maxax = size.max_aspect.x;
1716 c->minay = size.min_aspect.y;
1717 c->maxay = size.max_aspect.y;
1720 c->minax = c->maxax = c->minay = c->maxay = 0;
1721 c->isfixed = (c->maxw && c->minw && c->maxh && c->minh
1722 && c->maxw == c->minw && c->maxh == c->minh);
1726 updatetitle(Client *c) {
1727 if(!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
1728 gettextprop(c->win, wmatom[WMName], c->name, sizeof c->name);
1732 updatewmhints(Client *c) {
1735 if((wmh = XGetWMHints(dpy, c->win))) {
1737 sel->isurgent = False;
1739 c->isurgent = (wmh->flags & XUrgencyHint) ? True : False;
1746 view(const char *arg) {
1749 for(i = 0; i < LENGTH(tags); i++)
1750 tmp[i] = (NULL == arg);
1751 tmp[idxoftag(arg)] = True;
1753 if(memcmp(seltags, tmp, TAGSZ) != 0) {
1754 memcpy(prevtags, seltags, TAGSZ);
1755 memcpy(seltags, tmp, TAGSZ);
1761 viewprevtag(const char *arg) {
1763 memcpy(tmp, seltags, TAGSZ);
1764 memcpy(seltags, prevtags, TAGSZ);
1765 memcpy(prevtags, tmp, TAGSZ);
1769 /* There's no way to check accesses to destroyed windows, thus those cases are
1770 * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
1771 * default error handler, which may call exit. */
1773 xerror(Display *dpy, XErrorEvent *ee) {
1774 if(ee->error_code == BadWindow
1775 || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1776 || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1777 || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1778 || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1779 || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1780 || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1781 || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1783 fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1784 ee->request_code, ee->error_code);
1785 return xerrorxlib(dpy, ee); /* may call exit */
1789 xerrordummy(Display *dpy, XErrorEvent *ee) {
1793 /* Startup Error handler to check if another window manager
1794 * is already running. */
1796 xerrorstart(Display *dpy, XErrorEvent *ee) {
1802 zoom(const char *arg) {
1805 if(!sel || lt->isfloating || sel->isfloating)
1807 if(c == nexttiled(clients))
1808 if(!(c = nexttiled(c->next)))
1817 main(int argc, char *argv[]) {
1818 if(argc == 2 && !strcmp("-v", argv[1]))
1819 eprint("dwm-"VERSION", © 2006-2008 dwm engineers, see LICENSE for details\n");
1821 eprint("usage: dwm [-v]\n");
1823 setlocale(LC_CTYPE, "");
1824 if(!(dpy = XOpenDisplay(0)))
1825 eprint("dwm: cannot open display\n");