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 * The event handlers of dwm are organized in an array which is accessed
10 * whenever a new event has been fetched. This allows event dispatching
13 * Each child of the root window is called a client, except windows which have
14 * set the override_redirect flag. Clients are organized in a global
15 * linked client list, the focus history is remembered through a global
16 * stack list. Each client contains a bit array to indicate the tags of a
19 * Keys and tagging rules are organized as arrays and defined in config.h.
21 * To understand everything else, start reading main().
31 #include <sys/types.h>
33 #include <X11/cursorfont.h>
34 #include <X11/keysym.h>
35 #include <X11/Xatom.h>
37 #include <X11/Xproto.h>
38 #include <X11/Xutil.h>
40 #include <X11/extensions/Xinerama.h>
44 #define BUTTONMASK (ButtonPressMask|ButtonReleaseMask)
45 #define CLEANMASK(mask) (mask & ~(numlockmask|LockMask))
46 #define INRECT(X,Y,RX,RY,RW,RH) ((X) >= (RX) && (X) < (RX) + (RW) && (Y) >= (RY) && (Y) < (RY) + (RH))
47 #define ISVISIBLE(x) (x->tags & tagset[seltags])
48 #define LENGTH(x) (sizeof x / sizeof x[0])
49 #define MAX(a, b) ((a) > (b) ? (a) : (b))
50 #define MIN(a, b) ((a) < (b) ? (a) : (b))
52 #define MOUSEMASK (BUTTONMASK|PointerMotionMask)
53 #define WIDTH(x) ((x)->w + 2 * (x)->bw)
54 #define HEIGHT(x) ((x)->h + 2 * (x)->bw)
55 #define TAGMASK ((int)((1LL << LENGTH(tags)) - 1))
56 #define TEXTW(x) (textnw(x, strlen(x)) + dc.font.height)
59 enum { CurNormal, CurResize, CurMove, CurLast }; /* cursor */
60 enum { ColBorder, ColFG, ColBG, ColLast }; /* color */
61 enum { NetSupported, NetWMName, NetLast }; /* EWMH atoms */
62 enum { WMProtocols, WMDelete, WMState, WMLast }; /* default atoms */
63 enum { ClkTagBar, ClkLtSymbol, ClkStatusText, ClkWinTitle,
64 ClkClientWin, ClkRootWin, ClkLast }; /* clicks */
77 void (*func)(const Arg *arg);
81 typedef struct Client Client;
86 int basew, baseh, incw, inch, maxw, maxh, minw, minh;
89 Bool isfixed, isfloating, isurgent;
97 unsigned long norm[ColLast];
98 unsigned long sel[ColLast];
108 } DC; /* draw context */
113 void (*func)(const Arg *);
119 void (*arrange)(void);
124 const char *instance;
130 /* function declarations */
131 static void applyrules(Client *c);
132 static void arrange(void);
133 static void attach(Client *c);
134 static void attachstack(Client *c);
135 static void buttonpress(XEvent *e);
136 static void checkotherwm(void);
137 static void cleanup(void);
138 static void clearurgent(Client *c);
139 static void configure(Client *c);
140 static void configurenotify(XEvent *e);
141 static void configurerequest(XEvent *e);
142 static void destroynotify(XEvent *e);
143 static void detach(Client *c);
144 static void detachstack(Client *c);
145 static void die(const char *errstr, ...);
146 static void drawbar(void);
147 static void drawsquare(Bool filled, Bool empty, Bool invert, unsigned long col[ColLast]);
148 static void drawtext(const char *text, unsigned long col[ColLast], Bool invert);
149 static void enternotify(XEvent *e);
150 static void expose(XEvent *e);
151 static void focus(Client *c);
152 static void focusin(XEvent *e);
153 static void focusstack(const Arg *arg);
154 static Client *getclient(Window w);
155 static unsigned long getcolor(const char *colstr);
156 static long getstate(Window w);
157 static Bool gettextprop(Window w, Atom atom, char *text, unsigned int size);
158 static void grabbuttons(Client *c, Bool focused);
159 static void grabkeys(void);
160 static void initfont(const char *fontstr);
161 static Bool isprotodel(Client *c);
162 static void keypress(XEvent *e);
163 static void killclient(const Arg *arg);
164 static void manage(Window w, XWindowAttributes *wa);
165 static void mappingnotify(XEvent *e);
166 static void maprequest(XEvent *e);
167 static void monocle(void);
168 static void movemouse(const Arg *arg);
169 static Client *nexttiled(Client *c);
170 static void propertynotify(XEvent *e);
171 static void quit(const Arg *arg);
172 static void resize(Client *c, int x, int y, int w, int h, Bool sizehints);
173 static void resizemouse(const Arg *arg);
174 static void restack(void);
175 static void run(void);
176 static void scan(void);
177 static void setclientstate(Client *c, long state);
178 static void setlayout(const Arg *arg);
179 static void setmfact(const Arg *arg);
180 static void setup(void);
181 static void showhide(Client *c, unsigned int ntiled);
182 static void sigchld(int signal);
183 static void spawn(const Arg *arg);
184 static void tag(const Arg *arg);
185 static int textnw(const char *text, unsigned int len);
186 static void tile(void);
187 static void togglebar(const Arg *arg);
188 static void togglefloating(const Arg *arg);
189 static void toggletag(const Arg *arg);
190 static void toggleview(const Arg *arg);
191 static void unmanage(Client *c);
192 static void unmapnotify(XEvent *e);
193 static void updatebar(void);
194 static void updategeom(void);
195 static void updatenumlockmask(void);
196 static void updatesizehints(Client *c);
197 static void updatestatus(void);
198 static void updatetitle(Client *c);
199 static void updatewmhints(Client *c);
200 static void view(const Arg *arg);
201 static int xerror(Display *dpy, XErrorEvent *ee);
202 static int xerrordummy(Display *dpy, XErrorEvent *ee);
203 static int xerrorstart(Display *dpy, XErrorEvent *ee);
204 static void zoom(const Arg *arg);
207 static char stext[256];
209 static int sx, sy, sw, sh; /* X display screen geometry x, y, width, height */
210 static int by, bh, blw; /* bar geometry y, height and layout symbol width */
211 static int wx, wy, ww, wh; /* window area geometry x, y, width, height, bar excluded */
212 static unsigned int seltags = 0, sellt = 0;
213 static int (*xerrorxlib)(Display *, XErrorEvent *);
214 static unsigned int numlockmask = 0;
215 static void (*handler[LASTEvent]) (XEvent *) = {
216 [ButtonPress] = buttonpress,
217 [ConfigureRequest] = configurerequest,
218 [ConfigureNotify] = configurenotify,
219 [DestroyNotify] = destroynotify,
220 [EnterNotify] = enternotify,
223 [KeyPress] = keypress,
224 [MappingNotify] = mappingnotify,
225 [MapRequest] = maprequest,
226 [PropertyNotify] = propertynotify,
227 [UnmapNotify] = unmapnotify
229 static Atom wmatom[WMLast], netatom[NetLast];
231 static Bool running = True;
232 static Client *clients = NULL;
233 static Client *sel = NULL;
234 static Client *stack = NULL;
235 static Cursor cursor[CurLast];
238 static Layout *lt[] = { NULL, NULL };
239 static Window root, barwin;
240 /* configuration, allows nested code to access above variables */
243 /* compile-time check if all tags fit into an unsigned int bit array. */
244 struct NumTags { char limitexceeded[sizeof(unsigned int) * 8 < LENGTH(tags) ? -1 : 1]; };
246 /* function implementations */
248 applyrules(Client *c) {
251 XClassHint ch = { 0 };
254 if(XGetClassHint(dpy, c->win, &ch)) {
255 for(i = 0; i < LENGTH(rules); i++) {
257 if((!r->title || strstr(c->name, r->title))
258 && (!r->class || (ch.res_class && strstr(ch.res_class, r->class)))
259 && (!r->instance || (ch.res_name && strstr(ch.res_name, r->instance)))) {
260 c->isfloating = r->isfloating;
261 c->tags |= r->tags & TAGMASK ? r->tags & TAGMASK : tagset[seltags];
270 c->tags = tagset[seltags];
278 for(nt = 0, c = nexttiled(clients); c; c = nexttiled(c->next), nt++);
281 if(lt[sellt]->arrange)
282 lt[sellt]->arrange();
293 attachstack(Client *c) {
299 buttonpress(XEvent *e) {
300 unsigned int i, x, click;
303 XButtonPressedEvent *ev = &e->xbutton;
306 if(ev->window == barwin) {
308 do x += TEXTW(tags[i]); while(ev->x >= x && ++i < LENGTH(tags));
309 if(i < LENGTH(tags)) {
313 else if(ev->x < x + blw)
315 else if(ev->x > wx + ww - TEXTW(stext))
316 click = ClkStatusText;
320 else if((c = getclient(ev->window))) {
322 click = ClkClientWin;
325 for(i = 0; i < LENGTH(buttons); i++)
326 if(click == buttons[i].click && buttons[i].func && buttons[i].button == ev->button
327 && CLEANMASK(buttons[i].mask) == CLEANMASK(ev->state))
328 buttons[i].func(click == ClkTagBar && buttons[i].arg.i == 0 ? &arg : &buttons[i].arg);
334 xerrorxlib = XSetErrorHandler(xerrorstart);
336 /* this causes an error if some other window manager is running */
337 XSelectInput(dpy, DefaultRootWindow(dpy), SubstructureRedirectMask);
340 die("dwm: another window manager is already running\n");
341 XSetErrorHandler(xerror);
348 Layout foo = { "", NULL };
355 XFreeFontSet(dpy, dc.font.set);
357 XFreeFont(dpy, dc.font.xfont);
358 XUngrabKey(dpy, AnyKey, AnyModifier, root);
359 XFreePixmap(dpy, dc.drawable);
361 XFreeCursor(dpy, cursor[CurNormal]);
362 XFreeCursor(dpy, cursor[CurResize]);
363 XFreeCursor(dpy, cursor[CurMove]);
364 XDestroyWindow(dpy, barwin);
366 XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime);
370 clearurgent(Client *c) {
374 if(!(wmh = XGetWMHints(dpy, c->win)))
376 wmh->flags &= ~XUrgencyHint;
377 XSetWMHints(dpy, c->win, wmh);
382 configure(Client *c) {
385 ce.type = ConfigureNotify;
393 ce.border_width = c->bw;
395 ce.override_redirect = False;
396 XSendEvent(dpy, c->win, False, StructureNotifyMask, (XEvent *)&ce);
400 configurenotify(XEvent *e) {
401 XConfigureEvent *ev = &e->xconfigure;
403 if(ev->window == root && (ev->width != sw || ev->height != sh)) {
413 configurerequest(XEvent *e) {
415 XConfigureRequestEvent *ev = &e->xconfigurerequest;
418 if((c = getclient(ev->window))) {
419 if(ev->value_mask & CWBorderWidth)
420 c->bw = ev->border_width;
421 else if(c->isfloating || !lt[sellt]->arrange) {
422 if(ev->value_mask & CWX)
424 if(ev->value_mask & CWY)
426 if(ev->value_mask & CWWidth)
428 if(ev->value_mask & CWHeight)
430 if((c->x - sx + c->w) > sw && c->isfloating)
431 c->x = sx + (sw / 2 - c->w / 2); /* center in x direction */
432 if((c->y - sy + c->h) > sh && c->isfloating)
433 c->y = sy + (sh / 2 - c->h / 2); /* center in y direction */
434 if((ev->value_mask & (CWX|CWY)) && !(ev->value_mask & (CWWidth|CWHeight)))
437 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h);
445 wc.width = ev->width;
446 wc.height = ev->height;
447 wc.border_width = ev->border_width;
448 wc.sibling = ev->above;
449 wc.stack_mode = ev->detail;
450 XConfigureWindow(dpy, ev->window, ev->value_mask, &wc);
456 destroynotify(XEvent *e) {
458 XDestroyWindowEvent *ev = &e->xdestroywindow;
460 if((c = getclient(ev->window)))
468 for(tc = &clients; *tc && *tc != c; tc = &(*tc)->next);
473 detachstack(Client *c) {
476 for(tc = &stack; *tc && *tc != c; tc = &(*tc)->snext);
481 die(const char *errstr, ...) {
484 va_start(ap, errstr);
485 vfprintf(stderr, errstr, ap);
493 unsigned int i, occ = 0, urg = 0;
497 for(c = clients; c; c = c->next) {
504 for(i = 0; i < LENGTH(tags); i++) {
505 dc.w = TEXTW(tags[i]);
506 col = tagset[seltags] & 1 << i ? dc.sel : dc.norm;
507 drawtext(tags[i], col, urg & 1 << i);
508 drawsquare(sel && sel->tags & 1 << i, occ & 1 << i, urg & 1 << i, col);
513 drawtext(lt[sellt]->symbol, dc.norm, False);
524 drawtext(stext, dc.norm, False);
525 if((dc.w = dc.x - x) > bh) {
528 drawtext(sel->name, dc.sel, False);
529 drawsquare(sel->isfixed, sel->isfloating, False, dc.sel);
532 drawtext(NULL, dc.norm, False);
534 XCopyArea(dpy, dc.drawable, barwin, dc.gc, 0, 0, ww, bh, 0, 0);
539 drawsquare(Bool filled, Bool empty, Bool invert, unsigned long col[ColLast]) {
542 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
544 gcv.foreground = col[invert ? ColBG : ColFG];
545 XChangeGC(dpy, dc.gc, GCForeground, &gcv);
546 x = (dc.font.ascent + dc.font.descent + 2) / 4;
550 r.width = r.height = x + 1;
551 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
554 r.width = r.height = x;
555 XDrawRectangles(dpy, dc.drawable, dc.gc, &r, 1);
560 drawtext(const char *text, unsigned long col[ColLast], Bool invert) {
562 int i, x, y, h, len, olen;
563 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
565 XSetForeground(dpy, dc.gc, col[invert ? ColFG : ColBG]);
566 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
570 h = dc.font.ascent + dc.font.descent;
571 y = dc.y + (dc.h / 2) - (h / 2) + dc.font.ascent;
573 /* shorten text if necessary */
574 for(len = MIN(olen, sizeof buf); len && textnw(text, len) > dc.w - h; len--);
577 memcpy(buf, text, len);
579 for(i = len; i && i > len - 3; buf[--i] = '.');
580 XSetForeground(dpy, dc.gc, col[invert ? ColBG : ColFG]);
582 XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
584 XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
588 enternotify(XEvent *e) {
590 XCrossingEvent *ev = &e->xcrossing;
592 if((ev->mode != NotifyNormal || ev->detail == NotifyInferior) && ev->window != root)
594 if((c = getclient(ev->window)))
602 XExposeEvent *ev = &e->xexpose;
604 if(ev->count == 0 && (ev->window == barwin))
610 if(!c || !ISVISIBLE(c))
611 for(c = stack; c && !ISVISIBLE(c); c = c->snext);
612 if(sel && sel != c) {
613 grabbuttons(sel, False);
614 XSetWindowBorder(dpy, sel->win, dc.norm[ColBorder]);
621 grabbuttons(c, True);
622 XSetWindowBorder(dpy, c->win, dc.sel[ColBorder]);
623 XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
626 XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
632 focusin(XEvent *e) { /* there are some broken focus acquiring clients */
633 XFocusChangeEvent *ev = &e->xfocus;
635 if(sel && ev->window != sel->win)
636 XSetInputFocus(dpy, sel->win, RevertToPointerRoot, CurrentTime);
640 focusstack(const Arg *arg) {
641 Client *c = NULL, *i;
646 for(c = sel->next; c && !ISVISIBLE(c); c = c->next);
648 for(c = clients; c && !ISVISIBLE(c); c = c->next);
651 for(i = clients; i != sel; i = i->next)
655 for(; i; i = i->next)
666 getclient(Window w) {
669 for(c = clients; c && c->win != w; c = c->next);
674 getcolor(const char *colstr) {
675 Colormap cmap = DefaultColormap(dpy, screen);
678 if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
679 die("error, cannot allocate color '%s'\n", colstr);
687 unsigned char *p = NULL;
688 unsigned long n, extra;
691 status = XGetWindowProperty(dpy, w, wmatom[WMState], 0L, 2L, False, wmatom[WMState],
692 &real, &format, &n, &extra, (unsigned char **)&p);
693 if(status != Success)
702 gettextprop(Window w, Atom atom, char *text, unsigned int size) {
707 if(!text || size == 0)
710 XGetTextProperty(dpy, w, &name, atom);
713 if(name.encoding == XA_STRING)
714 strncpy(text, (char *)name.value, size - 1);
716 if(XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success
718 strncpy(text, *list, size - 1);
719 XFreeStringList(list);
722 text[size - 1] = '\0';
728 grabbuttons(Client *c, Bool focused) {
732 unsigned int modifiers[] = { 0, LockMask, numlockmask, numlockmask|LockMask };
733 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
735 for(i = 0; i < LENGTH(buttons); i++)
736 if(buttons[i].click == ClkClientWin)
737 for(j = 0; j < LENGTH(modifiers); j++)
738 XGrabButton(dpy, buttons[i].button, buttons[i].mask | modifiers[j], c->win, False, BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
740 XGrabButton(dpy, AnyButton, AnyModifier, c->win, False,
741 BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
750 unsigned int modifiers[] = { 0, LockMask, numlockmask, numlockmask|LockMask };
753 XUngrabKey(dpy, AnyKey, AnyModifier, root);
754 for(i = 0; i < LENGTH(keys); i++) {
755 if((code = XKeysymToKeycode(dpy, keys[i].keysym)))
756 for(j = 0; j < LENGTH(modifiers); j++)
757 XGrabKey(dpy, code, keys[i].mod | modifiers[j], root,
758 True, GrabModeAsync, GrabModeAsync);
764 initfont(const char *fontstr) {
765 char *def, **missing;
769 dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
772 fprintf(stderr, "dwm: missing fontset: %s\n", missing[n]);
773 XFreeStringList(missing);
776 XFontSetExtents *font_extents;
777 XFontStruct **xfonts;
779 dc.font.ascent = dc.font.descent = 0;
780 font_extents = XExtentsOfFontSet(dc.font.set);
781 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
782 for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
783 dc.font.ascent = MAX(dc.font.ascent, (*xfonts)->ascent);
784 dc.font.descent = MAX(dc.font.descent,(*xfonts)->descent);
789 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr))
790 && !(dc.font.xfont = XLoadQueryFont(dpy, "fixed")))
791 die("error, cannot load font: '%s'\n", fontstr);
792 dc.font.ascent = dc.font.xfont->ascent;
793 dc.font.descent = dc.font.xfont->descent;
795 dc.font.height = dc.font.ascent + dc.font.descent;
799 isprotodel(Client *c) {
804 if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
805 for(i = 0; !ret && i < n; i++)
806 if(protocols[i] == wmatom[WMDelete])
814 keypress(XEvent *e) {
820 keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
821 for(i = 0; i < LENGTH(keys); i++)
822 if(keysym == keys[i].keysym
823 && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state)
825 keys[i].func(&(keys[i].arg));
829 killclient(const Arg *arg) {
834 if(isprotodel(sel)) {
835 ev.type = ClientMessage;
836 ev.xclient.window = sel->win;
837 ev.xclient.message_type = wmatom[WMProtocols];
838 ev.xclient.format = 32;
839 ev.xclient.data.l[0] = wmatom[WMDelete];
840 ev.xclient.data.l[1] = CurrentTime;
841 XSendEvent(dpy, sel->win, False, NoEventMask, &ev);
844 XKillClient(dpy, sel->win);
848 manage(Window w, XWindowAttributes *wa) {
850 Client *c, *t = NULL;
854 if(!(c = malloc(sizeof(Client))))
855 die("fatal: could not malloc() %u bytes\n", sizeof(Client));
864 c->oldbw = wa->border_width;
865 if(c->w == sw && c->h == sh) {
871 if(c->x + WIDTH(c) > sx + sw)
872 c->x = sx + sw - WIDTH(c);
873 if(c->y + HEIGHT(c) > sy + sh)
874 c->y = sy + sh - HEIGHT(c);
875 c->x = MAX(c->x, sx);
876 /* only fix client y-offset, if the client center might cover the bar */
877 c->y = MAX(c->y, ((by == 0) && (c->x + (c->w / 2) >= wx) && (c->x + (c->w / 2) < wx + ww)) ? bh : sy);
881 wc.border_width = c->bw;
882 XConfigureWindow(dpy, w, CWBorderWidth, &wc);
883 XSetWindowBorder(dpy, w, dc.norm[ColBorder]);
884 configure(c); /* propagates border_width, if size doesn't change */
886 XSelectInput(dpy, w, EnterWindowMask|FocusChangeMask|PropertyChangeMask|StructureNotifyMask);
887 grabbuttons(c, False);
889 if(XGetTransientForHint(dpy, w, &trans))
890 t = getclient(trans);
896 c->isfloating = trans != None || c->isfixed;
898 XRaiseWindow(dpy, c->win);
901 XMoveResizeWindow(dpy, c->win, c->x + 2 * sw, c->y, c->w, c->h); /* some windows require this */
902 XMapWindow(dpy, c->win);
903 setclientstate(c, NormalState);
908 mappingnotify(XEvent *e) {
909 XMappingEvent *ev = &e->xmapping;
911 XRefreshKeyboardMapping(ev);
912 if(ev->request == MappingKeyboard)
917 maprequest(XEvent *e) {
918 static XWindowAttributes wa;
919 XMapRequestEvent *ev = &e->xmaprequest;
921 if(!XGetWindowAttributes(dpy, ev->window, &wa))
923 if(wa.override_redirect)
925 if(!getclient(ev->window))
926 manage(ev->window, &wa);
933 for(c = nexttiled(clients); c; c = nexttiled(c->next)) {
934 resize(c, wx, wy, ww - 2 * c->bw, wh - 2 * c->bw, resizehints);
939 movemouse(const Arg *arg) {
940 int x, y, ocx, ocy, di, nx, ny;
951 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
952 None, cursor[CurMove], CurrentTime) != GrabSuccess)
954 XQueryPointer(dpy, root, &dummy, &dummy, &x, &y, &di, &di, &dui);
958 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
960 case ConfigureRequest:
963 handler[ev.type](&ev);
966 nx = ocx + (ev.xmotion.x - x);
967 ny = ocy + (ev.xmotion.y - y);
968 if(snap && nx >= wx && nx <= wx + ww
969 && ny >= wy && ny <= wy + wh) {
970 if(abs(wx - nx) < snap)
972 else if(abs((wx + ww) - (nx + WIDTH(c))) < snap)
973 nx = wx + ww - WIDTH(c);
974 if(abs(wy - ny) < snap)
976 else if(abs((wy + wh) - (ny + HEIGHT(c))) < snap)
977 ny = wy + wh - HEIGHT(c);
978 if(!c->isfloating && lt[sellt]->arrange && (abs(nx - c->x) > snap || abs(ny - c->y) > snap))
979 togglefloating(NULL);
981 if(!lt[sellt]->arrange || c->isfloating)
982 resize(c, nx, ny, c->w, c->h, False);
986 while(ev.type != ButtonRelease);
989 XUngrabPointer(dpy, CurrentTime);
993 nexttiled(Client *c) {
994 for(; c && (c->isfloating || !ISVISIBLE(c)); c = c->next);
999 propertynotify(XEvent *e) {
1002 XPropertyEvent *ev = &e->xproperty;
1004 if((ev->window == root) && (ev->atom == XA_WM_NAME))
1006 else if(ev->state == PropertyDelete)
1007 return; /* ignore */
1008 else if((c = getclient(ev->window))) {
1011 case XA_WM_TRANSIENT_FOR:
1012 XGetTransientForHint(dpy, c->win, &trans);
1013 if(!c->isfloating && (c->isfloating = (getclient(trans) != NULL)))
1016 case XA_WM_NORMAL_HINTS:
1024 if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
1033 quit(const Arg *arg) {
1038 resize(Client *c, int x, int y, int w, int h, Bool sizehints) {
1042 /* see last two sentences in ICCCM 4.1.2.3 */
1043 Bool baseismin = c->basew == c->minw && c->baseh == c->minh;
1045 /* set minimum possible */
1049 if(!baseismin) { /* temporarily remove base dimensions */
1054 /* adjust for aspect limits */
1055 if(c->mina > 0 && c->maxa > 0) {
1056 if(c->maxa < (float)w / h)
1058 else if(c->mina < (float)h / w)
1062 if(baseismin) { /* increment calculation requires this */
1067 /* adjust for increment value */
1073 /* restore base dimensions */
1077 w = MAX(w, c->minw);
1078 h = MAX(h, c->minh);
1081 w = MIN(w, c->maxw);
1084 h = MIN(h, c->maxh);
1086 if(w <= 0 || h <= 0)
1092 if(x + w + 2 * c->bw < sx)
1094 if(y + h + 2 * c->bw < sy)
1100 if(c->x != x || c->y != y || c->w != w || c->h != h) {
1103 c->w = wc.width = w;
1104 c->h = wc.height = h;
1105 wc.border_width = c->bw;
1106 XConfigureWindow(dpy, c->win,
1107 CWX|CWY|CWWidth|CWHeight|CWBorderWidth, &wc);
1114 resizemouse(const Arg *arg) {
1125 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1126 None, cursor[CurResize], CurrentTime) != GrabSuccess)
1128 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->bw - 1, c->h + c->bw - 1);
1132 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
1134 case ConfigureRequest:
1137 handler[ev.type](&ev);
1140 nw = MAX(ev.xmotion.x - ocx - 2 * c->bw + 1, 1);
1141 nh = MAX(ev.xmotion.y - ocy - 2 * c->bw + 1, 1);
1143 if(snap && nw >= wx && nw <= wx + ww
1144 && nh >= wy && nh <= wy + wh) {
1145 if(!c->isfloating && lt[sellt]->arrange
1146 && (abs(nw - c->w) > snap || abs(nh - c->h) > snap))
1147 togglefloating(NULL);
1149 if(!lt[sellt]->arrange || c->isfloating)
1150 resize(c, c->x, c->y, nw, nh, True);
1154 while(ev.type != ButtonRelease);
1157 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->bw - 1, c->h + c->bw - 1);
1158 XUngrabPointer(dpy, CurrentTime);
1159 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1171 if(sel->isfloating || !lt[sellt]->arrange)
1172 XRaiseWindow(dpy, sel->win);
1173 if(lt[sellt]->arrange) {
1174 wc.stack_mode = Below;
1175 wc.sibling = barwin;
1176 for(c = stack; c; c = c->snext)
1177 if(!c->isfloating && ISVISIBLE(c)) {
1178 XConfigureWindow(dpy, c->win, CWSibling|CWStackMode, &wc);
1179 wc.sibling = c->win;
1183 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1190 /* main event loop */
1192 while(running && !XNextEvent(dpy, &ev)) {
1193 if(handler[ev.type])
1194 (handler[ev.type])(&ev); /* call handler */
1200 unsigned int i, num;
1201 Window d1, d2, *wins = NULL;
1202 XWindowAttributes wa;
1204 if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1205 for(i = 0; i < num; i++) {
1206 if(!XGetWindowAttributes(dpy, wins[i], &wa)
1207 || wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1209 if(wa.map_state == IsViewable || getstate(wins[i]) == IconicState)
1210 manage(wins[i], &wa);
1212 for(i = 0; i < num; i++) { /* now the transients */
1213 if(!XGetWindowAttributes(dpy, wins[i], &wa))
1215 if(XGetTransientForHint(dpy, wins[i], &d1)
1216 && (wa.map_state == IsViewable || getstate(wins[i]) == IconicState))
1217 manage(wins[i], &wa);
1225 setclientstate(Client *c, long state) {
1226 long data[] = {state, None};
1228 XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1229 PropModeReplace, (unsigned char *)data, 2);
1233 setlayout(const Arg *arg) {
1234 if(!arg || !arg->v || arg->v != lt[sellt])
1237 lt[sellt] = (Layout *)arg->v;
1244 /* arg > 1.0 will set mfact absolutly */
1246 setmfact(const Arg *arg) {
1249 if(!arg || !lt[sellt]->arrange)
1251 f = arg->f < 1.0 ? arg->f + mfact : arg->f - 1.0;
1252 if(f < 0.1 || f > 0.9)
1262 XSetWindowAttributes wa;
1265 screen = DefaultScreen(dpy);
1266 root = RootWindow(dpy, screen);
1270 sw = DisplayWidth(dpy, screen);
1271 sh = DisplayHeight(dpy, screen);
1272 bh = dc.h = dc.font.height + 2;
1273 lt[0] = &layouts[0];
1274 lt[1] = &layouts[1 % LENGTH(layouts)];
1278 wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1279 wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1280 wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1281 netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1282 netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1285 wa.cursor = cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1286 cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1287 cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1289 /* init appearance */
1290 dc.norm[ColBorder] = getcolor(normbordercolor);
1291 dc.norm[ColBG] = getcolor(normbgcolor);
1292 dc.norm[ColFG] = getcolor(normfgcolor);
1293 dc.sel[ColBorder] = getcolor(selbordercolor);
1294 dc.sel[ColBG] = getcolor(selbgcolor);
1295 dc.sel[ColFG] = getcolor(selfgcolor);
1296 dc.drawable = XCreatePixmap(dpy, root, DisplayWidth(dpy, screen), bh, DefaultDepth(dpy, screen));
1297 dc.gc = XCreateGC(dpy, root, 0, NULL);
1298 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
1300 XSetFont(dpy, dc.gc, dc.font.xfont->fid);
1303 for(blw = i = 0; LENGTH(layouts) > 1 && i < LENGTH(layouts); i++) {
1304 w = TEXTW(layouts[i].symbol);
1308 wa.override_redirect = True;
1309 wa.background_pixmap = ParentRelative;
1310 wa.event_mask = ButtonPressMask|ExposureMask;
1312 barwin = XCreateWindow(dpy, root, wx, by, ww, bh, 0, DefaultDepth(dpy, screen),
1313 CopyFromParent, DefaultVisual(dpy, screen),
1314 CWOverrideRedirect|CWBackPixmap|CWEventMask, &wa);
1315 XDefineCursor(dpy, barwin, cursor[CurNormal]);
1316 XMapRaised(dpy, barwin);
1319 /* EWMH support per view */
1320 XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1321 PropModeReplace, (unsigned char *) netatom, NetLast);
1323 /* select for events */
1324 wa.event_mask = SubstructureRedirectMask|SubstructureNotifyMask|ButtonPressMask
1325 |EnterWindowMask|LeaveWindowMask|StructureNotifyMask
1326 |PropertyChangeMask;
1327 XChangeWindowAttributes(dpy, root, CWEventMask|CWCursor, &wa);
1328 XSelectInput(dpy, root, wa.event_mask);
1334 showhide(Client *c, unsigned int ntiled) {
1337 if(ISVISIBLE(c)) { /* show clients top down */
1338 XMoveWindow(dpy, c->win, c->x, c->y);
1339 if(!lt[sellt]->arrange || c->isfloating)
1340 resize(c, c->x, c->y, c->w, c->h, True);
1341 showhide(c->snext, ntiled);
1343 else { /* hide clients bottom up */
1344 showhide(c->snext, ntiled);
1345 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
1351 sigchld(int signal) {
1352 while(0 < waitpid(-1, NULL, WNOHANG));
1356 spawn(const Arg *arg) {
1357 signal(SIGCHLD, sigchld);
1360 close(ConnectionNumber(dpy));
1362 execvp(((char **)arg->v)[0], (char **)arg->v);
1363 fprintf(stderr, "dwm: execvp %s", ((char **)arg->v)[0]);
1370 tag(const Arg *arg) {
1371 if(sel && arg->ui & TAGMASK) {
1372 sel->tags = arg->ui & TAGMASK;
1378 textnw(const char *text, unsigned int len) {
1382 XmbTextExtents(dc.font.set, text, len, NULL, &r);
1385 return XTextWidth(dc.font.xfont, text, len);
1394 for(n = 0, c = nexttiled(clients); c; c = nexttiled(c->next), n++);
1399 c = nexttiled(clients);
1401 resize(c, wx, wy, (n == 1 ? ww : mw) - 2 * c->bw, wh - 2 * c->bw, resizehints);
1407 x = (wx + mw > c->x + c->w) ? c->x + c->w + 2 * c->bw : wx + mw;
1409 w = (wx + mw > c->x + c->w) ? wx + ww - x : ww - mw;
1414 for(i = 0, c = nexttiled(c->next); c; c = nexttiled(c->next), i++) {
1415 resize(c, x, y, w - 2 * c->bw, /* remainder */ ((i + 1 == n)
1416 ? wy + wh - y - 2 * c->bw : h - 2 * c->bw), resizehints);
1418 y = c->y + HEIGHT(c);
1423 togglebar(const Arg *arg) {
1431 togglefloating(const Arg *arg) {
1434 sel->isfloating = !sel->isfloating || sel->isfixed;
1436 resize(sel, sel->x, sel->y, sel->w, sel->h, True);
1441 toggletag(const Arg *arg) {
1447 mask = sel->tags ^ (arg->ui & TAGMASK);
1455 toggleview(const Arg *arg) {
1456 unsigned int mask = tagset[seltags] ^ (arg->ui & TAGMASK);
1459 tagset[seltags] = mask;
1465 unmanage(Client *c) {
1468 wc.border_width = c->oldbw;
1469 /* The server grab construct avoids race conditions. */
1471 XSetErrorHandler(xerrordummy);
1472 XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
1477 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1478 setclientstate(c, WithdrawnState);
1481 XSetErrorHandler(xerror);
1487 unmapnotify(XEvent *e) {
1489 XUnmapEvent *ev = &e->xunmap;
1491 if((c = getclient(ev->window)))
1497 if(dc.drawable != 0)
1498 XFreePixmap(dpy, dc.drawable);
1499 dc.drawable = XCreatePixmap(dpy, root, ww, bh, DefaultDepth(dpy, screen));
1500 XMoveResizeWindow(dpy, barwin, wx, by, ww, bh);
1507 XineramaScreenInfo *info = NULL;
1509 /* window area geometry */
1510 if(XineramaIsActive(dpy) && (info = XineramaQueryScreens(dpy, &n))) {
1515 if(XQueryPointer(dpy, root, &dummy, &dummy, &x, &y, &di, &di, &dui))
1516 for(i = 0; i < n; i++)
1517 if(INRECT(x, y, info[i].x_org, info[i].y_org, info[i].width, info[i].height))
1521 wy = showbar && topbar ? info[i].y_org + bh : info[i].y_org;
1523 wh = showbar ? info[i].height - bh : info[i].height;
1530 wy = showbar && topbar ? sy + bh : sy;
1532 wh = showbar ? sh - bh : sh;
1536 by = showbar ? (topbar ? wy - bh : wy + wh) : -bh;
1540 updatenumlockmask(void) {
1542 XModifierKeymap *modmap;
1545 modmap = XGetModifierMapping(dpy);
1546 for(i = 0; i < 8; i++)
1547 for(j = 0; j < modmap->max_keypermod; j++)
1548 if(modmap->modifiermap[i * modmap->max_keypermod + j] == XKeysymToKeycode(dpy, XK_Num_Lock))
1549 numlockmask = (1 << i);
1550 XFreeModifiermap(modmap);
1554 updatesizehints(Client *c) {
1558 if(!XGetWMNormalHints(dpy, c->win, &size, &msize))
1559 /* size is uninitialized, ensure that size.flags aren't used */
1561 if(size.flags & PBaseSize) {
1562 c->basew = size.base_width;
1563 c->baseh = size.base_height;
1565 else if(size.flags & PMinSize) {
1566 c->basew = size.min_width;
1567 c->baseh = size.min_height;
1570 c->basew = c->baseh = 0;
1571 if(size.flags & PResizeInc) {
1572 c->incw = size.width_inc;
1573 c->inch = size.height_inc;
1576 c->incw = c->inch = 0;
1577 if(size.flags & PMaxSize) {
1578 c->maxw = size.max_width;
1579 c->maxh = size.max_height;
1582 c->maxw = c->maxh = 0;
1583 if(size.flags & PMinSize) {
1584 c->minw = size.min_width;
1585 c->minh = size.min_height;
1587 else if(size.flags & PBaseSize) {
1588 c->minw = size.base_width;
1589 c->minh = size.base_height;
1592 c->minw = c->minh = 0;
1593 if(size.flags & PAspect) {
1594 c->mina = (float)size.min_aspect.y / (float)size.min_aspect.x;
1595 c->maxa = (float)size.max_aspect.x / (float)size.max_aspect.y;
1598 c->maxa = c->mina = 0.0;
1599 c->isfixed = (c->maxw && c->minw && c->maxh && c->minh
1600 && c->maxw == c->minw && c->maxh == c->minh);
1604 updatetitle(Client *c) {
1605 if(!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
1606 gettextprop(c->win, XA_WM_NAME, c->name, sizeof c->name);
1611 if(!gettextprop(root, XA_WM_NAME, stext, sizeof(stext)))
1612 strcpy(stext, "dwm-"VERSION);
1617 updatewmhints(Client *c) {
1620 if((wmh = XGetWMHints(dpy, c->win))) {
1621 if(c == sel && wmh->flags & XUrgencyHint) {
1622 wmh->flags &= ~XUrgencyHint;
1623 XSetWMHints(dpy, c->win, wmh);
1626 c->isurgent = (wmh->flags & XUrgencyHint) ? True : False;
1633 view(const Arg *arg) {
1634 if((arg->ui & TAGMASK) == tagset[seltags])
1636 seltags ^= 1; /* toggle sel tagset */
1637 if(arg->ui & TAGMASK)
1638 tagset[seltags] = arg->ui & TAGMASK;
1642 /* There's no way to check accesses to destroyed windows, thus those cases are
1643 * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
1644 * default error handler, which may call exit. */
1646 xerror(Display *dpy, XErrorEvent *ee) {
1647 if(ee->error_code == BadWindow
1648 || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1649 || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1650 || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1651 || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1652 || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1653 || (ee->request_code == X_GrabButton && ee->error_code == BadAccess)
1654 || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1655 || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1657 fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1658 ee->request_code, ee->error_code);
1659 return xerrorxlib(dpy, ee); /* may call exit */
1663 xerrordummy(Display *dpy, XErrorEvent *ee) {
1667 /* Startup Error handler to check if another window manager
1668 * is already running. */
1670 xerrorstart(Display *dpy, XErrorEvent *ee) {
1676 zoom(const Arg *arg) {
1679 if(!lt[sellt]->arrange || lt[sellt]->arrange == monocle || (sel && sel->isfloating))
1681 if(c == nexttiled(clients))
1682 if(!c || !(c = nexttiled(c->next)))
1691 main(int argc, char *argv[]) {
1692 if(argc == 2 && !strcmp("-v", argv[1]))
1693 die("dwm-"VERSION", © 2006-2009 dwm engineers, see LICENSE for details\n");
1695 die("usage: dwm [-v]\n");
1697 if(!setlocale(LC_CTYPE, "") || !XSupportsLocale())
1698 fputs("warning: no locale support\n", stderr);
1700 if(!(dpy = XOpenDisplay(NULL)))
1701 die("dwm: cannot open display\n");