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) == (C->m) && (C->tags & M->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 Monitor Monitor;
81 typedef struct Client Client;
86 int basew, baseh, incw, inch, maxw, maxh, minw, minh;
89 Bool isfixed, isfloating, isurgent;
98 unsigned long norm[ColLast];
99 unsigned long sel[ColLast];
109 } DC; /* draw context */
114 void (*func)(const Arg *);
120 void (*arrange)(Monitor *);
126 int by, btx; /* bar geometry */
127 int my, mh; /* vertical screen size*/
128 int wx, wy, ww, wh; /* window area */
129 unsigned int seltags;
131 unsigned int tagset[2];
140 const char *instance;
146 /* function declarations */
147 static void applyrules(Client *c);
148 static Bool applysizehints(Client *c, int *x, int *y, int *w, int *h);
149 static void arrange(void);
150 static void attach(Client *c);
151 static void attachstack(Client *c);
152 static void buttonpress(XEvent *e);
153 static void checkotherwm(void);
154 static void cleanup(void);
155 static void cleanupmons(void);
156 static void clearurgent(Client *c);
157 static void configure(Client *c);
158 static void configurenotify(XEvent *e);
159 static void configurerequest(XEvent *e);
160 static void destroynotify(XEvent *e);
161 static void detach(Client *c);
162 static void detachstack(Client *c);
163 static void die(const char *errstr, ...);
164 static void drawbar(Monitor *m);
165 static void drawbars();
166 static void drawsquare(Bool filled, Bool empty, Bool invert, unsigned long col[ColLast]);
167 static void drawtext(const char *text, unsigned long col[ColLast], Bool invert);
168 static void enternotify(XEvent *e);
169 static void expose(XEvent *e);
170 static void focus(Client *c);
171 static void focusin(XEvent *e);
172 static void focusstack(const Arg *arg);
173 static Client *getclient(Window w);
174 static unsigned long getcolor(const char *colstr);
175 static long getstate(Window w);
176 static Bool gettextprop(Window w, Atom atom, char *text, unsigned int size);
177 static void grabbuttons(Client *c, Bool focused);
178 static void grabkeys(void);
179 static void initfont(const char *fontstr);
180 static Bool isprotodel(Client *c);
181 static void keypress(XEvent *e);
182 static void killclient(const Arg *arg);
183 static void manage(Window w, XWindowAttributes *wa);
184 static void mappingnotify(XEvent *e);
185 static void maprequest(XEvent *e);
186 static void monocle(Monitor *m);
187 static void movemouse(const Arg *arg);
188 static Client *nexttiled(Monitor *m, Client *c);
189 static void propertynotify(XEvent *e);
190 static void quit(const Arg *arg);
191 static void resize(Client *c, int x, int y, int w, int h);
192 static void resizemouse(const Arg *arg);
193 static void restack(Monitor *m);
194 static void run(void);
195 static void scan(void);
196 static void setclientstate(Client *c, long state);
197 static void setlayout(const Arg *arg);
198 static void setmfact(const Arg *arg);
199 static void setup(void);
200 static void showhide(Client *c);
201 static void sigchld(int signal);
202 static void spawn(const Arg *arg);
203 static void tag(const Arg *arg);
204 static int textnw(const char *text, unsigned int len);
205 static void tile(Monitor *);
206 static void togglebar(const Arg *arg);
207 static void togglefloating(const Arg *arg);
208 static void toggletag(const Arg *arg);
209 static void toggleview(const Arg *arg);
210 static void unmanage(Client *c);
211 static void unmapnotify(XEvent *e);
212 static void updategeom(void);
213 static void updatebarpos(Monitor *m);
214 static void updatebars(void);
215 static void updatenumlockmask(void);
216 static void updatesizehints(Client *c);
217 static void updatestatus(void);
218 static void updatetitle(Client *c);
219 static void updatewmhints(Client *c);
220 static void view(const Arg *arg);
221 static int xerror(Display *dpy, XErrorEvent *ee);
222 static int xerrordummy(Display *dpy, XErrorEvent *ee);
223 static int xerrorstart(Display *dpy, XErrorEvent *ee);
224 static void zoom(const Arg *arg);
226 static void focusmon(const Arg *arg);
227 static void tagmon(const Arg *arg);
228 #endif /* XINERAMA */
231 static char stext[256];
233 static int sx, sy, sw, sh; /* X display screen geometry x, y, width, height */
234 static int bh, blw = 0; /* bar geometry */
235 static int (*xerrorxlib)(Display *, XErrorEvent *);
236 static unsigned int numlockmask = 0;
237 static void (*handler[LASTEvent]) (XEvent *) = {
238 [ButtonPress] = buttonpress,
239 [ConfigureRequest] = configurerequest,
240 [ConfigureNotify] = configurenotify,
241 [DestroyNotify] = destroynotify,
242 [EnterNotify] = enternotify,
245 [KeyPress] = keypress,
246 [MappingNotify] = mappingnotify,
247 [MapRequest] = maprequest,
248 [PropertyNotify] = propertynotify,
249 [UnmapNotify] = unmapnotify
251 static Atom wmatom[WMLast], netatom[NetLast];
253 static Bool running = True;
254 static Client *clients = NULL;
255 static Client *sel = NULL;
256 static Client *stack = NULL;
257 static Cursor cursor[CurLast];
260 static Layout *lt[] = { NULL, NULL };
261 static Monitor *mons = NULL, *selmon = NULL;
263 /* configuration, allows nested code to access above variables */
266 /* compile-time check if all tags fit into an unsigned int bit array. */
267 struct NumTags { char limitexceeded[sizeof(unsigned int) * 8 < LENGTH(tags) ? -1 : 1]; };
269 /* function implementations */
271 applyrules(Client *c) {
274 XClassHint ch = { 0 };
277 c->isfloating = c->tags = 0;
278 if(XGetClassHint(dpy, c->win, &ch)) {
279 for(i = 0; i < LENGTH(rules); i++) {
281 if((!r->title || strstr(c->name, r->title))
282 && (!r->class || (ch.res_class && strstr(ch.res_class, r->class)))
283 && (!r->instance || (ch.res_name && strstr(ch.res_name, r->instance)))) {
284 c->isfloating = r->isfloating;
293 c->tags = c->tags & TAGMASK ? c->tags & TAGMASK : c->m->tagset[c->m->seltags];
297 applysizehints(Client *c, int *x, int *y, int *w, int *h) {
300 /* set minimum possible */
308 if(*x + *w + 2 * c->bw < sx)
310 if(*y + *h + 2 * c->bw < sy)
317 if(resizehints || c->isfloating) {
318 /* see last two sentences in ICCCM 4.1.2.3 */
319 baseismin = c->basew == c->minw && c->baseh == c->minh;
321 if(!baseismin) { /* temporarily remove base dimensions */
326 /* adjust for aspect limits */
327 if(c->mina > 0 && c->maxa > 0) {
328 if(c->maxa < (float)*w / *h)
330 else if(c->mina < (float)*h / *w)
334 if(baseismin) { /* increment calculation requires this */
339 /* adjust for increment value */
345 /* restore base dimensions */
349 *w = MAX(*w, c->minw);
350 *h = MAX(*h, c->minh);
353 *w = MIN(*w, c->maxw);
356 *h = MIN(*h, c->maxh);
358 return *x != c->x || *y != c->y || *w != c->w || *h != c->h;
367 for(m = mons; m; m = m->next) {
368 if(lt[m->sellt]->arrange)
369 lt[m->sellt]->arrange(m);
381 attachstack(Client *c) {
387 buttonpress(XEvent *e) {
388 unsigned int i, x, click;
391 XButtonPressedEvent *ev = &e->xbutton;
394 if(ev->window == selmon->barwin && ev->x >= selmon->btx) {
399 while(ev->x >= x && ++i < LENGTH(tags));
400 if(i < LENGTH(tags)) {
404 else if(ev->x < x + blw)
406 else if(ev->x > selmon->wx + selmon->ww - TEXTW(stext))
407 click = ClkStatusText;
411 else if((c = getclient(ev->window))) {
413 click = ClkClientWin;
416 for(i = 0; i < LENGTH(buttons); i++)
417 if(click == buttons[i].click && buttons[i].func && buttons[i].button == ev->button
418 && CLEANMASK(buttons[i].mask) == CLEANMASK(ev->state))
419 buttons[i].func(click == ClkTagBar && buttons[i].arg.i == 0 ? &arg : &buttons[i].arg);
425 xerrorxlib = XSetErrorHandler(xerrorstart);
427 /* this causes an error if some other window manager is running */
428 XSelectInput(dpy, DefaultRootWindow(dpy), SubstructureRedirectMask);
431 die("dwm: another window manager is already running\n");
432 XSetErrorHandler(xerror);
439 Layout foo = { "", NULL };
442 lt[selmon->sellt] = &foo;
446 XFreeFontSet(dpy, dc.font.set);
448 XFreeFont(dpy, dc.font.xfont);
449 XUngrabKey(dpy, AnyKey, AnyModifier, root);
450 XFreePixmap(dpy, dc.drawable);
452 XFreeCursor(dpy, cursor[CurNormal]);
453 XFreeCursor(dpy, cursor[CurResize]);
454 XFreeCursor(dpy, cursor[CurMove]);
457 XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime);
466 XUnmapWindow(dpy, mons->barwin);
467 XDestroyWindow(dpy, mons->barwin);
474 clearurgent(Client *c) {
478 if(!(wmh = XGetWMHints(dpy, c->win)))
480 wmh->flags &= ~XUrgencyHint;
481 XSetWMHints(dpy, c->win, wmh);
486 configure(Client *c) {
489 ce.type = ConfigureNotify;
497 ce.border_width = c->bw;
499 ce.override_redirect = False;
500 XSendEvent(dpy, c->win, False, StructureNotifyMask, (XEvent *)&ce);
504 configurenotify(XEvent *e) {
506 XConfigureEvent *ev = &e->xconfigure;
508 if(ev->window == root && (ev->width != sw || ev->height != sh)) {
513 XFreePixmap(dpy, dc.drawable);
514 dc.drawable = XCreatePixmap(dpy, root, sw, bh, DefaultDepth(dpy, screen));
516 for(m = mons; m; m = m->next)
517 XMoveResizeWindow(dpy, m->barwin, m->wx, m->by, m->ww, bh);
523 configurerequest(XEvent *e) {
525 XConfigureRequestEvent *ev = &e->xconfigurerequest;
528 if((c = getclient(ev->window))) {
529 if(ev->value_mask & CWBorderWidth)
530 c->bw = ev->border_width;
531 else if(c->isfloating || !lt[selmon->sellt]->arrange) {
532 if(ev->value_mask & CWX)
534 if(ev->value_mask & CWY)
536 if(ev->value_mask & CWWidth)
538 if(ev->value_mask & CWHeight)
540 if((c->x - sx + c->w) > sw && c->isfloating)
541 c->x = sx + (sw / 2 - c->w / 2); /* center in x direction */
542 if((c->y - sy + c->h) > sh && c->isfloating)
543 c->y = sy + (sh / 2 - c->h / 2); /* center in y direction */
544 if((ev->value_mask & (CWX|CWY)) && !(ev->value_mask & (CWWidth|CWHeight)))
546 if(ISVISIBLE((c->m), c))
547 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h);
555 wc.width = ev->width;
556 wc.height = ev->height;
557 wc.border_width = ev->border_width;
558 wc.sibling = ev->above;
559 wc.stack_mode = ev->detail;
560 XConfigureWindow(dpy, ev->window, ev->value_mask, &wc);
566 destroynotify(XEvent *e) {
568 XDestroyWindowEvent *ev = &e->xdestroywindow;
570 if((c = getclient(ev->window)))
578 for(tc = &clients; *tc && *tc != c; tc = &(*tc)->next);
583 detachstack(Client *c) {
586 for(tc = &stack; *tc && *tc != c; tc = &(*tc)->snext);
591 die(const char *errstr, ...) {
594 va_start(ap, errstr);
595 vfprintf(stderr, errstr, ap);
601 drawbar(Monitor *m) {
604 unsigned int i, occ = 0, urg = 0;
608 for(c = clients; c; c = c->next) {
619 buf[0] = m->screen_number + '0';
622 drawtext(buf, selmon == m ? dc.sel : dc.norm, True);
625 #endif /* XINERAMA */
627 for(i = 0; i < LENGTH(tags); i++) {
628 dc.w = TEXTW(tags[i]);
629 col = m->tagset[m->seltags] & 1 << i ? dc.sel : dc.norm;
630 drawtext(tags[i], col, urg & 1 << i);
631 drawsquare(m == selmon && sel && sel->tags & 1 << i,
632 occ & 1 << i, urg & 1 << i, col);
637 drawtext(lt[m->sellt]->symbol, dc.norm, False);
649 drawtext(stext, dc.norm, False);
650 if((dc.w = dc.x - x) > bh) {
653 drawtext(sel->name, dc.sel, False);
654 drawsquare(sel->isfixed, sel->isfloating, False, dc.sel);
657 drawtext(NULL, dc.norm, False);
663 drawtext(NULL, dc.norm, False);
665 XCopyArea(dpy, dc.drawable, m->barwin, dc.gc, 0, 0, m->ww, bh, 0, 0);
673 for(m = mons; m; m = m->next)
678 drawsquare(Bool filled, Bool empty, Bool invert, unsigned long col[ColLast]) {
681 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
683 gcv.foreground = col[invert ? ColBG : ColFG];
684 XChangeGC(dpy, dc.gc, GCForeground, &gcv);
685 x = (dc.font.ascent + dc.font.descent + 2) / 4;
689 r.width = r.height = x + 1;
690 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
693 r.width = r.height = x;
694 XDrawRectangles(dpy, dc.drawable, dc.gc, &r, 1);
699 drawtext(const char *text, unsigned long col[ColLast], Bool invert) {
701 int i, x, y, h, len, olen;
702 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
704 XSetForeground(dpy, dc.gc, col[invert ? ColFG : ColBG]);
705 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
709 h = dc.font.ascent + dc.font.descent;
710 y = dc.y + (dc.h / 2) - (h / 2) + dc.font.ascent;
712 /* shorten text if necessary */
713 for(len = MIN(olen, sizeof buf); len && textnw(text, len) > dc.w - h; len--);
716 memcpy(buf, text, len);
718 for(i = len; i && i > len - 3; buf[--i] = '.');
719 XSetForeground(dpy, dc.gc, col[invert ? ColBG : ColFG]);
721 XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
723 XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
727 enternotify(XEvent *e) {
729 XCrossingEvent *ev = &e->xcrossing;
731 if((ev->mode != NotifyNormal || ev->detail == NotifyInferior) && ev->window != root)
733 if((c = getclient(ev->window)))
742 XExposeEvent *ev = &e->xexpose;
745 for(m = mons; m; m = m->next)
746 if(ev->window == m->barwin) {
754 if(!c || !ISVISIBLE((c->m), c))
755 for(c = stack; c && !ISVISIBLE(selmon, c); c = c->snext);
756 if(sel && sel != c) {
757 grabbuttons(sel, False);
758 XSetWindowBorder(dpy, sel->win, dc.norm[ColBorder]);
765 grabbuttons(c, True);
766 XSetWindowBorder(dpy, c->win, dc.sel[ColBorder]);
767 XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
770 XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
776 focusin(XEvent *e) { /* there are some broken focus acquiring clients */
777 XFocusChangeEvent *ev = &e->xfocus;
779 if(sel && ev->window != sel->win)
780 XSetInputFocus(dpy, sel->win, RevertToPointerRoot, CurrentTime);
785 focusmon(const Arg *arg) {
789 for(i = 0, m = mons; m; m = m->next, i++)
797 #endif /* XINERAMA */
800 focusstack(const Arg *arg) {
801 Client *c = NULL, *i;
806 for(c = sel->next; c && !ISVISIBLE(selmon, c); c = c->next);
808 for(c = clients; c && !ISVISIBLE(selmon, c); c = c->next);
811 for(i = clients; i != sel; i = i->next)
812 if(ISVISIBLE(selmon, i))
815 for(; i; i = i->next)
816 if(ISVISIBLE(selmon, i))
826 getclient(Window w) {
829 for(c = clients; c && c->win != w; c = c->next);
834 getcolor(const char *colstr) {
835 Colormap cmap = DefaultColormap(dpy, screen);
838 if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
839 die("error, cannot allocate color '%s'\n", colstr);
847 unsigned char *p = NULL;
848 unsigned long n, extra;
851 status = XGetWindowProperty(dpy, w, wmatom[WMState], 0L, 2L, False, wmatom[WMState],
852 &real, &format, &n, &extra, (unsigned char **)&p);
853 if(status != Success)
862 gettextprop(Window w, Atom atom, char *text, unsigned int size) {
867 if(!text || size == 0)
870 XGetTextProperty(dpy, w, &name, atom);
873 if(name.encoding == XA_STRING)
874 strncpy(text, (char *)name.value, size - 1);
876 if(XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success
878 strncpy(text, *list, size - 1);
879 XFreeStringList(list);
882 text[size - 1] = '\0';
888 grabbuttons(Client *c, Bool focused) {
892 unsigned int modifiers[] = { 0, LockMask, numlockmask, numlockmask|LockMask };
893 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
895 for(i = 0; i < LENGTH(buttons); i++)
896 if(buttons[i].click == ClkClientWin)
897 for(j = 0; j < LENGTH(modifiers); j++)
898 XGrabButton(dpy, buttons[i].button,
899 buttons[i].mask | modifiers[j],
900 c->win, False, BUTTONMASK,
901 GrabModeAsync, GrabModeSync, None, None);
903 XGrabButton(dpy, AnyButton, AnyModifier, c->win, False,
904 BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
913 unsigned int modifiers[] = { 0, LockMask, numlockmask, numlockmask|LockMask };
916 XUngrabKey(dpy, AnyKey, AnyModifier, root);
917 for(i = 0; i < LENGTH(keys); i++) {
918 if((code = XKeysymToKeycode(dpy, keys[i].keysym)))
919 for(j = 0; j < LENGTH(modifiers); j++)
920 XGrabKey(dpy, code, keys[i].mod | modifiers[j], root,
921 True, GrabModeAsync, GrabModeAsync);
927 initfont(const char *fontstr) {
928 char *def, **missing;
932 dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
935 fprintf(stderr, "dwm: missing fontset: %s\n", missing[n]);
936 XFreeStringList(missing);
939 XFontSetExtents *font_extents;
940 XFontStruct **xfonts;
942 dc.font.ascent = dc.font.descent = 0;
943 font_extents = XExtentsOfFontSet(dc.font.set);
944 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
945 for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
946 dc.font.ascent = MAX(dc.font.ascent, (*xfonts)->ascent);
947 dc.font.descent = MAX(dc.font.descent,(*xfonts)->descent);
952 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr))
953 && !(dc.font.xfont = XLoadQueryFont(dpy, "fixed")))
954 die("error, cannot load font: '%s'\n", fontstr);
955 dc.font.ascent = dc.font.xfont->ascent;
956 dc.font.descent = dc.font.xfont->descent;
958 dc.font.height = dc.font.ascent + dc.font.descent;
962 isprotodel(Client *c) {
967 if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
968 for(i = 0; !ret && i < n; i++)
969 if(protocols[i] == wmatom[WMDelete])
977 keypress(XEvent *e) {
983 keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
984 for(i = 0; i < LENGTH(keys); i++)
985 if(keysym == keys[i].keysym
986 && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state)
988 keys[i].func(&(keys[i].arg));
992 killclient(const Arg *arg) {
997 if(isprotodel(sel)) {
998 ev.type = ClientMessage;
999 ev.xclient.window = sel->win;
1000 ev.xclient.message_type = wmatom[WMProtocols];
1001 ev.xclient.format = 32;
1002 ev.xclient.data.l[0] = wmatom[WMDelete];
1003 ev.xclient.data.l[1] = CurrentTime;
1004 XSendEvent(dpy, sel->win, False, NoEventMask, &ev);
1007 XKillClient(dpy, sel->win);
1011 manage(Window w, XWindowAttributes *wa) {
1013 Client *c, *t = NULL;
1014 Window trans = None;
1017 if(!(c = malloc(sizeof(Client))))
1018 die("fatal: could not malloc() %u bytes\n", sizeof(Client));
1028 c->oldbw = wa->border_width;
1029 if(c->w == sw && c->h == sh) {
1035 if(c->x + WIDTH(c) > sx + sw)
1036 c->x = sx + sw - WIDTH(c);
1037 if(c->y + HEIGHT(c) > sy + sh)
1038 c->y = sy + sh - HEIGHT(c);
1039 c->x = MAX(c->x, sx);
1040 /* only fix client y-offset, if the client center might cover the bar */
1041 c->y = MAX(c->y, ((selmon->by == 0) && (c->x + (c->w / 2) >= selmon->wx)
1042 && (c->x + (c->w / 2) < selmon->wx + selmon->ww)) ? bh : sy);
1046 wc.border_width = c->bw;
1047 XConfigureWindow(dpy, w, CWBorderWidth, &wc);
1048 XSetWindowBorder(dpy, w, dc.norm[ColBorder]);
1049 configure(c); /* propagates border_width, if size doesn't change */
1051 XSelectInput(dpy, w, EnterWindowMask|FocusChangeMask|PropertyChangeMask|StructureNotifyMask);
1052 grabbuttons(c, False);
1054 if(XGetTransientForHint(dpy, w, &trans))
1055 t = getclient(trans);
1061 c->isfloating = trans != None || c->isfixed;
1063 XRaiseWindow(dpy, c->win);
1066 XMoveResizeWindow(dpy, c->win, c->x + 2 * sw, c->y, c->w, c->h); /* some windows require this */
1067 XMapWindow(dpy, c->win);
1068 setclientstate(c, NormalState);
1073 mappingnotify(XEvent *e) {
1074 XMappingEvent *ev = &e->xmapping;
1076 XRefreshKeyboardMapping(ev);
1077 if(ev->request == MappingKeyboard)
1082 maprequest(XEvent *e) {
1083 static XWindowAttributes wa;
1084 XMapRequestEvent *ev = &e->xmaprequest;
1086 if(!XGetWindowAttributes(dpy, ev->window, &wa))
1088 if(wa.override_redirect)
1090 if(!getclient(ev->window))
1091 manage(ev->window, &wa);
1095 monocle(Monitor *m) {
1098 for(c = nexttiled(m, clients); c; c = nexttiled(m, c->next))
1099 resize(c, m->wx, m->wy, m->ww - 2 * c->bw, m->wh - 2 * c->bw);
1103 movemouse(const Arg *arg) {
1104 int x, y, ocx, ocy, di, nx, ny;
1115 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1116 None, cursor[CurMove], CurrentTime) != GrabSuccess)
1118 XQueryPointer(dpy, root, &dummy, &dummy, &x, &y, &di, &di, &dui);
1120 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
1122 case ConfigureRequest:
1125 handler[ev.type](&ev);
1128 nx = ocx + (ev.xmotion.x - x);
1129 ny = ocy + (ev.xmotion.y - y);
1130 if(snap && nx >= selmon->wx && nx <= selmon->wx + selmon->ww
1131 && ny >= selmon->wy && ny <= selmon->wy + selmon->wh) {
1132 if(abs(selmon->wx - nx) < snap)
1134 else if(abs((selmon->wx + selmon->ww) - (nx + WIDTH(c))) < snap)
1135 nx = selmon->wx + selmon->ww - WIDTH(c);
1136 if(abs(selmon->wy - ny) < snap)
1138 else if(abs((selmon->wy + selmon->wh) - (ny + HEIGHT(c))) < snap)
1139 ny = selmon->wy + selmon->wh - HEIGHT(c);
1140 if(!c->isfloating && lt[selmon->sellt]->arrange
1141 && (abs(nx - c->x) > snap || abs(ny - c->y) > snap))
1142 togglefloating(NULL);
1144 if(!lt[selmon->sellt]->arrange || c->isfloating)
1145 resize(c, nx, ny, c->w, c->h);
1149 while(ev.type != ButtonRelease);
1150 XUngrabPointer(dpy, CurrentTime);
1154 nexttiled(Monitor *m, Client *c) {
1156 for(; c && (c->isfloating || !ISVISIBLE(m, c)); c = c->next);
1161 propertynotify(XEvent *e) {
1164 XPropertyEvent *ev = &e->xproperty;
1166 if((ev->window == root) && (ev->atom == XA_WM_NAME))
1168 else if(ev->state == PropertyDelete)
1169 return; /* ignore */
1170 else if((c = getclient(ev->window))) {
1173 case XA_WM_TRANSIENT_FOR:
1174 XGetTransientForHint(dpy, c->win, &trans);
1175 if(!c->isfloating && (c->isfloating = (getclient(trans) != NULL)))
1178 case XA_WM_NORMAL_HINTS:
1186 if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
1195 quit(const Arg *arg) {
1200 resize(Client *c, int x, int y, int w, int h) {
1203 if(applysizehints(c, &x, &y, &w, &h)) {
1206 c->w = wc.width = w;
1207 c->h = wc.height = h;
1208 wc.border_width = c->bw;
1209 XConfigureWindow(dpy, c->win,
1210 CWX|CWY|CWWidth|CWHeight|CWBorderWidth, &wc);
1217 resizemouse(const Arg *arg) {
1228 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1229 None, cursor[CurResize], CurrentTime) != GrabSuccess)
1231 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->bw - 1, c->h + c->bw - 1);
1233 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
1235 case ConfigureRequest:
1238 handler[ev.type](&ev);
1241 nw = MAX(ev.xmotion.x - ocx - 2 * c->bw + 1, 1);
1242 nh = MAX(ev.xmotion.y - ocy - 2 * c->bw + 1, 1);
1244 if(snap && nw >= selmon->wx && nw <= selmon->wx + selmon->ww
1245 && nh >= selmon->wy && nh <= selmon->wy + selmon->wh) {
1246 if(!c->isfloating && lt[selmon->sellt]->arrange
1247 && (abs(nw - c->w) > snap || abs(nh - c->h) > snap))
1248 togglefloating(NULL);
1250 if(!lt[selmon->sellt]->arrange || c->isfloating)
1251 resize(c, c->x, c->y, nw, nh);
1255 while(ev.type != ButtonRelease);
1256 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->bw - 1, c->h + c->bw - 1);
1257 XUngrabPointer(dpy, CurrentTime);
1258 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1262 restack(Monitor *m) {
1270 if(m == selmon && (sel->isfloating || !lt[m->sellt]->arrange))
1271 XRaiseWindow(dpy, sel->win);
1272 if(lt[m->sellt]->arrange) {
1273 wc.stack_mode = Below;
1274 wc.sibling = m->barwin;
1275 for(c = stack; c; c = c->snext)
1276 if(!c->isfloating && ISVISIBLE(m, c)) {
1277 XConfigureWindow(dpy, c->win, CWSibling|CWStackMode, &wc);
1278 wc.sibling = c->win;
1282 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1289 /* main event loop */
1291 while(running && !XNextEvent(dpy, &ev)) {
1292 if(handler[ev.type])
1293 (handler[ev.type])(&ev); /* call handler */
1299 unsigned int i, num;
1300 Window d1, d2, *wins = NULL;
1301 XWindowAttributes wa;
1303 if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1304 for(i = 0; i < num; i++) {
1305 if(!XGetWindowAttributes(dpy, wins[i], &wa)
1306 || wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1308 if(wa.map_state == IsViewable || getstate(wins[i]) == IconicState)
1309 manage(wins[i], &wa);
1311 for(i = 0; i < num; i++) { /* now the transients */
1312 if(!XGetWindowAttributes(dpy, wins[i], &wa))
1314 if(XGetTransientForHint(dpy, wins[i], &d1)
1315 && (wa.map_state == IsViewable || getstate(wins[i]) == IconicState))
1316 manage(wins[i], &wa);
1324 setclientstate(Client *c, long state) {
1325 long data[] = {state, None};
1327 XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1328 PropModeReplace, (unsigned char *)data, 2);
1332 setlayout(const Arg *arg) {
1333 if(!arg || !arg->v || arg->v != lt[selmon->sellt])
1336 lt[selmon->sellt] = (Layout *)arg->v;
1343 /* arg > 1.0 will set mfact absolutly */
1345 setmfact(const Arg *arg) {
1348 if(!arg || !lt[selmon->sellt]->arrange)
1350 f = arg->f < 1.0 ? arg->f + selmon->mfact : arg->f - 1.0;
1351 if(f < 0.1 || f > 0.9)
1361 XSetWindowAttributes wa;
1364 screen = DefaultScreen(dpy);
1365 root = RootWindow(dpy, screen);
1369 sw = DisplayWidth(dpy, screen);
1370 sh = DisplayHeight(dpy, screen);
1371 bh = dc.h = dc.font.height + 2;
1372 lt[0] = &layouts[0];
1373 lt[1] = &layouts[1 % LENGTH(layouts)];
1377 wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1378 wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1379 wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1380 netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1381 netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1384 cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1385 cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1386 cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1388 /* init appearance */
1389 dc.norm[ColBorder] = getcolor(normbordercolor);
1390 dc.norm[ColBG] = getcolor(normbgcolor);
1391 dc.norm[ColFG] = getcolor(normfgcolor);
1392 dc.sel[ColBorder] = getcolor(selbordercolor);
1393 dc.sel[ColBG] = getcolor(selbgcolor);
1394 dc.sel[ColFG] = getcolor(selfgcolor);
1395 dc.drawable = XCreatePixmap(dpy, root, DisplayWidth(dpy, screen), bh, DefaultDepth(dpy, screen));
1396 dc.gc = XCreateGC(dpy, root, 0, NULL);
1397 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
1399 XSetFont(dpy, dc.gc, dc.font.xfont->fid);
1402 for(blw = i = 0; LENGTH(layouts) > 1 && i < LENGTH(layouts); i++) {
1403 w = TEXTW(layouts[i].symbol);
1409 /* EWMH support per view */
1410 XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1411 PropModeReplace, (unsigned char *) netatom, NetLast);
1413 /* select for events */
1414 wa.cursor = cursor[CurNormal];
1415 wa.event_mask = SubstructureRedirectMask|SubstructureNotifyMask|ButtonPressMask
1416 |EnterWindowMask|LeaveWindowMask|StructureNotifyMask
1417 |PropertyChangeMask;
1418 XChangeWindowAttributes(dpy, root, CWEventMask|CWCursor, &wa);
1419 XSelectInput(dpy, root, wa.event_mask);
1425 showhide(Client *c) {
1428 if(ISVISIBLE((c->m), c)) { /* show clients top down */
1429 XMoveWindow(dpy, c->win, c->x, c->y);
1430 if(!lt[c->m->sellt]->arrange || c->isfloating)
1431 resize(c, c->x, c->y, c->w, c->h);
1434 else { /* hide clients bottom up */
1436 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
1442 sigchld(int signal) {
1443 while(0 < waitpid(-1, NULL, WNOHANG));
1447 spawn(const Arg *arg) {
1448 signal(SIGCHLD, sigchld);
1451 close(ConnectionNumber(dpy));
1453 execvp(((char **)arg->v)[0], (char **)arg->v);
1454 fprintf(stderr, "dwm: execvp %s", ((char **)arg->v)[0]);
1461 tag(const Arg *arg) {
1462 if(sel && arg->ui & TAGMASK) {
1463 sel->tags = arg->ui & TAGMASK;
1470 tagmon(const Arg *arg) {
1474 for(i = 0, m = mons; m; m = m->next, i++)
1481 #endif /* XINERAMA */
1484 textnw(const char *text, unsigned int len) {
1488 XmbTextExtents(dc.font.set, text, len, NULL, &r);
1491 return XTextWidth(dc.font.xfont, text, len);
1500 for(n = 0, c = nexttiled(m, clients); c; c = nexttiled(m, c->next), n++);
1505 c = nexttiled(m, clients);
1506 mw = m->mfact * m->ww;
1507 resize(c, m->wx, m->wy, (n == 1 ? m->ww : mw) - 2 * c->bw, m->wh - 2 * c->bw);
1513 x = (m->wx + mw > c->x + c->w) ? c->x + c->w + 2 * c->bw : m->wx + mw;
1515 w = (m->wx + mw > c->x + c->w) ? m->wx + m->ww - x : m->ww - mw;
1520 for(i = 0, c = nexttiled(m, c->next); c; c = nexttiled(m, c->next), i++) {
1521 resize(c, x, y, w - 2 * c->bw, /* remainder */ ((i + 1 == n)
1522 ? m->wy + m->wh - y - 2 * c->bw : h - 2 * c->bw));
1524 y = c->y + HEIGHT(c);
1529 togglebar(const Arg *arg) {
1530 selmon->showbar = !selmon->showbar;
1531 updatebarpos(selmon);
1532 XMoveResizeWindow(dpy, selmon->barwin, selmon->wx, selmon->by, selmon->ww, bh);
1537 togglefloating(const Arg *arg) {
1540 sel->isfloating = !sel->isfloating || sel->isfixed;
1542 resize(sel, sel->x, sel->y, sel->w, sel->h);
1547 toggletag(const Arg *arg) {
1553 mask = sel->tags ^ (arg->ui & TAGMASK);
1561 toggleview(const Arg *arg) {
1562 unsigned int mask = selmon->tagset[selmon->seltags] ^ (arg->ui & TAGMASK);
1565 selmon->tagset[selmon->seltags] = mask;
1571 unmanage(Client *c) {
1574 wc.border_width = c->oldbw;
1575 /* The server grab construct avoids race conditions. */
1577 XSetErrorHandler(xerrordummy);
1578 XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
1583 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1584 setclientstate(c, WithdrawnState);
1587 XSetErrorHandler(xerror);
1593 unmapnotify(XEvent *e) {
1595 XUnmapEvent *ev = &e->xunmap;
1597 if((c = getclient(ev->window)))
1604 XSetWindowAttributes wa;
1606 wa.override_redirect = True;
1607 wa.background_pixmap = ParentRelative;
1608 wa.event_mask = ButtonPressMask|ExposureMask;
1610 for(m = mons; m; m = m->next) {
1611 m->barwin = XCreateWindow(dpy, root, m->wx, m->by, m->ww, bh, 0, DefaultDepth(dpy, screen),
1613 CopyFromParent, DefaultVisual(dpy, screen),
1614 CWOverrideRedirect|CWBackPixmap|CWEventMask, &wa);
1615 XDefineCursor(dpy, m->barwin, cursor[CurNormal]);
1616 XMapRaised(dpy, m->barwin);
1621 updatebarpos(Monitor *m) {
1626 m->by = m->topbar ? m->wy : m->wy + m->wh;
1627 m->wy = m->topbar ? m->wy + bh : m->wy;
1637 Monitor *newmons = NULL, *m;
1640 XineramaScreenInfo *info = NULL;
1642 if(XineramaIsActive(dpy))
1643 info = XineramaQueryScreens(dpy, &n);
1645 /* allocate monitor(s) for the new geometry setup */
1646 for(i = 0; i < n; i++) {
1647 m = (Monitor *)malloc(sizeof(Monitor));
1652 /* initialise monitor(s) */
1654 if(XineramaIsActive(dpy)) {
1655 for(i = 0, m = newmons; m; m = m->next, i++) {
1656 m->screen_number = info[i].screen_number;
1657 m->wx = info[i].x_org;
1658 m->my = m->wy = info[i].y_org;
1659 m->ww = info[i].width;
1660 m->mh = m->wh = info[i].height;
1666 /* default monitor setup */
1668 m->screen_number = 0;
1675 /* bar geometry setup */
1676 for(m = newmons; m; m = m->next) {
1677 /* TODO: consider removing the following values from config.h */
1680 m->tagset[0] = m->tagset[1] = 1;
1682 m->showbar = showbar;
1685 /* reassign all clients with same screen number */
1686 for(c = clients; c; c = c->next)
1687 if(c->m->screen_number == m->screen_number)
1691 /* reassign left over clients with disappeared screen number */
1692 for(c = clients; c; c = c->next)
1693 if(c->m->screen_number >= n)
1696 /* select focused monitor */
1702 if(XQueryPointer(dpy, root, &dummy, &dummy, &x, &y, &di, &di, &dui))
1703 for(m = newmons; m; m = m->next)
1704 if(INRECT(x, y, m->wx, m->wy, m->ww, m->wh)) {
1710 /* final assignment of new monitors */
1716 updatenumlockmask(void) {
1718 XModifierKeymap *modmap;
1721 modmap = XGetModifierMapping(dpy);
1722 for(i = 0; i < 8; i++)
1723 for(j = 0; j < modmap->max_keypermod; j++)
1724 if(modmap->modifiermap[i * modmap->max_keypermod + j]
1725 == XKeysymToKeycode(dpy, XK_Num_Lock))
1726 numlockmask = (1 << i);
1727 XFreeModifiermap(modmap);
1731 updatesizehints(Client *c) {
1735 if(!XGetWMNormalHints(dpy, c->win, &size, &msize))
1736 /* size is uninitialized, ensure that size.flags aren't used */
1738 if(size.flags & PBaseSize) {
1739 c->basew = size.base_width;
1740 c->baseh = size.base_height;
1742 else if(size.flags & PMinSize) {
1743 c->basew = size.min_width;
1744 c->baseh = size.min_height;
1747 c->basew = c->baseh = 0;
1748 if(size.flags & PResizeInc) {
1749 c->incw = size.width_inc;
1750 c->inch = size.height_inc;
1753 c->incw = c->inch = 0;
1754 if(size.flags & PMaxSize) {
1755 c->maxw = size.max_width;
1756 c->maxh = size.max_height;
1759 c->maxw = c->maxh = 0;
1760 if(size.flags & PMinSize) {
1761 c->minw = size.min_width;
1762 c->minh = size.min_height;
1764 else if(size.flags & PBaseSize) {
1765 c->minw = size.base_width;
1766 c->minh = size.base_height;
1769 c->minw = c->minh = 0;
1770 if(size.flags & PAspect) {
1771 c->mina = (float)size.min_aspect.y / (float)size.min_aspect.x;
1772 c->maxa = (float)size.max_aspect.x / (float)size.max_aspect.y;
1775 c->maxa = c->mina = 0.0;
1776 c->isfixed = (c->maxw && c->minw && c->maxh && c->minh
1777 && c->maxw == c->minw && c->maxh == c->minh);
1781 updatetitle(Client *c) {
1782 if(!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
1783 gettextprop(c->win, XA_WM_NAME, c->name, sizeof c->name);
1788 if(!gettextprop(root, XA_WM_NAME, stext, sizeof(stext)))
1789 strcpy(stext, "dwm-"VERSION);
1794 updatewmhints(Client *c) {
1797 if((wmh = XGetWMHints(dpy, c->win))) {
1798 if(c == sel && wmh->flags & XUrgencyHint) {
1799 wmh->flags &= ~XUrgencyHint;
1800 XSetWMHints(dpy, c->win, wmh);
1803 c->isurgent = (wmh->flags & XUrgencyHint) ? True : False;
1810 view(const Arg *arg) {
1811 if((arg->ui & TAGMASK) == selmon->tagset[selmon->seltags])
1813 selmon->seltags ^= 1; /* toggle sel tagset */
1814 if(arg->ui & TAGMASK)
1815 selmon->tagset[selmon->seltags] = arg->ui & TAGMASK;
1819 /* There's no way to check accesses to destroyed windows, thus those cases are
1820 * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
1821 * default error handler, which may call exit. */
1823 xerror(Display *dpy, XErrorEvent *ee) {
1824 if(ee->error_code == BadWindow
1825 || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1826 || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1827 || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1828 || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1829 || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1830 || (ee->request_code == X_GrabButton && ee->error_code == BadAccess)
1831 || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1832 || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1834 fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1835 ee->request_code, ee->error_code);
1836 return xerrorxlib(dpy, ee); /* may call exit */
1840 xerrordummy(Display *dpy, XErrorEvent *ee) {
1844 /* Startup Error handler to check if another window manager
1845 * is already running. */
1847 xerrorstart(Display *dpy, XErrorEvent *ee) {
1853 zoom(const Arg *arg) {
1856 if(!lt[selmon->sellt]->arrange || lt[selmon->sellt]->arrange == monocle || (sel && sel->isfloating))
1858 if(c == nexttiled(selmon, clients))
1859 if(!c || !(c = nexttiled(selmon, c->next)))
1868 main(int argc, char *argv[]) {
1869 if(argc == 2 && !strcmp("-v", argv[1]))
1870 die("dwm-"VERSION", © 2006-2009 dwm engineers, see LICENSE for details\n");
1872 die("usage: dwm [-v]\n");
1874 if(!setlocale(LC_CTYPE, "") || !XSupportsLocale())
1875 fputs("warning: no locale support\n", stderr);
1877 if(!(dpy = XOpenDisplay(NULL)))
1878 die("dwm: cannot open display\n");