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().
30 #include <sys/types.h>
32 #include <X11/cursorfont.h>
33 #include <X11/keysym.h>
34 #include <X11/Xatom.h>
36 #include <X11/Xproto.h>
37 #include <X11/Xutil.h>
39 #include <X11/extensions/Xinerama.h>
43 #define BUTTONMASK (ButtonPressMask|ButtonReleaseMask)
44 #define CLEANMASK(mask) (mask & ~(numlockmask|LockMask))
45 #define INRECT(X,Y,RX,RY,RW,RH) ((X) >= (RX) && (X) < (RX) + (RW) && (Y) >= (RY) && (Y) < (RY) + (RH))
46 #define ISVISIBLE(x) (x->tags & tagset[seltags])
47 #define LENGTH(x) (sizeof x / sizeof x[0])
48 #define MAX(a, b) ((a) > (b) ? (a) : (b))
49 #define MIN(a, b) ((a) < (b) ? (a) : (b))
51 #define MOUSEMASK (BUTTONMASK|PointerMotionMask)
52 #define WIDTH(x) ((x)->w + 2 * (x)->bw)
53 #define HEIGHT(x) ((x)->h + 2 * (x)->bw)
54 #define TAGMASK ((int)((1LL << LENGTH(tags)) - 1))
55 #define TEXTW(x) (textnw(x, strlen(x)) + dc.font.height)
58 enum { CurNormal, CurResize, CurMove, CurLast }; /* cursor */
59 enum { ColBorder, ColFG, ColBG, ColLast }; /* color */
60 enum { NetSupported, NetWMName, NetLast }; /* EWMH atoms */
61 enum { WMProtocols, WMDelete, WMState, WMLast }; /* default atoms */
62 enum { ClkTagBar, ClkLtSymbol, ClkStatusText, ClkWinTitle,
63 ClkClientWin, ClkRootWin, ClkLast }; /* clicks */
76 void (*func)(const Arg *arg);
80 typedef struct Client Client;
85 int basew, baseh, incw, inch, maxw, maxh, minw, minh;
88 Bool isfixed, isfloating, isurgent;
96 unsigned long norm[ColLast];
97 unsigned long sel[ColLast];
107 } DC; /* draw context */
112 void (*func)(const Arg *);
118 void (*arrange)(void);
123 const char *instance;
129 /* function declarations */
130 static void applyrules(Client *c);
131 static void arrange(void);
132 static void attach(Client *c);
133 static void attachstack(Client *c);
134 static void buttonpress(XEvent *e);
135 static void checkotherwm(void);
136 static void cleanup(void);
137 static void clearurgent(Client *c);
138 static void configure(Client *c);
139 static void configurenotify(XEvent *e);
140 static void configurerequest(XEvent *e);
141 static void destroynotify(XEvent *e);
142 static void detach(Client *c);
143 static void detachstack(Client *c);
144 static void die(const char *errstr, ...);
145 static void drawbar(void);
146 static void drawsquare(Bool filled, Bool empty, Bool invert, unsigned long col[ColLast]);
147 static void drawtext(const char *text, unsigned long col[ColLast], Bool invert);
148 static void enternotify(XEvent *e);
149 static void expose(XEvent *e);
150 static void focus(Client *c);
151 static void focusin(XEvent *e);
152 static void focusstack(const Arg *arg);
153 static Client *getclient(Window w);
154 static unsigned long getcolor(const char *colstr);
155 static long getstate(Window w);
156 static Bool gettextprop(Window w, Atom atom, char *text, unsigned int size);
157 static void grabbuttons(Client *c, Bool focused);
158 static void grabkeys(void);
159 static void initfont(const char *fontstr);
160 static Bool isprotodel(Client *c);
161 static void keypress(XEvent *e);
162 static void killclient(const Arg *arg);
163 static void manage(Window w, XWindowAttributes *wa);
164 static void mappingnotify(XEvent *e);
165 static void maprequest(XEvent *e);
166 static void monocle(void);
167 static void movemouse(const Arg *arg);
168 static Client *nexttiled(Client *c);
169 static void propertynotify(XEvent *e);
170 static void quit(const Arg *arg);
171 static void resize(Client *c, int x, int y, int w, int h, Bool sizehints);
172 static void resizemouse(const Arg *arg);
173 static void restack(void);
174 static void run(void);
175 static void scan(void);
176 static void setclientstate(Client *c, long state);
177 static void setlayout(const Arg *arg);
178 static void setmfact(const Arg *arg);
179 static void setup(void);
180 static void showhide(Client *c);
181 static void spawn(const Arg *arg);
182 static void tag(const Arg *arg);
183 static int textnw(const char *text, unsigned int len);
184 static void tile(void);
185 static void togglebar(const Arg *arg);
186 static void togglefloating(const Arg *arg);
187 static void toggletag(const Arg *arg);
188 static void toggleview(const Arg *arg);
189 static void unmanage(Client *c);
190 static void unmapnotify(XEvent *e);
191 static void updatebar(void);
192 static void updategeom(void);
193 static void updatenumlockmask(void);
194 static void updatesizehints(Client *c);
195 static void updatestatus(void);
196 static void updatetitle(Client *c);
197 static void updatewmhints(Client *c);
198 static void view(const Arg *arg);
199 static int xerror(Display *dpy, XErrorEvent *ee);
200 static int xerrordummy(Display *dpy, XErrorEvent *ee);
201 static int xerrorstart(Display *dpy, XErrorEvent *ee);
202 static void zoom(const Arg *arg);
205 static char stext[256];
207 static int sx, sy, sw, sh; /* X display screen geometry x, y, width, height */
208 static int by, bh, blw; /* bar geometry y, height and layout symbol width */
209 static int wx, wy, ww, wh; /* window area geometry x, y, width, height, bar excluded */
210 static unsigned int seltags = 0, sellt = 0;
211 static int (*xerrorxlib)(Display *, XErrorEvent *);
212 static unsigned int numlockmask = 0;
213 static void (*handler[LASTEvent]) (XEvent *) = {
214 [ButtonPress] = buttonpress,
215 [ConfigureRequest] = configurerequest,
216 [ConfigureNotify] = configurenotify,
217 [DestroyNotify] = destroynotify,
218 [EnterNotify] = enternotify,
221 [KeyPress] = keypress,
222 [MappingNotify] = mappingnotify,
223 [MapRequest] = maprequest,
224 [PropertyNotify] = propertynotify,
225 [UnmapNotify] = unmapnotify
227 static Atom wmatom[WMLast], netatom[NetLast];
229 static Bool running = True;
230 static Client *clients = NULL;
231 static Client *sel = NULL;
232 static Client *stack = NULL;
233 static Cursor cursor[CurLast];
236 static Layout *lt[] = { NULL, NULL };
237 static Window root, barwin;
238 /* configuration, allows nested code to access above variables */
241 /* compile-time check if all tags fit into an unsigned int bit array. */
242 struct NumTags { char limitexceeded[sizeof(unsigned int) * 8 < LENGTH(tags) ? -1 : 1]; };
244 /* function implementations */
246 applyrules(Client *c) {
249 XClassHint ch = { 0 };
252 if(XGetClassHint(dpy, c->win, &ch)) {
253 for(i = 0; i < LENGTH(rules); i++) {
255 if((!r->title || strstr(c->name, r->title))
256 && (!r->class || (ch.res_class && strstr(ch.res_class, r->class)))
257 && (!r->instance || (ch.res_name && strstr(ch.res_name, r->instance)))) {
258 c->isfloating = r->isfloating;
259 c->tags |= r->tags & TAGMASK;
268 c->tags = tagset[seltags];
275 if(lt[sellt]->arrange)
276 lt[sellt]->arrange();
287 attachstack(Client *c) {
293 buttonpress(XEvent *e) {
294 unsigned int i, x, click;
297 XButtonPressedEvent *ev = &e->xbutton;
300 if(ev->window == barwin) {
302 do x += TEXTW(tags[i]); while(ev->x >= x && ++i < LENGTH(tags));
303 if(i < LENGTH(tags)) {
307 else if(ev->x < x + blw)
309 else if(ev->x > wx + ww - TEXTW(stext))
310 click = ClkStatusText;
314 else if((c = getclient(ev->window))) {
316 click = ClkClientWin;
319 for(i = 0; i < LENGTH(buttons); i++)
320 if(click == buttons[i].click && buttons[i].func && buttons[i].button == ev->button
321 && CLEANMASK(buttons[i].mask) == CLEANMASK(ev->state))
322 buttons[i].func(click == ClkTagBar && buttons[i].arg.i == 0 ? &arg : &buttons[i].arg);
328 xerrorxlib = XSetErrorHandler(xerrorstart);
330 /* this causes an error if some other window manager is running */
331 XSelectInput(dpy, DefaultRootWindow(dpy), SubstructureRedirectMask);
334 die("dwm: another window manager is already running\n");
335 XSetErrorHandler(xerror);
342 Layout foo = { "", NULL };
350 XFreeFontSet(dpy, dc.font.set);
352 XFreeFont(dpy, dc.font.xfont);
353 XUngrabKey(dpy, AnyKey, AnyModifier, root);
354 XFreePixmap(dpy, dc.drawable);
356 XFreeCursor(dpy, cursor[CurNormal]);
357 XFreeCursor(dpy, cursor[CurResize]);
358 XFreeCursor(dpy, cursor[CurMove]);
359 XDestroyWindow(dpy, barwin);
361 XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime);
365 clearurgent(Client *c) {
369 if(!(wmh = XGetWMHints(dpy, c->win)))
371 wmh->flags &= ~XUrgencyHint;
372 XSetWMHints(dpy, c->win, wmh);
377 configure(Client *c) {
380 ce.type = ConfigureNotify;
388 ce.border_width = c->bw;
390 ce.override_redirect = False;
391 XSendEvent(dpy, c->win, False, StructureNotifyMask, (XEvent *)&ce);
395 configurenotify(XEvent *e) {
396 XConfigureEvent *ev = &e->xconfigure;
398 if(ev->window == root && (ev->width != sw || ev->height != sh)) {
408 configurerequest(XEvent *e) {
410 XConfigureRequestEvent *ev = &e->xconfigurerequest;
413 if((c = getclient(ev->window))) {
414 if(ev->value_mask & CWBorderWidth)
415 c->bw = ev->border_width;
416 else if(c->isfloating || !lt[sellt]->arrange) {
417 if(ev->value_mask & CWX)
419 if(ev->value_mask & CWY)
421 if(ev->value_mask & CWWidth)
423 if(ev->value_mask & CWHeight)
425 if((c->x - sx + c->w) > sw && c->isfloating)
426 c->x = sx + (sw / 2 - c->w / 2); /* center in x direction */
427 if((c->y - sy + c->h) > sh && c->isfloating)
428 c->y = sy + (sh / 2 - c->h / 2); /* center in y direction */
429 if((ev->value_mask & (CWX|CWY)) && !(ev->value_mask & (CWWidth|CWHeight)))
432 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h);
440 wc.width = ev->width;
441 wc.height = ev->height;
442 wc.border_width = ev->border_width;
443 wc.sibling = ev->above;
444 wc.stack_mode = ev->detail;
445 XConfigureWindow(dpy, ev->window, ev->value_mask, &wc);
451 destroynotify(XEvent *e) {
453 XDestroyWindowEvent *ev = &e->xdestroywindow;
455 if((c = getclient(ev->window)))
463 for(tc = &clients; *tc && *tc != c; tc = &(*tc)->next);
468 detachstack(Client *c) {
471 for(tc = &stack; *tc && *tc != c; tc = &(*tc)->snext);
476 die(const char *errstr, ...) {
479 va_start(ap, errstr);
480 vfprintf(stderr, errstr, ap);
488 unsigned int i, occ = 0, urg = 0;
492 for(c = clients; c; c = c->next) {
499 for(i = 0; i < LENGTH(tags); i++) {
500 dc.w = TEXTW(tags[i]);
501 col = tagset[seltags] & 1 << i ? dc.sel : dc.norm;
502 drawtext(tags[i], col, urg & 1 << i);
503 drawsquare(sel && sel->tags & 1 << i, occ & 1 << i, urg & 1 << i, col);
508 drawtext(lt[sellt]->symbol, dc.norm, False);
519 drawtext(stext, dc.norm, False);
520 if((dc.w = dc.x - x) > bh) {
523 drawtext(sel->name, dc.sel, False);
524 drawsquare(sel->isfixed, sel->isfloating, False, dc.sel);
527 drawtext(NULL, dc.norm, False);
529 XCopyArea(dpy, dc.drawable, barwin, dc.gc, 0, 0, ww, bh, 0, 0);
534 drawsquare(Bool filled, Bool empty, Bool invert, unsigned long col[ColLast]) {
537 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
539 gcv.foreground = col[invert ? ColBG : ColFG];
540 XChangeGC(dpy, dc.gc, GCForeground, &gcv);
541 x = (dc.font.ascent + dc.font.descent + 2) / 4;
545 r.width = r.height = x + 1;
546 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
549 r.width = r.height = x;
550 XDrawRectangles(dpy, dc.drawable, dc.gc, &r, 1);
555 drawtext(const char *text, unsigned long col[ColLast], Bool invert) {
557 int i, x, y, h, len, olen;
558 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
560 XSetForeground(dpy, dc.gc, col[invert ? ColFG : ColBG]);
561 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
565 h = dc.font.ascent + dc.font.descent;
566 y = dc.y + (dc.h / 2) - (h / 2) + dc.font.ascent;
568 /* shorten text if necessary */
569 for(len = MIN(olen, sizeof buf); len && textnw(text, len) > dc.w - h; len--);
572 memcpy(buf, text, len);
574 for(i = len; i && i > len - 3; buf[--i] = '.');
575 XSetForeground(dpy, dc.gc, col[invert ? ColBG : ColFG]);
577 XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
579 XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
583 enternotify(XEvent *e) {
585 XCrossingEvent *ev = &e->xcrossing;
587 if((ev->mode != NotifyNormal || ev->detail == NotifyInferior) && ev->window != root)
589 if((c = getclient(ev->window)))
597 XExposeEvent *ev = &e->xexpose;
599 if(ev->count == 0 && (ev->window == barwin))
605 if(!c || !ISVISIBLE(c))
606 for(c = stack; c && !ISVISIBLE(c); c = c->snext);
607 if(sel && sel != c) {
608 grabbuttons(sel, False);
609 XSetWindowBorder(dpy, sel->win, dc.norm[ColBorder]);
616 grabbuttons(c, True);
617 XSetWindowBorder(dpy, c->win, dc.sel[ColBorder]);
618 XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
621 XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
627 focusin(XEvent *e) { /* there are some broken focus acquiring clients */
628 XFocusChangeEvent *ev = &e->xfocus;
630 if(sel && ev->window != sel->win)
631 XSetInputFocus(dpy, sel->win, RevertToPointerRoot, CurrentTime);
635 focusstack(const Arg *arg) {
636 Client *c = NULL, *i;
641 for(c = sel->next; c && !ISVISIBLE(c); c = c->next);
643 for(c = clients; c && !ISVISIBLE(c); c = c->next);
646 for(i = clients; i != sel; i = i->next)
650 for(; i; i = i->next)
661 getclient(Window w) {
664 for(c = clients; c && c->win != w; c = c->next);
669 getcolor(const char *colstr) {
670 Colormap cmap = DefaultColormap(dpy, screen);
673 if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
674 die("error, cannot allocate color '%s'\n", colstr);
682 unsigned char *p = NULL;
683 unsigned long n, extra;
686 status = XGetWindowProperty(dpy, w, wmatom[WMState], 0L, 2L, False, wmatom[WMState],
687 &real, &format, &n, &extra, (unsigned char **)&p);
688 if(status != Success)
697 gettextprop(Window w, Atom atom, char *text, unsigned int size) {
702 if(!text || size == 0)
705 XGetTextProperty(dpy, w, &name, atom);
708 if(name.encoding == XA_STRING)
709 strncpy(text, (char *)name.value, size - 1);
711 if(XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success
713 strncpy(text, *list, size - 1);
714 XFreeStringList(list);
717 text[size - 1] = '\0';
723 grabbuttons(Client *c, Bool focused) {
727 unsigned int modifiers[] = { 0, LockMask, numlockmask, numlockmask|LockMask };
728 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
730 for(i = 0; i < LENGTH(buttons); i++)
731 if(buttons[i].click == ClkClientWin)
732 for(j = 0; j < LENGTH(modifiers); j++)
733 XGrabButton(dpy, buttons[i].button, buttons[i].mask | modifiers[j], c->win, False, BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
735 XGrabButton(dpy, AnyButton, AnyModifier, c->win, False,
736 BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
745 unsigned int modifiers[] = { 0, LockMask, numlockmask, numlockmask|LockMask };
748 XUngrabKey(dpy, AnyKey, AnyModifier, root);
749 for(i = 0; i < LENGTH(keys); i++) {
750 if((code = XKeysymToKeycode(dpy, keys[i].keysym)))
751 for(j = 0; j < LENGTH(modifiers); j++)
752 XGrabKey(dpy, code, keys[i].mod | modifiers[j], root,
753 True, GrabModeAsync, GrabModeAsync);
759 initfont(const char *fontstr) {
760 char *def, **missing;
764 dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
767 fprintf(stderr, "dwm: missing fontset: %s\n", missing[n]);
768 XFreeStringList(missing);
771 XFontSetExtents *font_extents;
772 XFontStruct **xfonts;
774 dc.font.ascent = dc.font.descent = 0;
775 font_extents = XExtentsOfFontSet(dc.font.set);
776 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
777 for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
778 dc.font.ascent = MAX(dc.font.ascent, (*xfonts)->ascent);
779 dc.font.descent = MAX(dc.font.descent,(*xfonts)->descent);
784 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr))
785 && !(dc.font.xfont = XLoadQueryFont(dpy, "fixed")))
786 die("error, cannot load font: '%s'\n", fontstr);
787 dc.font.ascent = dc.font.xfont->ascent;
788 dc.font.descent = dc.font.xfont->descent;
790 dc.font.height = dc.font.ascent + dc.font.descent;
794 isprotodel(Client *c) {
799 if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
800 for(i = 0; !ret && i < n; i++)
801 if(protocols[i] == wmatom[WMDelete])
809 keypress(XEvent *e) {
815 keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
816 for(i = 0; i < LENGTH(keys); i++)
817 if(keysym == keys[i].keysym
818 && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state)
820 keys[i].func(&(keys[i].arg));
824 killclient(const Arg *arg) {
829 if(isprotodel(sel)) {
830 ev.type = ClientMessage;
831 ev.xclient.window = sel->win;
832 ev.xclient.message_type = wmatom[WMProtocols];
833 ev.xclient.format = 32;
834 ev.xclient.data.l[0] = wmatom[WMDelete];
835 ev.xclient.data.l[1] = CurrentTime;
836 XSendEvent(dpy, sel->win, False, NoEventMask, &ev);
839 XKillClient(dpy, sel->win);
843 manage(Window w, XWindowAttributes *wa) {
845 Client *c, *t = NULL;
849 if(!(c = malloc(sizeof(Client))))
850 die("fatal: could not malloc() %u bytes\n", sizeof(Client));
859 c->oldbw = wa->border_width;
860 if(c->w == sw && c->h == sh) {
866 if(c->x + WIDTH(c) > sx + sw)
867 c->x = sx + sw - WIDTH(c);
868 if(c->y + HEIGHT(c) > sy + sh)
869 c->y = sy + sh - HEIGHT(c);
870 c->x = MAX(c->x, sx);
871 /* only fix client y-offset, if the client center might cover the bar */
872 c->y = MAX(c->y, ((by == 0) && (c->x + (c->w / 2) >= wx) && (c->x + (c->w / 2) < wx + ww)) ? bh : sy);
876 wc.border_width = c->bw;
877 XConfigureWindow(dpy, w, CWBorderWidth, &wc);
878 XSetWindowBorder(dpy, w, dc.norm[ColBorder]);
879 configure(c); /* propagates border_width, if size doesn't change */
881 XSelectInput(dpy, w, EnterWindowMask|FocusChangeMask|PropertyChangeMask|StructureNotifyMask);
882 grabbuttons(c, False);
884 if(XGetTransientForHint(dpy, w, &trans))
885 t = getclient(trans);
891 c->isfloating = trans != None || c->isfixed;
893 XRaiseWindow(dpy, c->win);
896 XMoveResizeWindow(dpy, c->win, c->x + 2 * sw, c->y, c->w, c->h); /* some windows require this */
897 XMapWindow(dpy, c->win);
898 setclientstate(c, NormalState);
903 mappingnotify(XEvent *e) {
904 XMappingEvent *ev = &e->xmapping;
906 XRefreshKeyboardMapping(ev);
907 if(ev->request == MappingKeyboard)
912 maprequest(XEvent *e) {
913 static XWindowAttributes wa;
914 XMapRequestEvent *ev = &e->xmaprequest;
916 if(!XGetWindowAttributes(dpy, ev->window, &wa))
918 if(wa.override_redirect)
920 if(!getclient(ev->window))
921 manage(ev->window, &wa);
928 for(c = nexttiled(clients); c; c = nexttiled(c->next))
929 resize(c, wx, wy, ww - 2 * c->bw, wh - 2 * c->bw, resizehints);
933 movemouse(const Arg *arg) {
934 int x, y, ocx, ocy, di, nx, ny;
945 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
946 None, cursor[CurMove], CurrentTime) != GrabSuccess)
948 XQueryPointer(dpy, root, &dummy, &dummy, &x, &y, &di, &di, &dui);
952 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
954 case ConfigureRequest:
957 handler[ev.type](&ev);
960 nx = ocx + (ev.xmotion.x - x);
961 ny = ocy + (ev.xmotion.y - y);
962 if(snap && nx >= wx && nx <= wx + ww
963 && ny >= wy && ny <= wy + wh) {
964 if(abs(wx - nx) < snap)
966 else if(abs((wx + ww) - (nx + WIDTH(c))) < snap)
967 nx = wx + ww - WIDTH(c);
968 if(abs(wy - ny) < snap)
970 else if(abs((wy + wh) - (ny + HEIGHT(c))) < snap)
971 ny = wy + wh - HEIGHT(c);
972 if(!c->isfloating && lt[sellt]->arrange && (abs(nx - c->x) > snap || abs(ny - c->y) > snap))
973 togglefloating(NULL);
975 if(!lt[sellt]->arrange || c->isfloating)
976 resize(c, nx, ny, c->w, c->h, False);
980 while(ev.type != ButtonRelease);
983 XUngrabPointer(dpy, CurrentTime);
987 nexttiled(Client *c) {
988 for(; c && (c->isfloating || !ISVISIBLE(c)); c = c->next);
993 propertynotify(XEvent *e) {
996 XPropertyEvent *ev = &e->xproperty;
998 if((ev->window == root) && (ev->atom = XA_WM_NAME))
1000 else if(ev->state == PropertyDelete)
1001 return; /* ignore */
1002 else if((c = getclient(ev->window))) {
1005 case XA_WM_TRANSIENT_FOR:
1006 XGetTransientForHint(dpy, c->win, &trans);
1007 if(!c->isfloating && (c->isfloating = (getclient(trans) != NULL)))
1010 case XA_WM_NORMAL_HINTS:
1018 if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
1027 quit(const Arg *arg) {
1032 resize(Client *c, int x, int y, int w, int h, Bool sizehints) {
1036 /* see last two sentences in ICCCM 4.1.2.3 */
1037 Bool baseismin = c->basew == c->minw && c->baseh == c->minh;
1039 /* set minimum possible */
1043 if(!baseismin) { /* temporarily remove base dimensions */
1048 /* adjust for aspect limits */
1049 if(c->mina > 0 && c->maxa > 0) {
1050 if(c->maxa < (float)w / h)
1052 else if(c->mina < (float)h / w)
1056 if(baseismin) { /* increment calculation requires this */
1061 /* adjust for increment value */
1067 /* restore base dimensions */
1071 w = MAX(w, c->minw);
1072 h = MAX(h, c->minh);
1075 w = MIN(w, c->maxw);
1078 h = MIN(h, c->maxh);
1080 if(w <= 0 || h <= 0)
1086 if(x + w + 2 * c->bw < sx)
1088 if(y + h + 2 * c->bw < sy)
1094 if(c->x != x || c->y != y || c->w != w || c->h != h) {
1097 c->w = wc.width = w;
1098 c->h = wc.height = h;
1099 wc.border_width = c->bw;
1100 XConfigureWindow(dpy, c->win,
1101 CWX|CWY|CWWidth|CWHeight|CWBorderWidth, &wc);
1108 resizemouse(const Arg *arg) {
1119 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1120 None, cursor[CurResize], CurrentTime) != GrabSuccess)
1122 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->bw - 1, c->h + c->bw - 1);
1126 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
1128 case ConfigureRequest:
1131 handler[ev.type](&ev);
1134 nw = MAX(ev.xmotion.x - ocx - 2*c->bw + 1, 1);
1135 nh = MAX(ev.xmotion.y - ocy - 2*c->bw + 1, 1);
1137 if(snap && nw >= wx && nw <= wx + ww
1138 && nh >= wy && nh <= wy + wh) {
1139 if(!c->isfloating && lt[sellt]->arrange
1140 && (abs(nw - c->w) > snap || abs(nh - c->h) > snap))
1141 togglefloating(NULL);
1143 if(!lt[sellt]->arrange || c->isfloating)
1144 resize(c, c->x, c->y, nw, nh, True);
1148 while(ev.type != ButtonRelease);
1151 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->bw - 1, c->h + c->bw - 1);
1152 XUngrabPointer(dpy, CurrentTime);
1153 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1165 if(sel->isfloating || !lt[sellt]->arrange)
1166 XRaiseWindow(dpy, sel->win);
1167 if(lt[sellt]->arrange) {
1168 wc.stack_mode = Below;
1169 wc.sibling = barwin;
1170 for(c = stack; c; c = c->snext)
1171 if(!c->isfloating && ISVISIBLE(c)) {
1172 XConfigureWindow(dpy, c->win, CWSibling|CWStackMode, &wc);
1173 wc.sibling = c->win;
1177 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1184 /* main event loop */
1186 while(running && !XNextEvent(dpy, &ev)) {
1187 if(handler[ev.type])
1188 (handler[ev.type])(&ev); /* call handler */
1194 unsigned int i, num;
1195 Window d1, d2, *wins = NULL;
1196 XWindowAttributes wa;
1198 if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1199 for(i = 0; i < num; i++) {
1200 if(!XGetWindowAttributes(dpy, wins[i], &wa)
1201 || wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1203 if(wa.map_state == IsViewable || getstate(wins[i]) == IconicState)
1204 manage(wins[i], &wa);
1206 for(i = 0; i < num; i++) { /* now the transients */
1207 if(!XGetWindowAttributes(dpy, wins[i], &wa))
1209 if(XGetTransientForHint(dpy, wins[i], &d1)
1210 && (wa.map_state == IsViewable || getstate(wins[i]) == IconicState))
1211 manage(wins[i], &wa);
1219 setclientstate(Client *c, long state) {
1220 long data[] = {state, None};
1222 XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1223 PropModeReplace, (unsigned char *)data, 2);
1227 setlayout(const Arg *arg) {
1228 if(!arg || !arg->v || arg->v != lt[sellt])
1231 lt[sellt] = (Layout *)arg->v;
1238 /* arg > 1.0 will set mfact absolutly */
1240 setmfact(const Arg *arg) {
1243 if(!arg || !lt[sellt]->arrange)
1245 f = arg->f < 1.0 ? arg->f + mfact : arg->f - 1.0;
1246 if(f < 0.1 || f > 0.9)
1256 XSetWindowAttributes wa;
1259 screen = DefaultScreen(dpy);
1260 root = RootWindow(dpy, screen);
1264 sw = DisplayWidth(dpy, screen);
1265 sh = DisplayHeight(dpy, screen);
1266 bh = dc.h = dc.font.height + 2;
1267 lt[0] = &layouts[0];
1268 lt[1] = &layouts[1 % LENGTH(layouts)];
1272 wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1273 wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1274 wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1275 netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1276 netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1279 wa.cursor = cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1280 cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1281 cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1283 /* init appearance */
1284 dc.norm[ColBorder] = getcolor(normbordercolor);
1285 dc.norm[ColBG] = getcolor(normbgcolor);
1286 dc.norm[ColFG] = getcolor(normfgcolor);
1287 dc.sel[ColBorder] = getcolor(selbordercolor);
1288 dc.sel[ColBG] = getcolor(selbgcolor);
1289 dc.sel[ColFG] = getcolor(selfgcolor);
1290 dc.drawable = XCreatePixmap(dpy, root, DisplayWidth(dpy, screen), bh, DefaultDepth(dpy, screen));
1291 dc.gc = XCreateGC(dpy, root, 0, 0);
1292 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
1294 XSetFont(dpy, dc.gc, dc.font.xfont->fid);
1297 for(blw = i = 0; LENGTH(layouts) > 1 && i < LENGTH(layouts); i++) {
1298 w = TEXTW(layouts[i].symbol);
1302 wa.override_redirect = 1;
1303 wa.background_pixmap = ParentRelative;
1304 wa.event_mask = ButtonPressMask|ExposureMask;
1306 barwin = XCreateWindow(dpy, root, wx, by, ww, bh, 0, DefaultDepth(dpy, screen),
1307 CopyFromParent, DefaultVisual(dpy, screen),
1308 CWOverrideRedirect|CWBackPixmap|CWEventMask, &wa);
1309 XDefineCursor(dpy, barwin, cursor[CurNormal]);
1310 XMapRaised(dpy, barwin);
1313 /* EWMH support per view */
1314 XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1315 PropModeReplace, (unsigned char *) netatom, NetLast);
1317 /* select for events */
1318 wa.event_mask = SubstructureRedirectMask|SubstructureNotifyMask|ButtonPressMask
1319 |EnterWindowMask|LeaveWindowMask|StructureNotifyMask
1320 |PropertyChangeMask;
1321 XChangeWindowAttributes(dpy, root, CWEventMask|CWCursor, &wa);
1322 XSelectInput(dpy, root, wa.event_mask);
1328 showhide(Client *c) {
1331 if(ISVISIBLE(c)) { /* show clients top down */
1332 XMoveWindow(dpy, c->win, c->x, c->y);
1333 if(!lt[sellt]->arrange || c->isfloating)
1334 resize(c, c->x, c->y, c->w, c->h, True);
1337 else { /* hide clients bottom up */
1339 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
1344 spawn(const Arg *arg) {
1345 /* The double-fork construct avoids zombie processes and keeps the code
1346 * clean from stupid signal handlers. */
1350 close(ConnectionNumber(dpy));
1352 execvp(((char **)arg->v)[0], (char **)arg->v);
1353 fprintf(stderr, "dwm: execvp %s", ((char **)arg->v)[0]);
1362 tag(const Arg *arg) {
1363 if(sel && arg->ui & TAGMASK) {
1364 sel->tags = arg->ui & TAGMASK;
1370 textnw(const char *text, unsigned int len) {
1374 XmbTextExtents(dc.font.set, text, len, NULL, &r);
1377 return XTextWidth(dc.font.xfont, text, len);
1386 for(n = 0, c = nexttiled(clients); c; c = nexttiled(c->next), n++);
1391 c = nexttiled(clients);
1393 resize(c, wx, wy, (n == 1 ? ww : mw) - 2 * c->bw, wh - 2 * c->bw, resizehints);
1399 x = (wx + mw > c->x + c->w) ? c->x + c->w + 2 * c->bw : wx + mw;
1401 w = (wx + mw > c->x + c->w) ? wx + ww - x : ww - mw;
1406 for(i = 0, c = nexttiled(c->next); c; c = nexttiled(c->next), i++) {
1407 resize(c, x, y, w - 2 * c->bw, /* remainder */ ((i + 1 == n)
1408 ? wy + wh - y - 2 * c->bw : h - 2 * c->bw), resizehints);
1410 y = c->y + HEIGHT(c);
1415 togglebar(const Arg *arg) {
1423 togglefloating(const Arg *arg) {
1426 sel->isfloating = !sel->isfloating || sel->isfixed;
1428 resize(sel, sel->x, sel->y, sel->w, sel->h, True);
1433 toggletag(const Arg *arg) {
1439 mask = sel->tags ^ (arg->ui & TAGMASK);
1447 toggleview(const Arg *arg) {
1448 unsigned int mask = tagset[seltags] ^ (arg->ui & TAGMASK);
1451 tagset[seltags] = mask;
1457 unmanage(Client *c) {
1460 wc.border_width = c->oldbw;
1461 /* The server grab construct avoids race conditions. */
1463 XSetErrorHandler(xerrordummy);
1464 XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
1469 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1470 setclientstate(c, WithdrawnState);
1473 XSetErrorHandler(xerror);
1479 unmapnotify(XEvent *e) {
1481 XUnmapEvent *ev = &e->xunmap;
1483 if((c = getclient(ev->window)))
1489 if(dc.drawable != 0)
1490 XFreePixmap(dpy, dc.drawable);
1491 dc.drawable = XCreatePixmap(dpy, root, ww, bh, DefaultDepth(dpy, screen));
1492 XMoveResizeWindow(dpy, barwin, wx, by, ww, bh);
1499 XineramaScreenInfo *info = NULL;
1501 /* window area geometry */
1502 if(XineramaIsActive(dpy) && (info = XineramaQueryScreens(dpy, &n))) {
1507 if(XQueryPointer(dpy, root, &dummy, &dummy, &x, &y, &di, &di, &dui))
1508 for(i = 0; i < n; i++)
1509 if(INRECT(x, y, info[i].x_org, info[i].y_org, info[i].width, info[i].height))
1513 wy = showbar && topbar ? info[i].y_org + bh : info[i].y_org;
1515 wh = showbar ? info[i].height - bh : info[i].height;
1522 wy = showbar && topbar ? sy + bh : sy;
1524 wh = showbar ? sh - bh : sh;
1528 by = showbar ? (topbar ? wy - bh : wy + wh) : -bh;
1532 updatenumlockmask(void) {
1534 XModifierKeymap *modmap;
1537 modmap = XGetModifierMapping(dpy);
1538 for(i = 0; i < 8; i++)
1539 for(j = 0; j < modmap->max_keypermod; j++)
1540 if(modmap->modifiermap[i * modmap->max_keypermod + j] == XKeysymToKeycode(dpy, XK_Num_Lock))
1541 numlockmask = (1 << i);
1542 XFreeModifiermap(modmap);
1546 updatesizehints(Client *c) {
1550 if(!XGetWMNormalHints(dpy, c->win, &size, &msize))
1551 /* size is uninitialized, ensure that size.flags aren't used */
1553 if(size.flags & PBaseSize) {
1554 c->basew = size.base_width;
1555 c->baseh = size.base_height;
1557 else if(size.flags & PMinSize) {
1558 c->basew = size.min_width;
1559 c->baseh = size.min_height;
1562 c->basew = c->baseh = 0;
1563 if(size.flags & PResizeInc) {
1564 c->incw = size.width_inc;
1565 c->inch = size.height_inc;
1568 c->incw = c->inch = 0;
1569 if(size.flags & PMaxSize) {
1570 c->maxw = size.max_width;
1571 c->maxh = size.max_height;
1574 c->maxw = c->maxh = 0;
1575 if(size.flags & PMinSize) {
1576 c->minw = size.min_width;
1577 c->minh = size.min_height;
1579 else if(size.flags & PBaseSize) {
1580 c->minw = size.base_width;
1581 c->minh = size.base_height;
1584 c->minw = c->minh = 0;
1585 if(size.flags & PAspect) {
1586 c->mina = (float)size.min_aspect.y / (float)size.min_aspect.x;
1587 c->maxa = (float)size.max_aspect.x / (float)size.max_aspect.y;
1590 c->maxa = c->mina = 0.0;
1591 c->isfixed = (c->maxw && c->minw && c->maxh && c->minh
1592 && c->maxw == c->minw && c->maxh == c->minh);
1596 updatetitle(Client *c) {
1597 if(!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
1598 gettextprop(c->win, XA_WM_NAME, c->name, sizeof c->name);
1603 if(!gettextprop(root, XA_WM_NAME, stext, sizeof(stext)))
1604 strcpy(stext, "dwm-"VERSION);
1609 updatewmhints(Client *c) {
1612 if((wmh = XGetWMHints(dpy, c->win))) {
1613 if(c == sel && wmh->flags & XUrgencyHint) {
1614 wmh->flags &= ~XUrgencyHint;
1615 XSetWMHints(dpy, c->win, wmh);
1618 c->isurgent = (wmh->flags & XUrgencyHint) ? True : False;
1625 view(const Arg *arg) {
1626 if((arg->ui & TAGMASK) == tagset[seltags])
1628 seltags ^= 1; /* toggle sel tagset */
1629 if(arg->ui & TAGMASK)
1630 tagset[seltags] = arg->ui & TAGMASK;
1634 /* There's no way to check accesses to destroyed windows, thus those cases are
1635 * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
1636 * default error handler, which may call exit. */
1638 xerror(Display *dpy, XErrorEvent *ee) {
1639 if(ee->error_code == BadWindow
1640 || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1641 || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1642 || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1643 || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1644 || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1645 || (ee->request_code == X_GrabButton && ee->error_code == BadAccess)
1646 || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1647 || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1649 fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1650 ee->request_code, ee->error_code);
1651 return xerrorxlib(dpy, ee); /* may call exit */
1655 xerrordummy(Display *dpy, XErrorEvent *ee) {
1659 /* Startup Error handler to check if another window manager
1660 * is already running. */
1662 xerrorstart(Display *dpy, XErrorEvent *ee) {
1668 zoom(const Arg *arg) {
1671 if(!lt[sellt]->arrange || lt[sellt]->arrange == monocle || (sel && sel->isfloating))
1673 if(c == nexttiled(clients))
1674 if(!c || !(c = nexttiled(c->next)))
1683 main(int argc, char *argv[]) {
1684 if(argc == 2 && !strcmp("-v", argv[1]))
1685 die("dwm-"VERSION", © 2006-2008 dwm engineers, see LICENSE for details\n");
1687 die("usage: dwm [-v]\n");
1689 if(!setlocale(LC_CTYPE, "") || !XSupportsLocale())
1690 fprintf(stderr, "warning: no locale support\n");
1692 if(!(dpy = XOpenDisplay(0)))
1693 die("dwm: cannot open display\n");