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(M, C) ((M) == (&mon[C->mon]) && (C->tags & tagset[M->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))
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;
89 Bool isfixed, isfloating, isurgent;
97 unsigned long norm[ColLast];
98 unsigned long sel[ColLast];
108 } DC; /* draw context */
113 void (*func)(const Arg *);
120 int by, btx; /* bar geometry */
121 int wx, wy, ww, wh; /* window area */
122 unsigned int seltags;
131 void (*arrange)(Monitor *);
136 const char *instance;
142 /* function declarations */
143 static void applyrules(Client *c);
144 static Bool applysizehints(Client *c, int *x, int *y, int *w, int *h);
145 static void arrange(void);
146 static void attach(Client *c);
147 static void attachstack(Client *c);
148 static void buttonpress(XEvent *e);
149 static void checkotherwm(void);
150 static void cleanup(void);
151 static void clearurgent(Client *c);
152 static void configure(Client *c);
153 static void configurenotify(XEvent *e);
154 static void configurerequest(XEvent *e);
155 static void destroynotify(XEvent *e);
156 static void detach(Client *c);
157 static void detachstack(Client *c);
158 static void die(const char *errstr, ...);
159 static void drawbar(Monitor *m);
160 static void drawbars();
161 static void drawsquare(Bool filled, Bool empty, Bool invert, unsigned long col[ColLast]);
162 static void drawtext(const char *text, unsigned long col[ColLast], Bool invert);
163 static void enternotify(XEvent *e);
164 static void expose(XEvent *e);
165 static void focus(Client *c);
166 static void focusin(XEvent *e);
167 static void focusstack(const Arg *arg);
168 static Client *getclient(Window w);
169 static unsigned long getcolor(const char *colstr);
170 static long getstate(Window w);
171 static Bool gettextprop(Window w, Atom atom, char *text, unsigned int size);
172 static void grabbuttons(Client *c, Bool focused);
173 static void grabkeys(void);
174 static void initfont(const char *fontstr);
175 static Bool isprotodel(Client *c);
176 static void keypress(XEvent *e);
177 static void killclient(const Arg *arg);
178 static void manage(Window w, XWindowAttributes *wa);
179 static void mappingnotify(XEvent *e);
180 static void maprequest(XEvent *e);
181 static void monocle(Monitor *m);
182 static void movemouse(const Arg *arg);
183 static Client *nexttiled(Monitor *m, Client *c);
184 static void propertynotify(XEvent *e);
185 static void quit(const Arg *arg);
186 static void resize(Client *c, int x, int y, int w, int h);
187 static void resizemouse(const Arg *arg);
188 static void restack(Monitor *m);
189 static void run(void);
190 static void scan(void);
191 static void setclientstate(Client *c, long state);
192 static void setlayout(const Arg *arg);
193 static void setmfact(const Arg *arg);
194 static void setup(void);
195 static void showhide(Client *c);
196 static void sigchld(int signal);
197 static void spawn(const Arg *arg);
198 static void tag(const Arg *arg);
199 static int textnw(const char *text, unsigned int len);
200 static void tile(Monitor *);
201 static void togglebar(const Arg *arg);
202 static void togglefloating(const Arg *arg);
203 static void toggletag(const Arg *arg);
204 static void toggleview(const Arg *arg);
205 static void unmanage(Client *c);
206 static void unmapnotify(XEvent *e);
207 static void updategeom(void);
208 static void updatenumlockmask(void);
209 static void updatesizehints(Client *c);
210 static void updatestatus(void);
211 static void updatetitle(Client *c);
212 static void updatewmhints(Client *c);
213 static void view(const Arg *arg);
214 static int xerror(Display *dpy, XErrorEvent *ee);
215 static int xerrordummy(Display *dpy, XErrorEvent *ee);
216 static int xerrorstart(Display *dpy, XErrorEvent *ee);
217 static void zoom(const Arg *arg);
219 static void focusmon(const Arg *arg);
220 static void tagmon(const Arg *arg);
221 #endif /* XINERAMA */
224 static char stext[256];
226 static int sx, sy, sw, sh; /* X display screen geometry x, y, width, height */
227 static int bh, blw = 0; /* bar geometry */
228 static int (*xerrorxlib)(Display *, XErrorEvent *);
229 static unsigned int numlockmask = 0;
230 static void (*handler[LASTEvent]) (XEvent *) = {
231 [ButtonPress] = buttonpress,
232 [ConfigureRequest] = configurerequest,
233 [ConfigureNotify] = configurenotify,
234 [DestroyNotify] = destroynotify,
235 [EnterNotify] = enternotify,
238 [KeyPress] = keypress,
239 [MappingNotify] = mappingnotify,
240 [MapRequest] = maprequest,
241 [PropertyNotify] = propertynotify,
242 [UnmapNotify] = unmapnotify
244 static Atom wmatom[WMLast], netatom[NetLast];
246 static Bool running = True;
247 static Client *clients = NULL;
248 static Client *sel = NULL;
249 static Client *stack = NULL;
250 static Cursor cursor[CurLast];
253 static Layout *lt[] = { NULL, NULL };
254 static Monitor *mon = NULL, *selmon = NULL;
255 static unsigned int nmons = 0;
257 /* configuration, allows nested code to access above variables */
260 /* compile-time check if all tags fit into an unsigned int bit array. */
261 struct NumTags { char limitexceeded[sizeof(unsigned int) * 8 < LENGTH(tags) ? -1 : 1]; };
263 /* function implementations */
265 applyrules(Client *c) {
268 XClassHint ch = { 0 };
271 c->isfloating = c->tags = 0;
272 if(XGetClassHint(dpy, c->win, &ch)) {
273 for(i = 0; i < LENGTH(rules); i++) {
275 if((!r->title || strstr(c->name, r->title))
276 && (!r->class || (ch.res_class && strstr(ch.res_class, r->class)))
277 && (!r->instance || (ch.res_name && strstr(ch.res_name, r->instance)))) {
278 c->isfloating = r->isfloating;
287 c->tags = c->tags & TAGMASK ? c->tags & TAGMASK : tagset[mon[c->mon].seltags];
291 applysizehints(Client *c, int *x, int *y, int *w, int *h) {
294 /* set minimum possible */
302 if(*x + *w + 2 * c->bw < sx)
304 if(*y + *h + 2 * c->bw < sy)
311 if(resizehints || c->isfloating) {
312 /* see last two sentences in ICCCM 4.1.2.3 */
313 baseismin = c->basew == c->minw && c->baseh == c->minh;
315 if(!baseismin) { /* temporarily remove base dimensions */
320 /* adjust for aspect limits */
321 if(c->mina > 0 && c->maxa > 0) {
322 if(c->maxa < (float)*w / *h)
324 else if(c->mina < (float)*h / *w)
328 if(baseismin) { /* increment calculation requires this */
333 /* adjust for increment value */
339 /* restore base dimensions */
343 *w = MAX(*w, c->minw);
344 *h = MAX(*h, c->minh);
347 *w = MIN(*w, c->maxw);
350 *h = MIN(*h, c->maxh);
352 return *x != c->x || *y != c->y || *w != c->w || *h != c->h;
360 for(i = 0; i < nmons; i++) {
361 if(lt[mon[i].sellt]->arrange)
362 lt[mon[i].sellt]->arrange(&mon[i]);
374 attachstack(Client *c) {
380 buttonpress(XEvent *e) {
381 unsigned int i, x, click;
384 XButtonPressedEvent *ev = &e->xbutton;
387 if(ev->window == selmon->barwin) {
392 while(ev->x >= x && ++i < LENGTH(tags));
393 if(i < LENGTH(tags)) {
397 else if(ev->x < x + blw)
399 else if(ev->x > selmon->wx + selmon->ww - TEXTW(stext))
400 click = ClkStatusText;
404 else if((c = getclient(ev->window))) {
406 click = ClkClientWin;
409 for(i = 0; i < LENGTH(buttons); i++)
410 if(click == buttons[i].click && buttons[i].func && buttons[i].button == ev->button
411 && CLEANMASK(buttons[i].mask) == CLEANMASK(ev->state))
412 buttons[i].func(click == ClkTagBar && buttons[i].arg.i == 0 ? &arg : &buttons[i].arg);
418 xerrorxlib = XSetErrorHandler(xerrorstart);
420 /* this causes an error if some other window manager is running */
421 XSelectInput(dpy, DefaultRootWindow(dpy), SubstructureRedirectMask);
424 die("dwm: another window manager is already running\n");
425 XSetErrorHandler(xerror);
433 Layout foo = { "", NULL };
436 lt[selmon->sellt] = &foo;
440 XFreeFontSet(dpy, dc.font.set);
442 XFreeFont(dpy, dc.font.xfont);
443 XUngrabKey(dpy, AnyKey, AnyModifier, root);
444 XFreePixmap(dpy, dc.drawable);
446 XFreeCursor(dpy, cursor[CurNormal]);
447 XFreeCursor(dpy, cursor[CurResize]);
448 XFreeCursor(dpy, cursor[CurMove]);
449 for(i = 0; i < nmons; i++)
450 XDestroyWindow(dpy, mon[i].barwin);
453 XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime);
457 clearurgent(Client *c) {
461 if(!(wmh = XGetWMHints(dpy, c->win)))
463 wmh->flags &= ~XUrgencyHint;
464 XSetWMHints(dpy, c->win, wmh);
469 configure(Client *c) {
472 ce.type = ConfigureNotify;
480 ce.border_width = c->bw;
482 ce.override_redirect = False;
483 XSendEvent(dpy, c->win, False, StructureNotifyMask, (XEvent *)&ce);
487 configurenotify(XEvent *e) {
489 XConfigureEvent *ev = &e->xconfigure;
491 if(ev->window == root && (ev->width != sw || ev->height != sh)) {
496 XFreePixmap(dpy, dc.drawable);
497 dc.drawable = XCreatePixmap(dpy, root, sw, bh, DefaultDepth(dpy, screen));
498 for(i = 0; i < nmons; i++)
499 XMoveResizeWindow(dpy, mon[i].barwin, mon[i].wx, mon[i].by, mon[i].ww, bh);
505 configurerequest(XEvent *e) {
507 XConfigureRequestEvent *ev = &e->xconfigurerequest;
510 if((c = getclient(ev->window))) {
511 if(ev->value_mask & CWBorderWidth)
512 c->bw = ev->border_width;
513 else if(c->isfloating || !lt[selmon->sellt]->arrange) {
514 if(ev->value_mask & CWX)
516 if(ev->value_mask & CWY)
518 if(ev->value_mask & CWWidth)
520 if(ev->value_mask & CWHeight)
522 if((c->x - sx + c->w) > sw && c->isfloating)
523 c->x = sx + (sw / 2 - c->w / 2); /* center in x direction */
524 if((c->y - sy + c->h) > sh && c->isfloating)
525 c->y = sy + (sh / 2 - c->h / 2); /* center in y direction */
526 if((ev->value_mask & (CWX|CWY)) && !(ev->value_mask & (CWWidth|CWHeight)))
528 if(ISVISIBLE((&mon[c->mon]), c))
529 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h);
537 wc.width = ev->width;
538 wc.height = ev->height;
539 wc.border_width = ev->border_width;
540 wc.sibling = ev->above;
541 wc.stack_mode = ev->detail;
542 XConfigureWindow(dpy, ev->window, ev->value_mask, &wc);
548 destroynotify(XEvent *e) {
550 XDestroyWindowEvent *ev = &e->xdestroywindow;
552 if((c = getclient(ev->window)))
560 for(tc = &clients; *tc && *tc != c; tc = &(*tc)->next);
565 detachstack(Client *c) {
568 for(tc = &stack; *tc && *tc != c; tc = &(*tc)->snext);
573 die(const char *errstr, ...) {
576 va_start(ap, errstr);
577 vfprintf(stderr, errstr, ap);
583 drawbar(Monitor *m) {
585 unsigned int i, occ = 0, urg = 0;
589 for(c = clients; c; c = c->next) {
590 if(m == &mon[c->mon]) {
600 dc.w = TEXTW(m->symbol);
601 drawtext(m->symbol, selmon == m ? dc.sel : dc.norm, False);
604 #endif /* XINERAMA */
606 for(i = 0; i < LENGTH(tags); i++) {
607 dc.w = TEXTW(tags[i]);
608 col = tagset[m->seltags] & 1 << i ? dc.sel : dc.norm;
609 drawtext(tags[i], col, urg & 1 << i);
610 drawsquare(m == selmon && sel && sel->tags & 1 << i,
611 occ & 1 << i, urg & 1 << i, col);
616 drawtext(lt[m->sellt]->symbol, dc.norm, False);
628 drawtext(stext, dc.norm, False);
629 if((dc.w = dc.x - x) > bh) {
632 drawtext(sel->name, dc.sel, False);
633 drawsquare(sel->isfixed, sel->isfloating, False, dc.sel);
636 drawtext(NULL, dc.norm, False);
642 drawtext(NULL, dc.norm, False);
644 XCopyArea(dpy, dc.drawable, m->barwin, dc.gc, 0, 0, m->ww, bh, 0, 0);
652 for(i = 0; i < nmons; i++)
657 drawsquare(Bool filled, Bool empty, Bool invert, unsigned long col[ColLast]) {
660 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
662 gcv.foreground = col[invert ? ColBG : ColFG];
663 XChangeGC(dpy, dc.gc, GCForeground, &gcv);
664 x = (dc.font.ascent + dc.font.descent + 2) / 4;
668 r.width = r.height = x + 1;
669 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
672 r.width = r.height = x;
673 XDrawRectangles(dpy, dc.drawable, dc.gc, &r, 1);
678 drawtext(const char *text, unsigned long col[ColLast], Bool invert) {
680 int i, x, y, h, len, olen;
681 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
683 XSetForeground(dpy, dc.gc, col[invert ? ColFG : ColBG]);
684 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
688 h = dc.font.ascent + dc.font.descent;
689 y = dc.y + (dc.h / 2) - (h / 2) + dc.font.ascent;
691 /* shorten text if necessary */
692 for(len = MIN(olen, sizeof buf); len && textnw(text, len) > dc.w - h; len--);
695 memcpy(buf, text, len);
697 for(i = len; i && i > len - 3; buf[--i] = '.');
698 XSetForeground(dpy, dc.gc, col[invert ? ColBG : ColFG]);
700 XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
702 XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
706 enternotify(XEvent *e) {
708 XCrossingEvent *ev = &e->xcrossing;
710 if((ev->mode != NotifyNormal || ev->detail == NotifyInferior) && ev->window != root)
712 if((c = getclient(ev->window)))
721 XExposeEvent *ev = &e->xexpose;
724 for(i = 0; i < nmons; i++)
725 if(ev->window == mon[i].barwin) {
733 if(!c || !ISVISIBLE((&mon[c->mon]), c))
734 for(c = stack; c && !ISVISIBLE(selmon, c); c = c->snext);
735 if(sel && sel != c) {
736 grabbuttons(sel, False);
737 XSetWindowBorder(dpy, sel->win, dc.norm[ColBorder]);
744 grabbuttons(c, True);
745 XSetWindowBorder(dpy, c->win, dc.sel[ColBorder]);
746 XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
749 XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
752 selmon = &mon[c->mon];
757 focusin(XEvent *e) { /* there are some broken focus acquiring clients */
758 XFocusChangeEvent *ev = &e->xfocus;
760 if(sel && ev->window != sel->win)
761 XSetInputFocus(dpy, sel->win, RevertToPointerRoot, CurrentTime);
766 focusmon(const Arg *arg) {
769 selmon = &mon[arg->ui];
773 #endif /* XINERAMA */
776 focusstack(const Arg *arg) {
777 Client *c = NULL, *i;
782 for(c = sel->next; c && !ISVISIBLE(selmon, c); c = c->next);
784 for(c = clients; c && !ISVISIBLE(selmon, c); c = c->next);
787 for(i = clients; i != sel; i = i->next)
788 if(ISVISIBLE(selmon, i))
791 for(; i; i = i->next)
792 if(ISVISIBLE(selmon, i))
802 getclient(Window w) {
805 for(c = clients; c && c->win != w; c = c->next);
810 getcolor(const char *colstr) {
811 Colormap cmap = DefaultColormap(dpy, screen);
814 if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
815 die("error, cannot allocate color '%s'\n", colstr);
823 unsigned char *p = NULL;
824 unsigned long n, extra;
827 status = XGetWindowProperty(dpy, w, wmatom[WMState], 0L, 2L, False, wmatom[WMState],
828 &real, &format, &n, &extra, (unsigned char **)&p);
829 if(status != Success)
838 gettextprop(Window w, Atom atom, char *text, unsigned int size) {
843 if(!text || size == 0)
846 XGetTextProperty(dpy, w, &name, atom);
849 if(name.encoding == XA_STRING)
850 strncpy(text, (char *)name.value, size - 1);
852 if(XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success
854 strncpy(text, *list, size - 1);
855 XFreeStringList(list);
858 text[size - 1] = '\0';
864 grabbuttons(Client *c, Bool focused) {
868 unsigned int modifiers[] = { 0, LockMask, numlockmask, numlockmask|LockMask };
869 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
871 for(i = 0; i < LENGTH(buttons); i++)
872 if(buttons[i].click == ClkClientWin)
873 for(j = 0; j < LENGTH(modifiers); j++)
874 XGrabButton(dpy, buttons[i].button,
875 buttons[i].mask | modifiers[j],
876 c->win, False, BUTTONMASK,
877 GrabModeAsync, GrabModeSync, None, None);
879 XGrabButton(dpy, AnyButton, AnyModifier, c->win, False,
880 BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
889 unsigned int modifiers[] = { 0, LockMask, numlockmask, numlockmask|LockMask };
892 XUngrabKey(dpy, AnyKey, AnyModifier, root);
893 for(i = 0; i < LENGTH(keys); i++) {
894 if((code = XKeysymToKeycode(dpy, keys[i].keysym)))
895 for(j = 0; j < LENGTH(modifiers); j++)
896 XGrabKey(dpy, code, keys[i].mod | modifiers[j], root,
897 True, GrabModeAsync, GrabModeAsync);
903 initfont(const char *fontstr) {
904 char *def, **missing;
908 dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
911 fprintf(stderr, "dwm: missing fontset: %s\n", missing[n]);
912 XFreeStringList(missing);
915 XFontSetExtents *font_extents;
916 XFontStruct **xfonts;
918 dc.font.ascent = dc.font.descent = 0;
919 font_extents = XExtentsOfFontSet(dc.font.set);
920 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
921 for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
922 dc.font.ascent = MAX(dc.font.ascent, (*xfonts)->ascent);
923 dc.font.descent = MAX(dc.font.descent,(*xfonts)->descent);
928 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr))
929 && !(dc.font.xfont = XLoadQueryFont(dpy, "fixed")))
930 die("error, cannot load font: '%s'\n", fontstr);
931 dc.font.ascent = dc.font.xfont->ascent;
932 dc.font.descent = dc.font.xfont->descent;
934 dc.font.height = dc.font.ascent + dc.font.descent;
938 isprotodel(Client *c) {
943 if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
944 for(i = 0; !ret && i < n; i++)
945 if(protocols[i] == wmatom[WMDelete])
953 keypress(XEvent *e) {
959 keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
960 for(i = 0; i < LENGTH(keys); i++)
961 if(keysym == keys[i].keysym
962 && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state)
964 keys[i].func(&(keys[i].arg));
968 killclient(const Arg *arg) {
973 if(isprotodel(sel)) {
974 ev.type = ClientMessage;
975 ev.xclient.window = sel->win;
976 ev.xclient.message_type = wmatom[WMProtocols];
977 ev.xclient.format = 32;
978 ev.xclient.data.l[0] = wmatom[WMDelete];
979 ev.xclient.data.l[1] = CurrentTime;
980 XSendEvent(dpy, sel->win, False, NoEventMask, &ev);
983 XKillClient(dpy, sel->win);
987 manage(Window w, XWindowAttributes *wa) {
989 Client *c, *t = NULL;
993 if(!(c = malloc(sizeof(Client))))
994 die("fatal: could not malloc() %u bytes\n", sizeof(Client));
997 for(c->mon = 0; selmon != &mon[c->mon]; c->mon++);
1004 c->oldbw = wa->border_width;
1005 if(c->w == sw && c->h == sh) {
1011 if(c->x + WIDTH(c) > sx + sw)
1012 c->x = sx + sw - WIDTH(c);
1013 if(c->y + HEIGHT(c) > sy + sh)
1014 c->y = sy + sh - HEIGHT(c);
1015 c->x = MAX(c->x, sx);
1016 /* only fix client y-offset, if the client center might cover the bar */
1017 c->y = MAX(c->y, ((selmon->by == 0) && (c->x + (c->w / 2) >= selmon->wx)
1018 && (c->x + (c->w / 2) < selmon->wx + selmon->ww)) ? bh : sy);
1022 wc.border_width = c->bw;
1023 XConfigureWindow(dpy, w, CWBorderWidth, &wc);
1024 XSetWindowBorder(dpy, w, dc.norm[ColBorder]);
1025 configure(c); /* propagates border_width, if size doesn't change */
1027 XSelectInput(dpy, w, EnterWindowMask|FocusChangeMask|PropertyChangeMask|StructureNotifyMask);
1028 grabbuttons(c, False);
1030 if(XGetTransientForHint(dpy, w, &trans))
1031 t = getclient(trans);
1037 c->isfloating = trans != None || c->isfixed;
1039 XRaiseWindow(dpy, c->win);
1042 XMoveResizeWindow(dpy, c->win, c->x + 2 * sw, c->y, c->w, c->h); /* some windows require this */
1043 XMapWindow(dpy, c->win);
1044 setclientstate(c, NormalState);
1049 mappingnotify(XEvent *e) {
1050 XMappingEvent *ev = &e->xmapping;
1052 XRefreshKeyboardMapping(ev);
1053 if(ev->request == MappingKeyboard)
1058 maprequest(XEvent *e) {
1059 static XWindowAttributes wa;
1060 XMapRequestEvent *ev = &e->xmaprequest;
1062 if(!XGetWindowAttributes(dpy, ev->window, &wa))
1064 if(wa.override_redirect)
1066 if(!getclient(ev->window))
1067 manage(ev->window, &wa);
1071 monocle(Monitor *m) {
1074 for(c = nexttiled(m, clients); c; c = nexttiled(m, c->next))
1075 resize(c, m->wx, m->wy, m->ww - 2 * c->bw, m->wh - 2 * c->bw);
1079 movemouse(const Arg *arg) {
1080 int x, y, ocx, ocy, di, nx, ny;
1091 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1092 None, cursor[CurMove], CurrentTime) != GrabSuccess)
1094 XQueryPointer(dpy, root, &dummy, &dummy, &x, &y, &di, &di, &dui);
1096 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
1098 case ConfigureRequest:
1101 handler[ev.type](&ev);
1104 nx = ocx + (ev.xmotion.x - x);
1105 ny = ocy + (ev.xmotion.y - y);
1106 if(snap && nx >= selmon->wx && nx <= selmon->wx + selmon->ww
1107 && ny >= selmon->wy && ny <= selmon->wy + selmon->wh) {
1108 if(abs(selmon->wx - nx) < snap)
1110 else if(abs((selmon->wx + selmon->ww) - (nx + WIDTH(c))) < snap)
1111 nx = selmon->wx + selmon->ww - WIDTH(c);
1112 if(abs(selmon->wy - ny) < snap)
1114 else if(abs((selmon->wy + selmon->wh) - (ny + HEIGHT(c))) < snap)
1115 ny = selmon->wy + selmon->wh - HEIGHT(c);
1116 if(!c->isfloating && lt[selmon->sellt]->arrange
1117 && (abs(nx - c->x) > snap || abs(ny - c->y) > snap))
1118 togglefloating(NULL);
1120 if(!lt[selmon->sellt]->arrange || c->isfloating)
1121 resize(c, nx, ny, c->w, c->h);
1125 while(ev.type != ButtonRelease);
1126 XUngrabPointer(dpy, CurrentTime);
1130 nexttiled(Monitor *m, Client *c) {
1132 for(; c && (c->isfloating || !ISVISIBLE(m, c)); c = c->next);
1137 propertynotify(XEvent *e) {
1140 XPropertyEvent *ev = &e->xproperty;
1142 if((ev->window == root) && (ev->atom == XA_WM_NAME))
1144 else if(ev->state == PropertyDelete)
1145 return; /* ignore */
1146 else if((c = getclient(ev->window))) {
1149 case XA_WM_TRANSIENT_FOR:
1150 XGetTransientForHint(dpy, c->win, &trans);
1151 if(!c->isfloating && (c->isfloating = (getclient(trans) != NULL)))
1154 case XA_WM_NORMAL_HINTS:
1162 if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
1171 quit(const Arg *arg) {
1176 resize(Client *c, int x, int y, int w, int h) {
1179 if(applysizehints(c, &x, &y, &w, &h)) {
1182 c->w = wc.width = w;
1183 c->h = wc.height = h;
1184 wc.border_width = c->bw;
1185 XConfigureWindow(dpy, c->win,
1186 CWX|CWY|CWWidth|CWHeight|CWBorderWidth, &wc);
1193 resizemouse(const Arg *arg) {
1204 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1205 None, cursor[CurResize], CurrentTime) != GrabSuccess)
1207 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->bw - 1, c->h + c->bw - 1);
1209 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
1211 case ConfigureRequest:
1214 handler[ev.type](&ev);
1217 nw = MAX(ev.xmotion.x - ocx - 2 * c->bw + 1, 1);
1218 nh = MAX(ev.xmotion.y - ocy - 2 * c->bw + 1, 1);
1220 if(snap && nw >= selmon->wx && nw <= selmon->wx + selmon->ww
1221 && nh >= selmon->wy && nh <= selmon->wy + selmon->wh) {
1222 if(!c->isfloating && lt[selmon->sellt]->arrange
1223 && (abs(nw - c->w) > snap || abs(nh - c->h) > snap))
1224 togglefloating(NULL);
1226 if(!lt[selmon->sellt]->arrange || c->isfloating)
1227 resize(c, c->x, c->y, nw, nh);
1231 while(ev.type != ButtonRelease);
1232 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->bw - 1, c->h + c->bw - 1);
1233 XUngrabPointer(dpy, CurrentTime);
1234 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1238 restack(Monitor *m) {
1246 if(m == selmon && (sel->isfloating || !lt[m->sellt]->arrange))
1247 XRaiseWindow(dpy, sel->win);
1248 if(lt[m->sellt]->arrange) {
1249 wc.stack_mode = Below;
1250 wc.sibling = m->barwin;
1251 for(c = stack; c; c = c->snext)
1252 if(!c->isfloating && ISVISIBLE(m, c)) {
1253 XConfigureWindow(dpy, c->win, CWSibling|CWStackMode, &wc);
1254 wc.sibling = c->win;
1258 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1265 /* main event loop */
1267 while(running && !XNextEvent(dpy, &ev)) {
1268 if(handler[ev.type])
1269 (handler[ev.type])(&ev); /* call handler */
1275 unsigned int i, num;
1276 Window d1, d2, *wins = NULL;
1277 XWindowAttributes wa;
1279 if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1280 for(i = 0; i < num; i++) {
1281 if(!XGetWindowAttributes(dpy, wins[i], &wa)
1282 || wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1284 if(wa.map_state == IsViewable || getstate(wins[i]) == IconicState)
1285 manage(wins[i], &wa);
1287 for(i = 0; i < num; i++) { /* now the transients */
1288 if(!XGetWindowAttributes(dpy, wins[i], &wa))
1290 if(XGetTransientForHint(dpy, wins[i], &d1)
1291 && (wa.map_state == IsViewable || getstate(wins[i]) == IconicState))
1292 manage(wins[i], &wa);
1300 setclientstate(Client *c, long state) {
1301 long data[] = {state, None};
1303 XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1304 PropModeReplace, (unsigned char *)data, 2);
1308 setlayout(const Arg *arg) {
1309 if(!arg || !arg->v || arg->v != lt[selmon->sellt])
1312 lt[selmon->sellt] = (Layout *)arg->v;
1319 /* arg > 1.0 will set mfact absolutly */
1321 setmfact(const Arg *arg) {
1324 if(!arg || !lt[selmon->sellt]->arrange)
1326 f = arg->f < 1.0 ? arg->f + selmon->mfact : arg->f - 1.0;
1327 if(f < 0.1 || f > 0.9)
1337 XSetWindowAttributes wa;
1340 screen = DefaultScreen(dpy);
1341 root = RootWindow(dpy, screen);
1345 sw = DisplayWidth(dpy, screen);
1346 sh = DisplayHeight(dpy, screen);
1347 bh = dc.h = dc.font.height + 2;
1348 lt[0] = &layouts[0];
1349 lt[1] = &layouts[1 % LENGTH(layouts)];
1353 wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1354 wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1355 wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1356 netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1357 netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1360 wa.cursor = cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1361 cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1362 cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1364 /* init appearance */
1365 dc.norm[ColBorder] = getcolor(normbordercolor);
1366 dc.norm[ColBG] = getcolor(normbgcolor);
1367 dc.norm[ColFG] = getcolor(normfgcolor);
1368 dc.sel[ColBorder] = getcolor(selbordercolor);
1369 dc.sel[ColBG] = getcolor(selbgcolor);
1370 dc.sel[ColFG] = getcolor(selfgcolor);
1371 dc.drawable = XCreatePixmap(dpy, root, DisplayWidth(dpy, screen), bh, DefaultDepth(dpy, screen));
1372 dc.gc = XCreateGC(dpy, root, 0, NULL);
1373 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
1375 XSetFont(dpy, dc.gc, dc.font.xfont->fid);
1378 wa.override_redirect = True;
1379 wa.background_pixmap = ParentRelative;
1380 wa.event_mask = ButtonPressMask|ExposureMask;
1381 for(blw = i = 0; LENGTH(layouts) > 1 && i < LENGTH(layouts); i++) {
1382 w = TEXTW(layouts[i].symbol);
1386 for(i = 0; i < nmons; i++) {
1387 mon[i].barwin = XCreateWindow(dpy, root, mon[i].wx, mon[i].by, mon[i].ww, bh, 0, DefaultDepth(dpy, screen),
1389 CopyFromParent, DefaultVisual(dpy, screen),
1390 CWOverrideRedirect|CWBackPixmap|CWEventMask, &wa);
1391 XDefineCursor(dpy, mon[i].barwin, cursor[CurNormal]);
1392 XMapRaised(dpy, mon[i].barwin);
1396 /* EWMH support per view */
1397 XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1398 PropModeReplace, (unsigned char *) netatom, NetLast);
1400 /* select for events */
1401 wa.event_mask = SubstructureRedirectMask|SubstructureNotifyMask|ButtonPressMask
1402 |EnterWindowMask|LeaveWindowMask|StructureNotifyMask
1403 |PropertyChangeMask;
1404 XChangeWindowAttributes(dpy, root, CWEventMask|CWCursor, &wa);
1405 XSelectInput(dpy, root, wa.event_mask);
1411 showhide(Client *c) {
1414 if(ISVISIBLE((&mon[c->mon]), c)) { /* show clients top down */
1415 XMoveWindow(dpy, c->win, c->x, c->y);
1416 if(!lt[selmon->sellt]->arrange || c->isfloating)
1417 resize(c, c->x, c->y, c->w, c->h);
1420 else { /* hide clients bottom up */
1422 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
1428 sigchld(int signal) {
1429 while(0 < waitpid(-1, NULL, WNOHANG));
1433 spawn(const Arg *arg) {
1434 signal(SIGCHLD, sigchld);
1437 close(ConnectionNumber(dpy));
1439 execvp(((char **)arg->v)[0], (char **)arg->v);
1440 fprintf(stderr, "dwm: execvp %s", ((char **)arg->v)[0]);
1447 tag(const Arg *arg) {
1448 if(sel && arg->ui & TAGMASK) {
1449 sel->tags = arg->ui & TAGMASK;
1456 tagmon(const Arg *arg) {
1457 if(!sel || arg->ui >= nmons)
1462 #endif /* XINERAMA */
1465 textnw(const char *text, unsigned int len) {
1469 XmbTextExtents(dc.font.set, text, len, NULL, &r);
1472 return XTextWidth(dc.font.xfont, text, len);
1481 for(n = 0, c = nexttiled(m, clients); c; c = nexttiled(m, c->next), n++);
1486 c = nexttiled(m, clients);
1487 mw = m->mfact * m->ww;
1488 resize(c, m->wx, m->wy, (n == 1 ? m->ww : mw) - 2 * c->bw, m->wh - 2 * c->bw);
1494 x = (m->wx + mw > c->x + c->w) ? c->x + c->w + 2 * c->bw : m->wx + mw;
1496 w = (m->wx + mw > c->x + c->w) ? m->wx + m->ww - x : m->ww - mw;
1501 for(i = 0, c = nexttiled(m, c->next); c; c = nexttiled(m, c->next), i++) {
1502 resize(c, x, y, w - 2 * c->bw, /* remainder */ ((i + 1 == n)
1503 ? m->wy + m->wh - y - 2 * c->bw : h - 2 * c->bw));
1505 y = c->y + HEIGHT(c);
1510 togglebar(const Arg *arg) {
1511 selmon->showbar = !selmon->showbar;
1513 XMoveResizeWindow(dpy, selmon->barwin, selmon->wx, selmon->by, selmon->ww, bh);
1518 togglefloating(const Arg *arg) {
1521 sel->isfloating = !sel->isfloating || sel->isfixed;
1523 resize(sel, sel->x, sel->y, sel->w, sel->h);
1528 toggletag(const Arg *arg) {
1534 mask = sel->tags ^ (arg->ui & TAGMASK);
1542 toggleview(const Arg *arg) {
1543 unsigned int mask = tagset[selmon->seltags] ^ (arg->ui & TAGMASK);
1546 tagset[selmon->seltags] = mask;
1552 unmanage(Client *c) {
1555 wc.border_width = c->oldbw;
1556 /* The server grab construct avoids race conditions. */
1558 XSetErrorHandler(xerrordummy);
1559 XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
1564 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1565 setclientstate(c, WithdrawnState);
1568 XSetErrorHandler(xerror);
1574 unmapnotify(XEvent *e) {
1576 XUnmapEvent *ev = &e->xunmap;
1578 if((c = getclient(ev->window)))
1588 XineramaScreenInfo *info = NULL;
1590 /* window area geometry */
1591 if(XineramaIsActive(dpy) && (info = XineramaQueryScreens(dpy, &n))) {
1593 for(c = clients; c; c = c->next)
1596 if(!(mon = (Monitor *)realloc(mon, sizeof(Monitor) * n)))
1597 die("fatal: could not realloc() %u bytes\n", sizeof(Monitor) * nmons);
1599 for(i = 0; i < n ; i++) {
1600 /* TODO: consider re-using XineramaScreenInfo */
1601 mon[i].symbol[0] = '[';
1602 mon[i].symbol[1] = '0' + info[i].screen_number;
1603 mon[i].symbol[2] = ']';
1604 mon[i].symbol[3] = 0;
1605 if(!selmon) { /* not initialised yet */
1606 mon[i].mfact = mfact;
1607 mon[i].showbar = showbar;
1608 mon[i].topbar = topbar;
1610 mon[i].wx = info[i].x_org;
1611 mon[i].wy = mon[i].showbar && mon[i].topbar ? info[i].y_org + bh : info[i].y_org;
1612 mon[i].ww = info[i].width;
1613 mon[i].wh = mon[i].showbar ? info[i].height - bh : info[i].height;
1617 mon[i].by = mon[i].topbar ? info[i].y_org : mon[i].wy + mon[i].wh;
1621 nmons = (unsigned int)n;
1627 if(XQueryPointer(dpy, root, &dummy, &dummy, &x, &y, &di, &di, &dui))
1628 for(i = 0; i < nmons; i++)
1629 if(INRECT(x, y, info[i].x_org, info[i].y_org, info[i].width, info[i].height)) {
1637 #endif /* XINERAMA */
1641 if(!(mon = (Monitor *)malloc(sizeof(Monitor))))
1642 die("fatal: could not malloc() %u bytes\n", sizeof(Monitor));
1645 mon[0].symbol[0] = '[';
1646 mon[0].symbol[1] = '0';
1647 mon[0].symbol[2] = ']';
1648 mon[0].symbol[3] = 0;
1649 mon[0].mfact = mfact;
1650 mon[0].showbar = showbar;
1651 mon[0].topbar = topbar;
1654 mon[0].wy = mon[0].showbar && mon[0].topbar ? sy + bh : sy;
1656 mon[0].wh = mon[0].showbar ? sh - bh : sh;
1660 mon[0].by = mon[0].topbar ? sy : mon[0].wy + mon[0].wh;
1668 updatenumlockmask(void) {
1670 XModifierKeymap *modmap;
1673 modmap = XGetModifierMapping(dpy);
1674 for(i = 0; i < 8; i++)
1675 for(j = 0; j < modmap->max_keypermod; j++)
1676 if(modmap->modifiermap[i * modmap->max_keypermod + j]
1677 == XKeysymToKeycode(dpy, XK_Num_Lock))
1678 numlockmask = (1 << i);
1679 XFreeModifiermap(modmap);
1683 updatesizehints(Client *c) {
1687 if(!XGetWMNormalHints(dpy, c->win, &size, &msize))
1688 /* size is uninitialized, ensure that size.flags aren't used */
1690 if(size.flags & PBaseSize) {
1691 c->basew = size.base_width;
1692 c->baseh = size.base_height;
1694 else if(size.flags & PMinSize) {
1695 c->basew = size.min_width;
1696 c->baseh = size.min_height;
1699 c->basew = c->baseh = 0;
1700 if(size.flags & PResizeInc) {
1701 c->incw = size.width_inc;
1702 c->inch = size.height_inc;
1705 c->incw = c->inch = 0;
1706 if(size.flags & PMaxSize) {
1707 c->maxw = size.max_width;
1708 c->maxh = size.max_height;
1711 c->maxw = c->maxh = 0;
1712 if(size.flags & PMinSize) {
1713 c->minw = size.min_width;
1714 c->minh = size.min_height;
1716 else if(size.flags & PBaseSize) {
1717 c->minw = size.base_width;
1718 c->minh = size.base_height;
1721 c->minw = c->minh = 0;
1722 if(size.flags & PAspect) {
1723 c->mina = (float)size.min_aspect.y / (float)size.min_aspect.x;
1724 c->maxa = (float)size.max_aspect.x / (float)size.max_aspect.y;
1727 c->maxa = c->mina = 0.0;
1728 c->isfixed = (c->maxw && c->minw && c->maxh && c->minh
1729 && c->maxw == c->minw && c->maxh == c->minh);
1733 updatetitle(Client *c) {
1734 if(!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
1735 gettextprop(c->win, XA_WM_NAME, c->name, sizeof c->name);
1740 if(!gettextprop(root, XA_WM_NAME, stext, sizeof(stext)))
1741 strcpy(stext, "dwm-"VERSION);
1746 updatewmhints(Client *c) {
1749 if((wmh = XGetWMHints(dpy, c->win))) {
1750 if(c == sel && wmh->flags & XUrgencyHint) {
1751 wmh->flags &= ~XUrgencyHint;
1752 XSetWMHints(dpy, c->win, wmh);
1755 c->isurgent = (wmh->flags & XUrgencyHint) ? True : False;
1762 view(const Arg *arg) {
1763 if((arg->ui & TAGMASK) == tagset[selmon->seltags])
1765 selmon->seltags ^= 1; /* toggle sel tagset */
1766 if(arg->ui & TAGMASK)
1767 tagset[selmon->seltags] = arg->ui & TAGMASK;
1771 /* There's no way to check accesses to destroyed windows, thus those cases are
1772 * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
1773 * default error handler, which may call exit. */
1775 xerror(Display *dpy, XErrorEvent *ee) {
1776 if(ee->error_code == BadWindow
1777 || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1778 || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1779 || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1780 || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1781 || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1782 || (ee->request_code == X_GrabButton && ee->error_code == BadAccess)
1783 || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1784 || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1786 fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1787 ee->request_code, ee->error_code);
1788 return xerrorxlib(dpy, ee); /* may call exit */
1792 xerrordummy(Display *dpy, XErrorEvent *ee) {
1796 /* Startup Error handler to check if another window manager
1797 * is already running. */
1799 xerrorstart(Display *dpy, XErrorEvent *ee) {
1805 zoom(const Arg *arg) {
1808 if(!lt[selmon->sellt]->arrange || lt[selmon->sellt]->arrange == monocle || (sel && sel->isfloating))
1810 if(c == nexttiled(selmon, clients))
1811 if(!c || !(c = nexttiled(selmon, c->next)))
1820 main(int argc, char *argv[]) {
1821 if(argc == 2 && !strcmp("-v", argv[1]))
1822 die("dwm-"VERSION", © 2006-2009 dwm engineers, see LICENSE for details\n");
1824 die("usage: dwm [-v]\n");
1826 if(!setlocale(LC_CTYPE, "") || !XSupportsLocale())
1827 fputs("warning: no locale support\n", stderr);
1829 if(!(dpy = XOpenDisplay(NULL)))
1830 die("dwm: cannot open display\n");