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. For each client dwm
21 * creates a small title window, which is resized whenever the (_NET_)WM_NAME
22 * properties are updated or the client is moved/resized.
24 * Keys and tagging rules are organized as arrays and defined in config.h.
26 * To understand everything else, start reading main().
37 #include <sys/select.h>
38 #include <sys/types.h>
41 #include <X11/cursorfont.h>
42 #include <X11/keysym.h>
43 #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 MOUSEMASK (BUTTONMASK | PointerMotionMask)
53 enum { BarTop, BarBot, BarOff }; /* bar position */
54 enum { CurNormal, CurResize, CurMove, CurLast }; /* cursor */
55 enum { ColBorder, ColFG, ColBG, ColLast }; /* color */
56 enum { NetSupported, NetWMName, NetLast }; /* EWMH atoms */
57 enum { WMProtocols, WMDelete, WMName, WMState, WMLast };/* default atoms */
62 unsigned long norm[ColLast];
63 unsigned long sel[ColLast];
73 } DC; /* draw context */
78 void (*func)(const char *arg);
84 void (*arrange)(void);
98 /* forward declarations */
99 void applyrules(Client *c);
101 void attach(Client *c);
102 void attachstack(Client *c);
104 void buttonpress(XEvent *e);
105 void checkotherwm(void);
107 void compileregs(void);
108 void configure(Client *c);
109 void configurenotify(XEvent *e);
110 void configurerequest(XEvent *e);
111 void destroynotify(XEvent *e);
112 void detach(Client *c);
113 void detachstack(Client *c);
115 void drawsquare(Bool filled, Bool empty, unsigned long col[ColLast]);
116 void drawtext(const char *text, unsigned long col[ColLast]);
117 void *emallocz(unsigned int size);
118 void enternotify(XEvent *e);
119 void eprint(const char *errstr, ...);
120 void expose(XEvent *e);
121 void floating(void); /* default floating layout */
122 void focus(Client *c);
123 void focusnext(const char *arg);
124 void focusprev(const char *arg);
125 Client *getclient(Window w);
126 unsigned long getcolor(const char *colstr);
127 long getstate(Window w);
128 Bool gettextprop(Window w, Atom atom, char *text, unsigned int size);
129 void grabbuttons(Client *c, Bool focused);
130 unsigned int idxoftag(const char *tag);
131 void initfont(const char *fontstr);
132 Bool isarrange(void (*func)());
133 Bool isoccupied(unsigned int t);
134 Bool isprotodel(Client *c);
135 Bool isvisible(Client *c);
136 void keypress(XEvent *e);
137 void killclient(const char *arg);
138 void leavenotify(XEvent *e);
139 void manage(Window w, XWindowAttributes *wa);
140 void mappingnotify(XEvent *e);
141 void maprequest(XEvent *e);
142 void movemouse(Client *c);
143 Client *nexttiled(Client *c);
144 void propertynotify(XEvent *e);
145 void quit(const char *arg);
146 void resize(Client *c, int x, int y, int w, int h, Bool sizehints);
147 void resizemouse(Client *c);
151 void setclientstate(Client *c, long state);
152 void setlayout(const char *arg);
153 void setmwfact(const char *arg);
155 void spawn(const char *arg);
156 void tag(const char *arg);
157 unsigned int textnw(const char *text, unsigned int len);
158 unsigned int textw(const char *text);
160 void togglebar(const char *arg);
161 void togglefloating(const char *arg);
162 void togglemax(const char *arg);
163 void toggletag(const char *arg);
164 void toggleview(const char *arg);
165 void unban(Client *c);
166 void unmanage(Client *c);
167 void unmapnotify(XEvent *e);
168 void updatebarpos(void);
169 void updatesizehints(Client *c);
170 void updatetitle(Client *c);
171 void view(const char *arg);
172 void viewprevtag(const char *arg); /* views previous selected tags */
173 int xerror(Display *dpy, XErrorEvent *ee);
174 int xerrordummy(Display *dsply, XErrorEvent *ee);
175 int xerrorstart(Display *dsply, XErrorEvent *ee);
176 void zoom(const char *arg);
181 int screen, sx, sy, sw, sh, wax, way, waw, wah;
182 int (*xerrorxlib)(Display *, XErrorEvent *);
183 unsigned int bh, bpos;
184 unsigned int blw = 0;
185 unsigned int ltidx = 0; /* default */
186 unsigned int nlayouts = 0;
187 unsigned int nrules = 0;
188 unsigned int numlockmask = 0;
189 void (*handler[LASTEvent]) (XEvent *) = {
190 [ButtonPress] = buttonpress,
191 [ConfigureRequest] = configurerequest,
192 [ConfigureNotify] = configurenotify,
193 [DestroyNotify] = destroynotify,
194 [EnterNotify] = enternotify,
195 [LeaveNotify] = leavenotify,
197 [KeyPress] = keypress,
198 [MappingNotify] = mappingnotify,
199 [MapRequest] = maprequest,
200 [PropertyNotify] = propertynotify,
201 [UnmapNotify] = unmapnotify
203 Atom wmatom[WMLast], netatom[NetLast];
204 Bool otherwm, readin;
206 Bool selscreen = True;
207 Client *clients = NULL;
209 Client *stack = NULL;
210 Cursor cursor[CurLast];
216 /* configuration, allows nested code to access above variables */
219 /* Statically define the number of tags. */
220 unsigned int ntags = sizeof tags / sizeof tags[0];
221 Bool seltags[sizeof tags / sizeof tags[0]] = {[0] = True};
222 Bool prevtags[sizeof tags / sizeof tags[0]] = {[0] = True};
226 applyrules(Client *c) {
227 static char buf[512];
230 Bool matched = False;
231 XClassHint ch = { 0 };
234 XGetClassHint(dpy, c->win, &ch);
235 snprintf(buf, sizeof buf, "%s:%s:%s",
236 ch.res_class ? ch.res_class : "",
237 ch.res_name ? ch.res_name : "", c->name);
238 for(i = 0; i < nrules; i++)
239 if(regs[i].propregex && !regexec(regs[i].propregex, buf, 1, &tmp, 0)) {
240 c->isfloating = rules[i].isfloating;
241 for(j = 0; regs[i].tagregex && j < ntags; j++) {
242 if(!regexec(regs[i].tagregex, tags[j], 1, &tmp, 0)) {
253 memcpy(c->tags, seltags, sizeof seltags);
260 for(c = clients; c; c = c->next)
265 layouts[ltidx].arrange();
279 attachstack(Client *c) {
288 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
293 buttonpress(XEvent *e) {
296 XButtonPressedEvent *ev = &e->xbutton;
298 if(barwin == ev->window) {
300 for(i = 0; i < ntags; i++) {
303 if(ev->button == Button1) {
304 if(ev->state & MODKEY)
309 else if(ev->button == Button3) {
310 if(ev->state & MODKEY)
318 if((ev->x < x + blw) && ev->button == Button1)
321 else if((c = getclient(ev->window))) {
323 if(CLEANMASK(ev->state) != MODKEY)
325 if(ev->button == Button1) {
326 if(isarrange(floating) || c->isfloating)
329 togglefloating(NULL);
332 else if(ev->button == Button2) {
333 if(ISTILE && !c->isfixed && c->isfloating)
334 togglefloating(NULL);
338 else if(ev->button == Button3 && !c->isfixed) {
339 if(isarrange(floating) || c->isfloating)
342 togglefloating(NULL);
351 XSetErrorHandler(xerrorstart);
353 /* this causes an error if some other window manager is running */
354 XSelectInput(dpy, root, 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 XDestroyWindow(dpy, barwin);
379 XFreeCursor(dpy, cursor[CurNormal]);
380 XFreeCursor(dpy, cursor[CurResize]);
381 XFreeCursor(dpy, cursor[CurMove]);
382 XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime);
393 nrules = sizeof rules / sizeof rules[0];
394 regs = emallocz(nrules * sizeof(Regs));
395 for(i = 0; i < nrules; i++) {
397 reg = emallocz(sizeof(regex_t));
398 if(regcomp(reg, rules[i].prop, REG_EXTENDED))
401 regs[i].propregex = reg;
404 reg = emallocz(sizeof(regex_t));
405 if(regcomp(reg, rules[i].tags, REG_EXTENDED))
408 regs[i].tagregex = reg;
414 configure(Client *c) {
417 ce.type = ConfigureNotify;
425 ce.border_width = c->border;
427 ce.override_redirect = False;
428 XSendEvent(dpy, c->win, False, StructureNotifyMask, (XEvent *)&ce);
432 configurenotify(XEvent *e) {
433 XConfigureEvent *ev = &e->xconfigure;
435 if(ev->window == root && (ev->width != sw || ev->height != sh)) {
438 XFreePixmap(dpy, dc.drawable);
439 dc.drawable = XCreatePixmap(dpy, root, sw, bh, DefaultDepth(dpy, screen));
440 XResizeWindow(dpy, barwin, sw, bh);
447 configurerequest(XEvent *e) {
449 XConfigureRequestEvent *ev = &e->xconfigurerequest;
452 if((c = getclient(ev->window))) {
454 if(ev->value_mask & CWBorderWidth)
455 c->border = ev->border_width;
456 if(c->isfixed || c->isfloating || isarrange(floating)) {
457 if(ev->value_mask & CWX)
459 if(ev->value_mask & CWY)
461 if(ev->value_mask & CWWidth)
463 if(ev->value_mask & CWHeight)
465 if((c->x + c->w) > sw && c->isfloating)
466 c->x = sw / 2 - c->w / 2; /* center in x direction */
467 if((c->y + c->h) > sh && c->isfloating)
468 c->y = sh / 2 - c->h / 2; /* center in y direction */
469 if((ev->value_mask & (CWX | CWY))
470 && !(ev->value_mask & (CWWidth | CWHeight)))
473 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h);
481 wc.width = ev->width;
482 wc.height = ev->height;
483 wc.border_width = ev->border_width;
484 wc.sibling = ev->above;
485 wc.stack_mode = ev->detail;
486 XConfigureWindow(dpy, ev->window, ev->value_mask, &wc);
492 destroynotify(XEvent *e) {
494 XDestroyWindowEvent *ev = &e->xdestroywindow;
496 if((c = getclient(ev->window)))
503 c->prev->next = c->next;
505 c->next->prev = c->prev;
508 c->next = c->prev = NULL;
512 detachstack(Client *c) {
515 for(tc=&stack; *tc && *tc != c; tc=&(*tc)->snext);
524 for(i = 0; i < ntags; i++) {
525 dc.w = textw(tags[i]);
527 drawtext(tags[i], dc.sel);
528 drawsquare(sel && sel->tags[i], isoccupied(i), dc.sel);
531 drawtext(tags[i], dc.norm);
532 drawsquare(sel && sel->tags[i], isoccupied(i), dc.norm);
537 drawtext(layouts[ltidx].symbol, dc.norm);
545 drawtext(stext, dc.norm);
546 if((dc.w = dc.x - x) > bh) {
549 drawtext(sel->name, dc.sel);
550 drawsquare(sel->ismax, sel->isfloating, dc.sel);
553 drawtext(NULL, dc.norm);
555 XCopyArea(dpy, dc.drawable, barwin, dc.gc, 0, 0, sw, bh, 0, 0);
560 drawsquare(Bool filled, Bool empty, unsigned long col[ColLast]) {
563 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
565 gcv.foreground = col[ColFG];
566 XChangeGC(dpy, dc.gc, GCForeground, &gcv);
567 x = (dc.font.ascent + dc.font.descent + 2) / 4;
571 r.width = r.height = x + 1;
572 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
575 r.width = r.height = x;
576 XDrawRectangles(dpy, dc.drawable, dc.gc, &r, 1);
581 drawtext(const char *text, unsigned long col[ColLast]) {
583 static char buf[256];
584 unsigned int len, olen;
585 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
587 XSetForeground(dpy, dc.gc, col[ColBG]);
588 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
592 olen = len = strlen(text);
593 if(len >= sizeof buf)
594 len = sizeof buf - 1;
595 memcpy(buf, text, len);
597 h = dc.font.ascent + dc.font.descent;
598 y = dc.y + (dc.h / 2) - (h / 2) + dc.font.ascent;
600 /* shorten text if necessary */
601 while(len && (w = textnw(buf, len)) > dc.w - h)
612 return; /* too long */
613 XSetForeground(dpy, dc.gc, col[ColFG]);
615 XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
617 XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
621 emallocz(unsigned int size) {
622 void *res = calloc(1, size);
625 eprint("fatal: could not malloc() %u bytes\n", size);
630 enternotify(XEvent *e) {
632 XCrossingEvent *ev = &e->xcrossing;
634 if(ev->mode != NotifyNormal || ev->detail == NotifyInferior)
636 if((c = getclient(ev->window)))
638 else if(ev->window == root) {
645 eprint(const char *errstr, ...) {
648 va_start(ap, errstr);
649 vfprintf(stderr, errstr, ap);
656 XExposeEvent *ev = &e->xexpose;
659 if(barwin == ev->window)
665 floating(void) { /* default floating layout */
668 for(c = clients; c; c = c->next)
670 resize(c, c->x, c->y, c->w, c->h, True);
675 if((!c && selscreen) || (c && !isvisible(c)))
676 for(c = stack; c && !isvisible(c); c = c->snext);
677 if(sel && sel != c) {
678 grabbuttons(sel, False);
679 XSetWindowBorder(dpy, sel->win, dc.norm[ColBorder]);
684 grabbuttons(c, True);
691 XSetWindowBorder(dpy, c->win, dc.sel[ColBorder]);
692 XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
695 XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
699 focusnext(const char *arg) {
704 for(c = sel->next; c && !isvisible(c); c = c->next);
706 for(c = clients; c && !isvisible(c); c = c->next);
714 focusprev(const char *arg) {
719 for(c = sel->prev; c && !isvisible(c); c = c->prev);
721 for(c = clients; c && c->next; c = c->next);
722 for(; c && !isvisible(c); c = c->prev);
731 getclient(Window w) {
734 for(c = clients; c && c->win != w; c = c->next);
739 getcolor(const char *colstr) {
740 Colormap cmap = DefaultColormap(dpy, screen);
743 if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
744 eprint("error, cannot allocate color '%s'\n", colstr);
752 unsigned char *p = NULL;
753 unsigned long n, extra;
756 status = XGetWindowProperty(dpy, w, wmatom[WMState], 0L, 2L, False, wmatom[WMState],
757 &real, &format, &n, &extra, (unsigned char **)&p);
758 if(status != Success)
767 gettextprop(Window w, Atom atom, char *text, unsigned int size) {
772 if(!text || size == 0)
775 XGetTextProperty(dpy, w, &name, atom);
778 if(name.encoding == XA_STRING)
779 strncpy(text, (char *)name.value, size - 1);
781 if(XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success
784 strncpy(text, *list, size - 1);
785 XFreeStringList(list);
788 text[size - 1] = '\0';
794 grabbuttons(Client *c, Bool focused) {
795 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
798 XGrabButton(dpy, Button1, MODKEY, c->win, False, BUTTONMASK,
799 GrabModeAsync, GrabModeSync, None, None);
800 XGrabButton(dpy, Button1, MODKEY | LockMask, c->win, False, BUTTONMASK,
801 GrabModeAsync, GrabModeSync, None, None);
802 XGrabButton(dpy, Button1, MODKEY | numlockmask, c->win, False, BUTTONMASK,
803 GrabModeAsync, GrabModeSync, None, None);
804 XGrabButton(dpy, Button1, MODKEY | numlockmask | LockMask, c->win, False, BUTTONMASK,
805 GrabModeAsync, GrabModeSync, None, None);
807 XGrabButton(dpy, Button2, MODKEY, c->win, False, BUTTONMASK,
808 GrabModeAsync, GrabModeSync, None, None);
809 XGrabButton(dpy, Button2, MODKEY | LockMask, c->win, False, BUTTONMASK,
810 GrabModeAsync, GrabModeSync, None, None);
811 XGrabButton(dpy, Button2, MODKEY | numlockmask, c->win, False, BUTTONMASK,
812 GrabModeAsync, GrabModeSync, None, None);
813 XGrabButton(dpy, Button2, MODKEY | numlockmask | LockMask, c->win, False, BUTTONMASK,
814 GrabModeAsync, GrabModeSync, None, None);
816 XGrabButton(dpy, Button3, MODKEY, c->win, False, BUTTONMASK,
817 GrabModeAsync, GrabModeSync, None, None);
818 XGrabButton(dpy, Button3, MODKEY | LockMask, c->win, False, BUTTONMASK,
819 GrabModeAsync, GrabModeSync, None, None);
820 XGrabButton(dpy, Button3, MODKEY | numlockmask, c->win, False, BUTTONMASK,
821 GrabModeAsync, GrabModeSync, None, None);
822 XGrabButton(dpy, Button3, MODKEY | numlockmask | LockMask, c->win, False, BUTTONMASK,
823 GrabModeAsync, GrabModeSync, None, None);
826 XGrabButton(dpy, AnyButton, AnyModifier, c->win, False, BUTTONMASK,
827 GrabModeAsync, GrabModeSync, None, None);
831 idxoftag(const char *tag) {
834 for(i = 0; i < ntags; i++)
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 isarrange(void (*func)())
885 return func == layouts[ltidx].arrange;
889 isoccupied(unsigned int t) {
892 for(c = clients; c; c = c->next)
899 isprotodel(Client *c) {
904 if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
905 for(i = 0; !ret && i < n; i++)
906 if(protocols[i] == wmatom[WMDelete])
914 isvisible(Client *c) {
917 for(i = 0; i < ntags; i++)
918 if(c->tags[i] && seltags[i])
924 keypress(XEvent *e) {
926 unsigned int len = sizeof keys / sizeof keys[0];
932 if(!e) { /* grabkeys */
933 XUngrabKey(dpy, AnyKey, AnyModifier, root);
934 for(i = 0; i < len; i++) {
935 code = XKeysymToKeycode(dpy, keys[i].keysym);
936 XGrabKey(dpy, code, keys[i].mod, root, True,
937 GrabModeAsync, GrabModeAsync);
938 XGrabKey(dpy, code, keys[i].mod | LockMask, root, True,
939 GrabModeAsync, GrabModeAsync);
940 XGrabKey(dpy, code, keys[i].mod | numlockmask, root, True,
941 GrabModeAsync, GrabModeAsync);
942 XGrabKey(dpy, code, keys[i].mod | numlockmask | LockMask, root, True,
943 GrabModeAsync, GrabModeAsync);
948 keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
949 for(i = 0; i < len; i++)
950 if(keysym == keys[i].keysym
951 && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state))
954 keys[i].func(keys[i].arg);
959 killclient(const char *arg) {
964 if(isprotodel(sel)) {
965 ev.type = ClientMessage;
966 ev.xclient.window = sel->win;
967 ev.xclient.message_type = wmatom[WMProtocols];
968 ev.xclient.format = 32;
969 ev.xclient.data.l[0] = wmatom[WMDelete];
970 ev.xclient.data.l[1] = CurrentTime;
971 XSendEvent(dpy, sel->win, False, NoEventMask, &ev);
974 XKillClient(dpy, sel->win);
978 leavenotify(XEvent *e) {
979 XCrossingEvent *ev = &e->xcrossing;
981 if((ev->window == root) && !ev->same_screen) {
988 manage(Window w, XWindowAttributes *wa) {
989 Client *c, *t = NULL;
994 c = emallocz(sizeof(Client));
995 c->tags = emallocz(sizeof seltags);
1001 c->oldborder = wa->border_width;
1002 if(c->w == sw && c->h == sh) {
1005 c->border = wa->border_width;
1008 if(c->x + c->w + 2 * c->border > wax + waw)
1009 c->x = wax + waw - c->w - 2 * c->border;
1010 if(c->y + c->h + 2 * c->border > way + wah)
1011 c->y = way + wah - c->h - 2 * c->border;
1016 c->border = BORDERPX;
1018 wc.border_width = c->border;
1019 XConfigureWindow(dpy, w, CWBorderWidth, &wc);
1020 XSetWindowBorder(dpy, w, dc.norm[ColBorder]);
1021 configure(c); /* propagates border_width, if size doesn't change */
1023 XSelectInput(dpy, w,
1024 StructureNotifyMask | PropertyChangeMask | EnterWindowMask);
1025 grabbuttons(c, False);
1027 if((rettrans = XGetTransientForHint(dpy, w, &trans) == Success))
1028 for(t = clients; t && t->win != trans; t = t->next);
1030 memcpy(c->tags, t->tags, sizeof seltags);
1033 c->isfloating = (rettrans == Success) || c->isfixed;
1036 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h); /* some windows require this */
1038 XMapWindow(dpy, c->win);
1039 setclientstate(c, NormalState);
1044 mappingnotify(XEvent *e) {
1045 XMappingEvent *ev = &e->xmapping;
1047 XRefreshKeyboardMapping(ev);
1048 if(ev->request == MappingKeyboard)
1053 maprequest(XEvent *e) {
1054 static XWindowAttributes wa;
1055 XMapRequestEvent *ev = &e->xmaprequest;
1057 if(!XGetWindowAttributes(dpy, ev->window, &wa))
1059 if(wa.override_redirect)
1061 if(!getclient(ev->window))
1062 manage(ev->window, &wa);
1066 movemouse(Client *c) {
1067 int x1, y1, ocx, ocy, di, nx, ny;
1074 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1075 None, cursor[CurMove], CurrentTime) != GrabSuccess)
1078 XQueryPointer(dpy, root, &dummy, &dummy, &x1, &y1, &di, &di, &dui);
1080 XMaskEvent(dpy, MOUSEMASK | ExposureMask | SubstructureRedirectMask, &ev);
1083 XUngrabPointer(dpy, CurrentTime);
1085 case ConfigureRequest:
1088 handler[ev.type](&ev);
1092 nx = ocx + (ev.xmotion.x - x1);
1093 ny = ocy + (ev.xmotion.y - y1);
1094 if(abs(wax + nx) < SNAP)
1096 else if(abs((wax + waw) - (nx + c->w + 2 * c->border)) < SNAP)
1097 nx = wax + waw - c->w - 2 * c->border;
1098 if(abs(way - ny) < SNAP)
1100 else if(abs((way + wah) - (ny + c->h + 2 * c->border)) < SNAP)
1101 ny = way + wah - c->h - 2 * c->border;
1102 resize(c, nx, ny, c->w, c->h, False);
1109 nexttiled(Client *c) {
1110 for(; c && (c->isfloating || !isvisible(c)); c = c->next);
1115 propertynotify(XEvent *e) {
1118 XPropertyEvent *ev = &e->xproperty;
1120 if(ev->state == PropertyDelete)
1121 return; /* ignore */
1122 if((c = getclient(ev->window))) {
1125 case XA_WM_TRANSIENT_FOR:
1126 XGetTransientForHint(dpy, c->win, &trans);
1127 if(!c->isfloating && (c->isfloating = (getclient(trans) != NULL)))
1130 case XA_WM_NORMAL_HINTS:
1134 if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
1143 quit(const char *arg) {
1144 readin = running = False;
1148 resize(Client *c, int x, int y, int w, int h, Bool sizehints) {
1149 double dx, dy, max, min, ratio;
1153 if(c->minay > 0 && c->maxay > 0 && (h - c->baseh) > 0 && (w - c->basew) > 0) {
1154 dx = (double)(w - c->basew);
1155 dy = (double)(h - c->baseh);
1156 min = (double)(c->minax) / (double)(c->minay);
1157 max = (double)(c->maxax) / (double)(c->maxay);
1159 if(max > 0 && min > 0 && ratio > 0) {
1161 dy = (dx * min + dy) / (min * min + 1);
1163 w = (int)dx + c->basew;
1164 h = (int)dy + c->baseh;
1166 else if(ratio > max) {
1167 dy = (dx * min + dy) / (max * max + 1);
1169 w = (int)dx + c->basew;
1170 h = (int)dy + c->baseh;
1174 if(c->minw && w < c->minw)
1176 if(c->minh && h < c->minh)
1178 if(c->maxw && w > c->maxw)
1180 if(c->maxh && h > c->maxh)
1183 w -= (w - c->basew) % c->incw;
1185 h -= (h - c->baseh) % c->inch;
1187 if(w <= 0 || h <= 0)
1189 /* offscreen appearance fixes */
1191 x = sw - w - 2 * c->border;
1193 y = sh - h - 2 * c->border;
1194 if(x + w + 2 * c->border < sx)
1196 if(y + h + 2 * c->border < sy)
1198 if(c->x != x || c->y != y || c->w != w || c->h != h) {
1201 c->w = wc.width = w;
1202 c->h = wc.height = h;
1203 wc.border_width = c->border;
1204 XConfigureWindow(dpy, c->win, CWX | CWY | CWWidth | CWHeight | CWBorderWidth, &wc);
1211 resizemouse(Client *c) {
1218 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1219 None, cursor[CurResize], CurrentTime) != GrabSuccess)
1222 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->border - 1, c->h + c->border - 1);
1224 XMaskEvent(dpy, MOUSEMASK | ExposureMask | SubstructureRedirectMask , &ev);
1227 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0,
1228 c->w + c->border - 1, c->h + c->border - 1);
1229 XUngrabPointer(dpy, CurrentTime);
1230 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1232 case ConfigureRequest:
1235 handler[ev.type](&ev);
1239 if((nw = ev.xmotion.x - ocx - 2 * c->border + 1) <= 0)
1241 if((nh = ev.xmotion.y - ocy - 2 * c->border + 1) <= 0)
1243 resize(c, c->x, c->y, nw, nh, True);
1258 if(sel->isfloating || isarrange(floating))
1259 XRaiseWindow(dpy, sel->win);
1260 if(!isarrange(floating)) {
1261 wc.stack_mode = Below;
1262 wc.sibling = barwin;
1263 if(!sel->isfloating) {
1264 XConfigureWindow(dpy, sel->win, CWSibling | CWStackMode, &wc);
1265 wc.sibling = sel->win;
1267 for(c = nexttiled(clients); c; c = nexttiled(c->next)) {
1270 XConfigureWindow(dpy, c->win, CWSibling | CWStackMode, &wc);
1271 wc.sibling = c->win;
1275 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1285 /* main event loop, also reads status text from stdin */
1287 xfd = ConnectionNumber(dpy);
1292 FD_SET(STDIN_FILENO, &rd);
1294 if(select(xfd + 1, &rd, NULL, NULL, NULL) == -1) {
1297 eprint("select failed\n");
1299 if(FD_ISSET(STDIN_FILENO, &rd)) {
1300 switch(r = read(STDIN_FILENO, stext, sizeof stext - 1)) {
1302 strncpy(stext, strerror(errno), sizeof stext - 1);
1303 stext[sizeof stext - 1] = '\0';
1307 strncpy(stext, "EOF", 4);
1311 for(stext[r] = '\0', p = stext + strlen(stext) - 1; p >= stext && *p == '\n'; *p-- = '\0');
1312 for(; p >= stext && *p != '\n'; --p);
1314 strncpy(stext, p + 1, sizeof stext);
1318 while(XPending(dpy)) {
1319 XNextEvent(dpy, &ev);
1320 if(handler[ev.type])
1321 (handler[ev.type])(&ev); /* call handler */
1328 unsigned int i, num;
1329 Window *wins, d1, d2;
1330 XWindowAttributes wa;
1333 if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1334 for(i = 0; i < num; i++) {
1335 if(!XGetWindowAttributes(dpy, wins[i], &wa)
1336 || wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1338 if(wa.map_state == IsViewable || getstate(wins[i]) == IconicState)
1339 manage(wins[i], &wa);
1341 for(i = 0; i < num; i++) { /* now the transients */
1342 if(!XGetWindowAttributes(dpy, wins[i], &wa))
1344 if(XGetTransientForHint(dpy, wins[i], &d1)
1345 && (wa.map_state == IsViewable || getstate(wins[i]) == IconicState))
1346 manage(wins[i], &wa);
1354 setclientstate(Client *c, long state) {
1355 long data[] = {state, None};
1357 XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1358 PropModeReplace, (unsigned char *)data, 2);
1362 setlayout(const char *arg) {
1366 if(++ltidx == nlayouts)
1370 for(i = 0; i < nlayouts; i++)
1371 if(!strcmp(arg, layouts[i].symbol))
1384 setmwfact(const char *arg) {
1389 /* arg handling, manipulate mwfact */
1392 else if(1 == sscanf(arg, "%lf", &delta)) {
1393 if(arg[0] == '+' || arg[0] == '-')
1399 else if(mwfact > 0.9)
1408 unsigned int i, j, mask;
1410 XModifierKeymap *modmap;
1411 XSetWindowAttributes wa;
1414 wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1415 wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1416 wmatom[WMName] = XInternAtom(dpy, "WM_NAME", False);
1417 wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1418 netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1419 netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1420 XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1421 PropModeReplace, (unsigned char *) netatom, NetLast);
1424 cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1425 cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1426 cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1430 sw = DisplayWidth(dpy, screen);
1431 sh = DisplayHeight(dpy, screen);
1433 /* init modifier map */
1434 modmap = XGetModifierMapping(dpy);
1435 for(i = 0; i < 8; i++)
1436 for(j = 0; j < modmap->max_keypermod; j++) {
1437 if(modmap->modifiermap[i * modmap->max_keypermod + j]
1438 == XKeysymToKeycode(dpy, XK_Num_Lock))
1439 numlockmask = (1 << i);
1441 XFreeModifiermap(modmap);
1443 /* select for events */
1444 wa.event_mask = SubstructureRedirectMask | SubstructureNotifyMask
1445 | EnterWindowMask | LeaveWindowMask | StructureNotifyMask;
1446 wa.cursor = cursor[CurNormal];
1447 XChangeWindowAttributes(dpy, root, CWEventMask | CWCursor, &wa);
1448 XSelectInput(dpy, root, wa.event_mask);
1456 /* init appearance */
1457 dc.norm[ColBorder] = getcolor(NORMBORDERCOLOR);
1458 dc.norm[ColBG] = getcolor(NORMBGCOLOR);
1459 dc.norm[ColFG] = getcolor(NORMFGCOLOR);
1460 dc.sel[ColBorder] = getcolor(SELBORDERCOLOR);
1461 dc.sel[ColBG] = getcolor(SELBGCOLOR);
1462 dc.sel[ColFG] = getcolor(SELFGCOLOR);
1464 dc.h = bh = dc.font.height + 2;
1468 nlayouts = sizeof layouts / sizeof layouts[0];
1469 for(blw = i = 0; i < nlayouts; i++) {
1470 j = textw(layouts[i].symbol);
1477 wa.override_redirect = 1;
1478 wa.background_pixmap = ParentRelative;
1479 wa.event_mask = ButtonPressMask | ExposureMask;
1480 barwin = XCreateWindow(dpy, root, sx, sy, sw, bh, 0,
1481 DefaultDepth(dpy, screen), CopyFromParent, DefaultVisual(dpy, screen),
1482 CWOverrideRedirect | CWBackPixmap | CWEventMask, &wa);
1483 XDefineCursor(dpy, barwin, cursor[CurNormal]);
1485 XMapRaised(dpy, barwin);
1486 strcpy(stext, "dwm-"VERSION);
1487 dc.drawable = XCreatePixmap(dpy, root, sw, bh, DefaultDepth(dpy, screen));
1488 dc.gc = XCreateGC(dpy, root, 0, 0);
1489 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
1491 XSetFont(dpy, dc.gc, dc.font.xfont->fid);
1493 /* multihead support */
1494 selscreen = XQueryPointer(dpy, root, &w, &w, &d, &d, &d, &d, &mask);
1498 spawn(const char *arg) {
1499 static char *shell = NULL;
1501 if(!shell && !(shell = getenv("SHELL")))
1505 /* The double-fork construct avoids zombie processes and keeps the code
1506 * clean from stupid signal handlers. */
1510 close(ConnectionNumber(dpy));
1512 execl(shell, shell, "-c", arg, (char *)NULL);
1513 fprintf(stderr, "dwm: execl '%s -c %s'", shell, arg);
1522 tag(const char *arg) {
1527 for(i = 0; i < ntags; i++)
1528 sel->tags[i] = arg == NULL;
1530 if(i >= 0 && i < ntags)
1531 sel->tags[i] = True;
1536 textnw(const char *text, unsigned int len) {
1540 XmbTextExtents(dc.font.set, text, len, NULL, &r);
1543 return XTextWidth(dc.font.xfont, text, len);
1547 textw(const char *text) {
1548 return textnw(text, strlen(text)) + dc.font.height;
1553 unsigned int i, n, nx, ny, nw, nh, mw, th;
1556 for(n = 0, c = nexttiled(clients); c; c = nexttiled(c->next))
1560 mw = (n == 1) ? waw : mwfact * waw;
1561 th = (n > 1) ? wah / (n - 1) : 0;
1562 if(n > 1 && th < bh)
1567 nw = 0; /* gcc stupidity requires this */
1568 for(i = 0, c = mc = nexttiled(clients); c; c = nexttiled(c->next), i++) {
1570 if(i == 0) { /* master */
1571 nw = mw - 2 * c->border;
1572 nh = wah - 2 * c->border;
1574 else { /* tile window */
1577 nx += mc->w + 2 * mc->border;
1578 nw = waw - nx - 2 * c->border;
1580 if(i + 1 == n) /* remainder */
1581 nh = (way + wah) - ny - 2 * c->border;
1583 nh = th - 2 * c->border;
1585 resize(c, nx, ny, nw, nh, RESIZEHINTS);
1586 if(n > 1 && th != wah)
1587 ny = c->y + c->h + 2 * c->border;
1592 togglebar(const char *arg) {
1594 bpos = (BARPOS == BarOff) ? BarTop : BARPOS;
1602 togglefloating(const char *arg) {
1605 sel->isfloating = !sel->isfloating;
1607 resize(sel, sel->x, sel->y, sel->w, sel->h, True);
1612 togglemax(const char *arg) {
1615 if(!sel || sel->isfixed)
1617 if((sel->ismax = !sel->ismax)) {
1618 if(isarrange(floating) || sel->isfloating)
1619 sel->wasfloating = True;
1621 togglefloating(NULL);
1622 sel->wasfloating = False;
1628 resize(sel, wax, way, waw - 2 * sel->border, wah - 2 * sel->border, True);
1631 resize(sel, sel->rx, sel->ry, sel->rw, sel->rh, True);
1632 if(!sel->wasfloating)
1633 togglefloating(NULL);
1636 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1640 toggletag(const char *arg) {
1646 sel->tags[i] = !sel->tags[i];
1647 for(j = 0; j < ntags && !sel->tags[j]; j++);
1649 sel->tags[i] = True;
1654 toggleview(const char *arg) {
1658 seltags[i] = !seltags[i];
1659 for(j = 0; j < ntags && !seltags[j]; j++);
1661 seltags[i] = True; /* at least one tag must be viewed */
1669 XMoveWindow(dpy, c->win, c->x, c->y);
1670 c->isbanned = False;
1674 unmanage(Client *c) {
1677 wc.border_width = c->oldborder;
1678 /* The server grab construct avoids race conditions. */
1680 XSetErrorHandler(xerrordummy);
1681 XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
1686 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1687 setclientstate(c, WithdrawnState);
1691 XSetErrorHandler(xerror);
1697 unmapnotify(XEvent *e) {
1699 XUnmapEvent *ev = &e->xunmap;
1701 if((c = getclient(ev->window)))
1706 updatebarpos(void) {
1717 XMoveWindow(dpy, barwin, sx, sy);
1721 XMoveWindow(dpy, barwin, sx, sy + wah);
1724 XMoveWindow(dpy, barwin, sx, sy - bh);
1728 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1732 updatesizehints(Client *c) {
1736 if(!XGetWMNormalHints(dpy, c->win, &size, &msize) || !size.flags)
1738 c->flags = size.flags;
1739 if(c->flags & PBaseSize) {
1740 c->basew = size.base_width;
1741 c->baseh = size.base_height;
1743 else if(c->flags & PMinSize) {
1744 c->basew = size.min_width;
1745 c->baseh = size.min_height;
1748 c->basew = c->baseh = 0;
1749 if(c->flags & PResizeInc) {
1750 c->incw = size.width_inc;
1751 c->inch = size.height_inc;
1754 c->incw = c->inch = 0;
1755 if(c->flags & PMaxSize) {
1756 c->maxw = size.max_width;
1757 c->maxh = size.max_height;
1760 c->maxw = c->maxh = 0;
1761 if(c->flags & PMinSize) {
1762 c->minw = size.min_width;
1763 c->minh = size.min_height;
1765 else if(c->flags & PBaseSize) {
1766 c->minw = size.base_width;
1767 c->minh = size.base_height;
1770 c->minw = c->minh = 0;
1771 if(c->flags & PAspect) {
1772 c->minax = size.min_aspect.x;
1773 c->maxax = size.max_aspect.x;
1774 c->minay = size.min_aspect.y;
1775 c->maxay = size.max_aspect.y;
1778 c->minax = c->maxax = c->minay = c->maxay = 0;
1779 c->isfixed = (c->maxw && c->minw && c->maxh && c->minh
1780 && c->maxw == c->minw && c->maxh == c->minh);
1784 updatetitle(Client *c) {
1785 if(!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
1786 gettextprop(c->win, wmatom[WMName], c->name, sizeof c->name);
1789 /* There's no way to check accesses to destroyed windows, thus those cases are
1790 * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
1791 * default error handler, which may call exit. */
1793 xerror(Display *dpy, XErrorEvent *ee) {
1794 if(ee->error_code == BadWindow
1795 || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1796 || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1797 || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1798 || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1799 || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1800 || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1801 || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1803 fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1804 ee->request_code, ee->error_code);
1805 return xerrorxlib(dpy, ee); /* may call exit */
1809 xerrordummy(Display *dsply, XErrorEvent *ee) {
1813 /* Startup Error handler to check if another window manager
1814 * is already running. */
1816 xerrorstart(Display *dsply, XErrorEvent *ee) {
1822 view(const char *arg) {
1825 memcpy(prevtags, seltags, sizeof seltags);
1826 for(i = 0; i < ntags; i++)
1827 seltags[i] = arg == NULL;
1829 if(i >= 0 && i < ntags)
1835 viewprevtag(const char *arg) {
1836 static Bool tmptags[sizeof tags / sizeof tags[0]];
1838 memcpy(tmptags, seltags, sizeof seltags);
1839 memcpy(seltags, prevtags, sizeof seltags);
1840 memcpy(prevtags, tmptags, sizeof seltags);
1845 zoom(const char *arg) {
1848 if(!sel || !ISTILE || sel->isfloating)
1850 if((c = sel) == nexttiled(clients))
1851 if(!(c = nexttiled(c->next)))
1860 main(int argc, char *argv[]) {
1861 if(argc == 2 && !strcmp("-v", argv[1]))
1862 eprint("dwm-"VERSION", © 2006-2007 A. R. Garbe, S. van Dijk, J. Salmi, P. Hruby, S. Nagy\n");
1864 eprint("usage: dwm [-v]\n");
1866 setlocale(LC_CTYPE, "");
1867 if(!(dpy = XOpenDisplay(0)))
1868 eprint("dwm: cannot open display\n");
1869 screen = DefaultScreen(dpy);
1870 root = RootWindow(dpy, screen);