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 & 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 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;
124 unsigned int tagset[2];
132 void (*arrange)(Monitor *);
137 const char *instance;
143 /* function declarations */
144 static void applyrules(Client *c);
145 static Bool applysizehints(Client *c, int *x, int *y, int *w, int *h);
146 static void arrange(void);
147 static void attach(Client *c);
148 static void attachstack(Client *c);
149 static void buttonpress(XEvent *e);
150 static void checkotherwm(void);
151 static void cleanup(void);
152 static void clearurgent(Client *c);
153 static void configure(Client *c);
154 static void configurenotify(XEvent *e);
155 static void configurerequest(XEvent *e);
156 static void destroynotify(XEvent *e);
157 static void detach(Client *c);
158 static void detachstack(Client *c);
159 static void die(const char *errstr, ...);
160 static void drawbar(Monitor *m);
161 static void drawbars();
162 static void drawsquare(Bool filled, Bool empty, Bool invert, unsigned long col[ColLast]);
163 static void drawtext(const char *text, unsigned long col[ColLast], Bool invert);
164 static void enternotify(XEvent *e);
165 static void expose(XEvent *e);
166 static void focus(Client *c);
167 static void focusin(XEvent *e);
168 static void focusstack(const Arg *arg);
169 static Client *getclient(Window w);
170 static unsigned long getcolor(const char *colstr);
171 static long getstate(Window w);
172 static Bool gettextprop(Window w, Atom atom, char *text, unsigned int size);
173 static void grabbuttons(Client *c, Bool focused);
174 static void grabkeys(void);
175 static void initfont(const char *fontstr);
176 static Bool isprotodel(Client *c);
177 static void keypress(XEvent *e);
178 static void killclient(const Arg *arg);
179 static void manage(Window w, XWindowAttributes *wa);
180 static void mappingnotify(XEvent *e);
181 static void maprequest(XEvent *e);
182 static void monocle(Monitor *m);
183 static void movemouse(const Arg *arg);
184 static Client *nexttiled(Monitor *m, Client *c);
185 static void propertynotify(XEvent *e);
186 static void quit(const Arg *arg);
187 static void resize(Client *c, int x, int y, int w, int h);
188 static void resizemouse(const Arg *arg);
189 static void restack(Monitor *m);
190 static void run(void);
191 static void scan(void);
192 static void setclientstate(Client *c, long state);
193 static void setlayout(const Arg *arg);
194 static void setmfact(const Arg *arg);
195 static void setup(void);
196 static void showhide(Client *c);
197 static void sigchld(int signal);
198 static void spawn(const Arg *arg);
199 static void tag(const Arg *arg);
200 static int textnw(const char *text, unsigned int len);
201 static void tile(Monitor *);
202 static void togglebar(const Arg *arg);
203 static void togglefloating(const Arg *arg);
204 static void toggletag(const Arg *arg);
205 static void toggleview(const Arg *arg);
206 static void unmanage(Client *c);
207 static void unmapnotify(XEvent *e);
208 static void updategeom(void);
209 static void updatenumlockmask(void);
210 static void updatesizehints(Client *c);
211 static void updatestatus(void);
212 static void updatetitle(Client *c);
213 static void updatewmhints(Client *c);
214 static void view(const Arg *arg);
215 static int xerror(Display *dpy, XErrorEvent *ee);
216 static int xerrordummy(Display *dpy, XErrorEvent *ee);
217 static int xerrorstart(Display *dpy, XErrorEvent *ee);
218 static void zoom(const Arg *arg);
220 static void focusmon(const Arg *arg);
221 static void tagmon(const Arg *arg);
222 #endif /* XINERAMA */
225 static char stext[256];
227 static int sx, sy, sw, sh; /* X display screen geometry x, y, width, height */
228 static int bh, blw = 0; /* bar geometry */
229 static int (*xerrorxlib)(Display *, XErrorEvent *);
230 static unsigned int numlockmask = 0;
231 static void (*handler[LASTEvent]) (XEvent *) = {
232 [ButtonPress] = buttonpress,
233 [ConfigureRequest] = configurerequest,
234 [ConfigureNotify] = configurenotify,
235 [DestroyNotify] = destroynotify,
236 [EnterNotify] = enternotify,
239 [KeyPress] = keypress,
240 [MappingNotify] = mappingnotify,
241 [MapRequest] = maprequest,
242 [PropertyNotify] = propertynotify,
243 [UnmapNotify] = unmapnotify
245 static Atom wmatom[WMLast], netatom[NetLast];
247 static Bool running = True;
248 static Client *clients = NULL;
249 static Client *sel = NULL;
250 static Client *stack = NULL;
251 static Cursor cursor[CurLast];
254 static Layout *lt[] = { NULL, NULL };
255 static Monitor *mon = NULL, *selmon = NULL;
256 static unsigned int nmons = 0;
258 /* configuration, allows nested code to access above variables */
261 /* compile-time check if all tags fit into an unsigned int bit array. */
262 struct NumTags { char limitexceeded[sizeof(unsigned int) * 8 < LENGTH(tags) ? -1 : 1]; };
264 /* function implementations */
266 applyrules(Client *c) {
269 XClassHint ch = { 0 };
272 c->isfloating = c->tags = 0;
273 if(XGetClassHint(dpy, c->win, &ch)) {
274 for(i = 0; i < LENGTH(rules); i++) {
276 if((!r->title || strstr(c->name, r->title))
277 && (!r->class || (ch.res_class && strstr(ch.res_class, r->class)))
278 && (!r->instance || (ch.res_name && strstr(ch.res_name, r->instance)))) {
279 c->isfloating = r->isfloating;
288 c->tags = c->tags & TAGMASK ? c->tags & TAGMASK : mon[c->mon].tagset[mon[c->mon].seltags];
292 applysizehints(Client *c, int *x, int *y, int *w, int *h) {
295 /* set minimum possible */
303 if(*x + *w + 2 * c->bw < sx)
305 if(*y + *h + 2 * c->bw < sy)
312 if(resizehints || c->isfloating) {
313 /* see last two sentences in ICCCM 4.1.2.3 */
314 baseismin = c->basew == c->minw && c->baseh == c->minh;
316 if(!baseismin) { /* temporarily remove base dimensions */
321 /* adjust for aspect limits */
322 if(c->mina > 0 && c->maxa > 0) {
323 if(c->maxa < (float)*w / *h)
325 else if(c->mina < (float)*h / *w)
329 if(baseismin) { /* increment calculation requires this */
334 /* adjust for increment value */
340 /* restore base dimensions */
344 *w = MAX(*w, c->minw);
345 *h = MAX(*h, c->minh);
348 *w = MIN(*w, c->maxw);
351 *h = MIN(*h, c->maxh);
353 return *x != c->x || *y != c->y || *w != c->w || *h != c->h;
361 for(i = 0; i < nmons; i++) {
362 if(lt[mon[i].sellt]->arrange)
363 lt[mon[i].sellt]->arrange(&mon[i]);
375 attachstack(Client *c) {
381 buttonpress(XEvent *e) {
382 unsigned int i, x, click;
385 XButtonPressedEvent *ev = &e->xbutton;
388 if(ev->window == selmon->barwin) {
393 while(ev->x >= x && ++i < LENGTH(tags));
394 if(i < LENGTH(tags)) {
398 else if(ev->x < x + blw)
400 else if(ev->x > selmon->wx + selmon->ww - TEXTW(stext))
401 click = ClkStatusText;
405 else if((c = getclient(ev->window))) {
407 click = ClkClientWin;
410 for(i = 0; i < LENGTH(buttons); i++)
411 if(click == buttons[i].click && buttons[i].func && buttons[i].button == ev->button
412 && CLEANMASK(buttons[i].mask) == CLEANMASK(ev->state))
413 buttons[i].func(click == ClkTagBar && buttons[i].arg.i == 0 ? &arg : &buttons[i].arg);
419 xerrorxlib = XSetErrorHandler(xerrorstart);
421 /* this causes an error if some other window manager is running */
422 XSelectInput(dpy, DefaultRootWindow(dpy), SubstructureRedirectMask);
425 die("dwm: another window manager is already running\n");
426 XSetErrorHandler(xerror);
434 Layout foo = { "", NULL };
437 lt[selmon->sellt] = &foo;
441 XFreeFontSet(dpy, dc.font.set);
443 XFreeFont(dpy, dc.font.xfont);
444 XUngrabKey(dpy, AnyKey, AnyModifier, root);
445 XFreePixmap(dpy, dc.drawable);
447 XFreeCursor(dpy, cursor[CurNormal]);
448 XFreeCursor(dpy, cursor[CurResize]);
449 XFreeCursor(dpy, cursor[CurMove]);
450 for(i = 0; i < nmons; i++)
451 XDestroyWindow(dpy, mon[i].barwin);
454 XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime);
458 clearurgent(Client *c) {
462 if(!(wmh = XGetWMHints(dpy, c->win)))
464 wmh->flags &= ~XUrgencyHint;
465 XSetWMHints(dpy, c->win, wmh);
470 configure(Client *c) {
473 ce.type = ConfigureNotify;
481 ce.border_width = c->bw;
483 ce.override_redirect = False;
484 XSendEvent(dpy, c->win, False, StructureNotifyMask, (XEvent *)&ce);
488 configurenotify(XEvent *e) {
490 XConfigureEvent *ev = &e->xconfigure;
492 if(ev->window == root && (ev->width != sw || ev->height != sh)) {
497 XFreePixmap(dpy, dc.drawable);
498 dc.drawable = XCreatePixmap(dpy, root, sw, bh, DefaultDepth(dpy, screen));
499 for(i = 0; i < nmons; i++)
500 XMoveResizeWindow(dpy, mon[i].barwin, mon[i].wx, mon[i].by, mon[i].ww, bh);
506 configurerequest(XEvent *e) {
508 XConfigureRequestEvent *ev = &e->xconfigurerequest;
511 if((c = getclient(ev->window))) {
512 if(ev->value_mask & CWBorderWidth)
513 c->bw = ev->border_width;
514 else if(c->isfloating || !lt[selmon->sellt]->arrange) {
515 if(ev->value_mask & CWX)
517 if(ev->value_mask & CWY)
519 if(ev->value_mask & CWWidth)
521 if(ev->value_mask & CWHeight)
523 if((c->x - sx + c->w) > sw && c->isfloating)
524 c->x = sx + (sw / 2 - c->w / 2); /* center in x direction */
525 if((c->y - sy + c->h) > sh && c->isfloating)
526 c->y = sy + (sh / 2 - c->h / 2); /* center in y direction */
527 if((ev->value_mask & (CWX|CWY)) && !(ev->value_mask & (CWWidth|CWHeight)))
529 if(ISVISIBLE((&mon[c->mon]), c))
530 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h);
538 wc.width = ev->width;
539 wc.height = ev->height;
540 wc.border_width = ev->border_width;
541 wc.sibling = ev->above;
542 wc.stack_mode = ev->detail;
543 XConfigureWindow(dpy, ev->window, ev->value_mask, &wc);
549 destroynotify(XEvent *e) {
551 XDestroyWindowEvent *ev = &e->xdestroywindow;
553 if((c = getclient(ev->window)))
561 for(tc = &clients; *tc && *tc != c; tc = &(*tc)->next);
566 detachstack(Client *c) {
569 for(tc = &stack; *tc && *tc != c; tc = &(*tc)->snext);
574 die(const char *errstr, ...) {
577 va_start(ap, errstr);
578 vfprintf(stderr, errstr, ap);
584 drawbar(Monitor *m) {
586 unsigned int i, occ = 0, urg = 0;
590 for(c = clients; c; c = c->next) {
591 if(m == &mon[c->mon]) {
601 dc.w = TEXTW(m->symbol);
602 drawtext(m->symbol, selmon == m ? dc.sel : dc.norm, False);
605 #endif /* XINERAMA */
607 for(i = 0; i < LENGTH(tags); i++) {
608 dc.w = TEXTW(tags[i]);
609 col = m->tagset[m->seltags] & 1 << i ? dc.sel : dc.norm;
610 drawtext(tags[i], col, urg & 1 << i);
611 drawsquare(m == selmon && sel && sel->tags & 1 << i,
612 occ & 1 << i, urg & 1 << i, col);
617 drawtext(lt[m->sellt]->symbol, dc.norm, False);
629 drawtext(stext, dc.norm, False);
630 if((dc.w = dc.x - x) > bh) {
633 drawtext(sel->name, dc.sel, False);
634 drawsquare(sel->isfixed, sel->isfloating, False, dc.sel);
637 drawtext(NULL, dc.norm, False);
643 drawtext(NULL, dc.norm, False);
645 XCopyArea(dpy, dc.drawable, m->barwin, dc.gc, 0, 0, m->ww, bh, 0, 0);
653 for(i = 0; i < nmons; i++)
658 drawsquare(Bool filled, Bool empty, Bool invert, unsigned long col[ColLast]) {
661 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
663 gcv.foreground = col[invert ? ColBG : ColFG];
664 XChangeGC(dpy, dc.gc, GCForeground, &gcv);
665 x = (dc.font.ascent + dc.font.descent + 2) / 4;
669 r.width = r.height = x + 1;
670 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
673 r.width = r.height = x;
674 XDrawRectangles(dpy, dc.drawable, dc.gc, &r, 1);
679 drawtext(const char *text, unsigned long col[ColLast], Bool invert) {
681 int i, x, y, h, len, olen;
682 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
684 XSetForeground(dpy, dc.gc, col[invert ? ColFG : ColBG]);
685 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
689 h = dc.font.ascent + dc.font.descent;
690 y = dc.y + (dc.h / 2) - (h / 2) + dc.font.ascent;
692 /* shorten text if necessary */
693 for(len = MIN(olen, sizeof buf); len && textnw(text, len) > dc.w - h; len--);
696 memcpy(buf, text, len);
698 for(i = len; i && i > len - 3; buf[--i] = '.');
699 XSetForeground(dpy, dc.gc, col[invert ? ColBG : ColFG]);
701 XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
703 XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
707 enternotify(XEvent *e) {
709 XCrossingEvent *ev = &e->xcrossing;
711 if((ev->mode != NotifyNormal || ev->detail == NotifyInferior) && ev->window != root)
713 if((c = getclient(ev->window)))
722 XExposeEvent *ev = &e->xexpose;
725 for(i = 0; i < nmons; i++)
726 if(ev->window == mon[i].barwin) {
734 if(!c || !ISVISIBLE((&mon[c->mon]), c))
735 for(c = stack; c && !ISVISIBLE(selmon, c); c = c->snext);
736 if(sel && sel != c) {
737 grabbuttons(sel, False);
738 XSetWindowBorder(dpy, sel->win, dc.norm[ColBorder]);
745 grabbuttons(c, True);
746 XSetWindowBorder(dpy, c->win, dc.sel[ColBorder]);
747 XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
750 XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
756 focusin(XEvent *e) { /* there are some broken focus acquiring clients */
757 XFocusChangeEvent *ev = &e->xfocus;
759 if(sel && ev->window != sel->win)
760 XSetInputFocus(dpy, sel->win, RevertToPointerRoot, CurrentTime);
765 focusmon(const Arg *arg) {
768 selmon = &mon[arg->ui];
772 #endif /* XINERAMA */
775 focusstack(const Arg *arg) {
776 Client *c = NULL, *i;
781 for(c = sel->next; c && !ISVISIBLE(selmon, c); c = c->next);
783 for(c = clients; c && !ISVISIBLE(selmon, c); c = c->next);
786 for(i = clients; i != sel; i = i->next)
787 if(ISVISIBLE(selmon, i))
790 for(; i; i = i->next)
791 if(ISVISIBLE(selmon, i))
801 getclient(Window w) {
804 for(c = clients; c && c->win != w; c = c->next);
809 getcolor(const char *colstr) {
810 Colormap cmap = DefaultColormap(dpy, screen);
813 if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
814 die("error, cannot allocate color '%s'\n", colstr);
822 unsigned char *p = NULL;
823 unsigned long n, extra;
826 status = XGetWindowProperty(dpy, w, wmatom[WMState], 0L, 2L, False, wmatom[WMState],
827 &real, &format, &n, &extra, (unsigned char **)&p);
828 if(status != Success)
837 gettextprop(Window w, Atom atom, char *text, unsigned int size) {
842 if(!text || size == 0)
845 XGetTextProperty(dpy, w, &name, atom);
848 if(name.encoding == XA_STRING)
849 strncpy(text, (char *)name.value, size - 1);
851 if(XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success
853 strncpy(text, *list, size - 1);
854 XFreeStringList(list);
857 text[size - 1] = '\0';
863 grabbuttons(Client *c, Bool focused) {
867 unsigned int modifiers[] = { 0, LockMask, numlockmask, numlockmask|LockMask };
868 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
870 for(i = 0; i < LENGTH(buttons); i++)
871 if(buttons[i].click == ClkClientWin)
872 for(j = 0; j < LENGTH(modifiers); j++)
873 XGrabButton(dpy, buttons[i].button,
874 buttons[i].mask | modifiers[j],
875 c->win, False, BUTTONMASK,
876 GrabModeAsync, GrabModeSync, None, None);
878 XGrabButton(dpy, AnyButton, AnyModifier, c->win, False,
879 BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
888 unsigned int modifiers[] = { 0, LockMask, numlockmask, numlockmask|LockMask };
891 XUngrabKey(dpy, AnyKey, AnyModifier, root);
892 for(i = 0; i < LENGTH(keys); i++) {
893 if((code = XKeysymToKeycode(dpy, keys[i].keysym)))
894 for(j = 0; j < LENGTH(modifiers); j++)
895 XGrabKey(dpy, code, keys[i].mod | modifiers[j], root,
896 True, GrabModeAsync, GrabModeAsync);
902 initfont(const char *fontstr) {
903 char *def, **missing;
907 dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
910 fprintf(stderr, "dwm: missing fontset: %s\n", missing[n]);
911 XFreeStringList(missing);
914 XFontSetExtents *font_extents;
915 XFontStruct **xfonts;
917 dc.font.ascent = dc.font.descent = 0;
918 font_extents = XExtentsOfFontSet(dc.font.set);
919 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
920 for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
921 dc.font.ascent = MAX(dc.font.ascent, (*xfonts)->ascent);
922 dc.font.descent = MAX(dc.font.descent,(*xfonts)->descent);
927 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr))
928 && !(dc.font.xfont = XLoadQueryFont(dpy, "fixed")))
929 die("error, cannot load font: '%s'\n", fontstr);
930 dc.font.ascent = dc.font.xfont->ascent;
931 dc.font.descent = dc.font.xfont->descent;
933 dc.font.height = dc.font.ascent + dc.font.descent;
937 isprotodel(Client *c) {
942 if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
943 for(i = 0; !ret && i < n; i++)
944 if(protocols[i] == wmatom[WMDelete])
952 keypress(XEvent *e) {
958 keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
959 for(i = 0; i < LENGTH(keys); i++)
960 if(keysym == keys[i].keysym
961 && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state)
963 keys[i].func(&(keys[i].arg));
967 killclient(const Arg *arg) {
972 if(isprotodel(sel)) {
973 ev.type = ClientMessage;
974 ev.xclient.window = sel->win;
975 ev.xclient.message_type = wmatom[WMProtocols];
976 ev.xclient.format = 32;
977 ev.xclient.data.l[0] = wmatom[WMDelete];
978 ev.xclient.data.l[1] = CurrentTime;
979 XSendEvent(dpy, sel->win, False, NoEventMask, &ev);
982 XKillClient(dpy, sel->win);
986 manage(Window w, XWindowAttributes *wa) {
988 Client *c, *t = NULL;
992 if(!(c = malloc(sizeof(Client))))
993 die("fatal: could not malloc() %u bytes\n", sizeof(Client));
996 for(c->mon = 0; selmon != &mon[c->mon]; c->mon++);
1003 c->oldbw = wa->border_width;
1004 if(c->w == sw && c->h == sh) {
1010 if(c->x + WIDTH(c) > sx + sw)
1011 c->x = sx + sw - WIDTH(c);
1012 if(c->y + HEIGHT(c) > sy + sh)
1013 c->y = sy + sh - HEIGHT(c);
1014 c->x = MAX(c->x, sx);
1015 /* only fix client y-offset, if the client center might cover the bar */
1016 c->y = MAX(c->y, ((selmon->by == 0) && (c->x + (c->w / 2) >= selmon->wx)
1017 && (c->x + (c->w / 2) < selmon->wx + selmon->ww)) ? bh : sy);
1021 wc.border_width = c->bw;
1022 XConfigureWindow(dpy, w, CWBorderWidth, &wc);
1023 XSetWindowBorder(dpy, w, dc.norm[ColBorder]);
1024 configure(c); /* propagates border_width, if size doesn't change */
1026 XSelectInput(dpy, w, EnterWindowMask|FocusChangeMask|PropertyChangeMask|StructureNotifyMask);
1027 grabbuttons(c, False);
1029 if(XGetTransientForHint(dpy, w, &trans))
1030 t = getclient(trans);
1036 c->isfloating = trans != None || c->isfixed;
1038 XRaiseWindow(dpy, c->win);
1041 XMoveResizeWindow(dpy, c->win, c->x + 2 * sw, c->y, c->w, c->h); /* some windows require this */
1042 XMapWindow(dpy, c->win);
1043 setclientstate(c, NormalState);
1048 mappingnotify(XEvent *e) {
1049 XMappingEvent *ev = &e->xmapping;
1051 XRefreshKeyboardMapping(ev);
1052 if(ev->request == MappingKeyboard)
1057 maprequest(XEvent *e) {
1058 static XWindowAttributes wa;
1059 XMapRequestEvent *ev = &e->xmaprequest;
1061 if(!XGetWindowAttributes(dpy, ev->window, &wa))
1063 if(wa.override_redirect)
1065 if(!getclient(ev->window))
1066 manage(ev->window, &wa);
1070 monocle(Monitor *m) {
1073 for(c = nexttiled(m, clients); c; c = nexttiled(m, c->next))
1074 resize(c, m->wx, m->wy, m->ww - 2 * c->bw, m->wh - 2 * c->bw);
1078 movemouse(const Arg *arg) {
1079 int x, y, ocx, ocy, di, nx, ny;
1090 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1091 None, cursor[CurMove], CurrentTime) != GrabSuccess)
1093 XQueryPointer(dpy, root, &dummy, &dummy, &x, &y, &di, &di, &dui);
1095 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
1097 case ConfigureRequest:
1100 handler[ev.type](&ev);
1103 nx = ocx + (ev.xmotion.x - x);
1104 ny = ocy + (ev.xmotion.y - y);
1105 if(snap && nx >= selmon->wx && nx <= selmon->wx + selmon->ww
1106 && ny >= selmon->wy && ny <= selmon->wy + selmon->wh) {
1107 if(abs(selmon->wx - nx) < snap)
1109 else if(abs((selmon->wx + selmon->ww) - (nx + WIDTH(c))) < snap)
1110 nx = selmon->wx + selmon->ww - WIDTH(c);
1111 if(abs(selmon->wy - ny) < snap)
1113 else if(abs((selmon->wy + selmon->wh) - (ny + HEIGHT(c))) < snap)
1114 ny = selmon->wy + selmon->wh - HEIGHT(c);
1115 if(!c->isfloating && lt[selmon->sellt]->arrange
1116 && (abs(nx - c->x) > snap || abs(ny - c->y) > snap))
1117 togglefloating(NULL);
1119 if(!lt[selmon->sellt]->arrange || c->isfloating)
1120 resize(c, nx, ny, c->w, c->h);
1124 while(ev.type != ButtonRelease);
1125 XUngrabPointer(dpy, CurrentTime);
1129 nexttiled(Monitor *m, Client *c) {
1131 for(; c && (c->isfloating || !ISVISIBLE(m, c)); c = c->next);
1136 propertynotify(XEvent *e) {
1139 XPropertyEvent *ev = &e->xproperty;
1141 if((ev->window == root) && (ev->atom == XA_WM_NAME))
1143 else if(ev->state == PropertyDelete)
1144 return; /* ignore */
1145 else if((c = getclient(ev->window))) {
1148 case XA_WM_TRANSIENT_FOR:
1149 XGetTransientForHint(dpy, c->win, &trans);
1150 if(!c->isfloating && (c->isfloating = (getclient(trans) != NULL)))
1153 case XA_WM_NORMAL_HINTS:
1161 if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
1170 quit(const Arg *arg) {
1175 resize(Client *c, int x, int y, int w, int h) {
1178 if(applysizehints(c, &x, &y, &w, &h)) {
1181 c->w = wc.width = w;
1182 c->h = wc.height = h;
1183 wc.border_width = c->bw;
1184 XConfigureWindow(dpy, c->win,
1185 CWX|CWY|CWWidth|CWHeight|CWBorderWidth, &wc);
1192 resizemouse(const Arg *arg) {
1203 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1204 None, cursor[CurResize], CurrentTime) != GrabSuccess)
1206 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->bw - 1, c->h + c->bw - 1);
1208 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
1210 case ConfigureRequest:
1213 handler[ev.type](&ev);
1216 nw = MAX(ev.xmotion.x - ocx - 2 * c->bw + 1, 1);
1217 nh = MAX(ev.xmotion.y - ocy - 2 * c->bw + 1, 1);
1219 if(snap && nw >= selmon->wx && nw <= selmon->wx + selmon->ww
1220 && nh >= selmon->wy && nh <= selmon->wy + selmon->wh) {
1221 if(!c->isfloating && lt[selmon->sellt]->arrange
1222 && (abs(nw - c->w) > snap || abs(nh - c->h) > snap))
1223 togglefloating(NULL);
1225 if(!lt[selmon->sellt]->arrange || c->isfloating)
1226 resize(c, c->x, c->y, nw, nh);
1230 while(ev.type != ButtonRelease);
1231 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->bw - 1, c->h + c->bw - 1);
1232 XUngrabPointer(dpy, CurrentTime);
1233 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1237 restack(Monitor *m) {
1245 if(m == selmon && (sel->isfloating || !lt[m->sellt]->arrange))
1246 XRaiseWindow(dpy, sel->win);
1247 if(lt[m->sellt]->arrange) {
1248 wc.stack_mode = Below;
1249 wc.sibling = m->barwin;
1250 for(c = stack; c; c = c->snext)
1251 if(!c->isfloating && ISVISIBLE(m, c)) {
1252 XConfigureWindow(dpy, c->win, CWSibling|CWStackMode, &wc);
1253 wc.sibling = c->win;
1257 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1264 /* main event loop */
1266 while(running && !XNextEvent(dpy, &ev)) {
1267 if(handler[ev.type])
1268 (handler[ev.type])(&ev); /* call handler */
1274 unsigned int i, num;
1275 Window d1, d2, *wins = NULL;
1276 XWindowAttributes wa;
1278 if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1279 for(i = 0; i < num; i++) {
1280 if(!XGetWindowAttributes(dpy, wins[i], &wa)
1281 || wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1283 if(wa.map_state == IsViewable || getstate(wins[i]) == IconicState)
1284 manage(wins[i], &wa);
1286 for(i = 0; i < num; i++) { /* now the transients */
1287 if(!XGetWindowAttributes(dpy, wins[i], &wa))
1289 if(XGetTransientForHint(dpy, wins[i], &d1)
1290 && (wa.map_state == IsViewable || getstate(wins[i]) == IconicState))
1291 manage(wins[i], &wa);
1299 setclientstate(Client *c, long state) {
1300 long data[] = {state, None};
1302 XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1303 PropModeReplace, (unsigned char *)data, 2);
1307 setlayout(const Arg *arg) {
1308 if(!arg || !arg->v || arg->v != lt[selmon->sellt])
1311 lt[selmon->sellt] = (Layout *)arg->v;
1318 /* arg > 1.0 will set mfact absolutly */
1320 setmfact(const Arg *arg) {
1323 if(!arg || !lt[selmon->sellt]->arrange)
1325 f = arg->f < 1.0 ? arg->f + selmon->mfact : arg->f - 1.0;
1326 if(f < 0.1 || f > 0.9)
1336 XSetWindowAttributes wa;
1339 screen = DefaultScreen(dpy);
1340 root = RootWindow(dpy, screen);
1344 sw = DisplayWidth(dpy, screen);
1345 sh = DisplayHeight(dpy, screen);
1346 bh = dc.h = dc.font.height + 2;
1347 lt[0] = &layouts[0];
1348 lt[1] = &layouts[1 % LENGTH(layouts)];
1352 wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1353 wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1354 wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1355 netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1356 netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1359 wa.cursor = cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1360 cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1361 cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1363 /* init appearance */
1364 dc.norm[ColBorder] = getcolor(normbordercolor);
1365 dc.norm[ColBG] = getcolor(normbgcolor);
1366 dc.norm[ColFG] = getcolor(normfgcolor);
1367 dc.sel[ColBorder] = getcolor(selbordercolor);
1368 dc.sel[ColBG] = getcolor(selbgcolor);
1369 dc.sel[ColFG] = getcolor(selfgcolor);
1370 dc.drawable = XCreatePixmap(dpy, root, DisplayWidth(dpy, screen), bh, DefaultDepth(dpy, screen));
1371 dc.gc = XCreateGC(dpy, root, 0, NULL);
1372 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
1374 XSetFont(dpy, dc.gc, dc.font.xfont->fid);
1377 wa.override_redirect = True;
1378 wa.background_pixmap = ParentRelative;
1379 wa.event_mask = ButtonPressMask|ExposureMask;
1380 for(blw = i = 0; LENGTH(layouts) > 1 && i < LENGTH(layouts); i++) {
1381 w = TEXTW(layouts[i].symbol);
1385 for(i = 0; i < nmons; i++) {
1386 mon[i].barwin = XCreateWindow(dpy, root, mon[i].wx, mon[i].by, mon[i].ww, bh, 0, DefaultDepth(dpy, screen),
1388 CopyFromParent, DefaultVisual(dpy, screen),
1389 CWOverrideRedirect|CWBackPixmap|CWEventMask, &wa);
1390 XDefineCursor(dpy, mon[i].barwin, cursor[CurNormal]);
1391 XMapRaised(dpy, mon[i].barwin);
1395 /* EWMH support per view */
1396 XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1397 PropModeReplace, (unsigned char *) netatom, NetLast);
1399 /* select for events */
1400 wa.event_mask = SubstructureRedirectMask|SubstructureNotifyMask|ButtonPressMask
1401 |EnterWindowMask|LeaveWindowMask|StructureNotifyMask
1402 |PropertyChangeMask;
1403 XChangeWindowAttributes(dpy, root, CWEventMask|CWCursor, &wa);
1404 XSelectInput(dpy, root, wa.event_mask);
1410 showhide(Client *c) {
1413 if(ISVISIBLE((&mon[c->mon]), c)) { /* show clients top down */
1414 XMoveWindow(dpy, c->win, c->x, c->y);
1415 if(!lt[mon[c->mon].sellt]->arrange || c->isfloating)
1416 resize(c, c->x, c->y, c->w, c->h);
1419 else { /* hide clients bottom up */
1421 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
1427 sigchld(int signal) {
1428 while(0 < waitpid(-1, NULL, WNOHANG));
1432 spawn(const Arg *arg) {
1433 signal(SIGCHLD, sigchld);
1436 close(ConnectionNumber(dpy));
1438 execvp(((char **)arg->v)[0], (char **)arg->v);
1439 fprintf(stderr, "dwm: execvp %s", ((char **)arg->v)[0]);
1446 tag(const Arg *arg) {
1447 if(sel && arg->ui & TAGMASK) {
1448 sel->tags = arg->ui & TAGMASK;
1455 tagmon(const Arg *arg) {
1456 if(!sel || arg->ui >= nmons)
1461 #endif /* XINERAMA */
1464 textnw(const char *text, unsigned int len) {
1468 XmbTextExtents(dc.font.set, text, len, NULL, &r);
1471 return XTextWidth(dc.font.xfont, text, len);
1480 for(n = 0, c = nexttiled(m, clients); c; c = nexttiled(m, c->next), n++);
1485 c = nexttiled(m, clients);
1486 mw = m->mfact * m->ww;
1487 resize(c, m->wx, m->wy, (n == 1 ? m->ww : mw) - 2 * c->bw, m->wh - 2 * c->bw);
1493 x = (m->wx + mw > c->x + c->w) ? c->x + c->w + 2 * c->bw : m->wx + mw;
1495 w = (m->wx + mw > c->x + c->w) ? m->wx + m->ww - x : m->ww - mw;
1500 for(i = 0, c = nexttiled(m, c->next); c; c = nexttiled(m, c->next), i++) {
1501 resize(c, x, y, w - 2 * c->bw, /* remainder */ ((i + 1 == n)
1502 ? m->wy + m->wh - y - 2 * c->bw : h - 2 * c->bw));
1504 y = c->y + HEIGHT(c);
1509 togglebar(const Arg *arg) {
1510 selmon->showbar = !selmon->showbar;
1512 XMoveResizeWindow(dpy, selmon->barwin, selmon->wx, selmon->by, selmon->ww, bh);
1517 togglefloating(const Arg *arg) {
1520 sel->isfloating = !sel->isfloating || sel->isfixed;
1522 resize(sel, sel->x, sel->y, sel->w, sel->h);
1527 toggletag(const Arg *arg) {
1533 mask = sel->tags ^ (arg->ui & TAGMASK);
1541 toggleview(const Arg *arg) {
1542 unsigned int mask = selmon->tagset[selmon->seltags] ^ (arg->ui & TAGMASK);
1545 selmon->tagset[selmon->seltags] = mask;
1551 unmanage(Client *c) {
1554 wc.border_width = c->oldbw;
1555 /* The server grab construct avoids race conditions. */
1557 XSetErrorHandler(xerrordummy);
1558 XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
1563 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1564 setclientstate(c, WithdrawnState);
1567 XSetErrorHandler(xerror);
1573 unmapnotify(XEvent *e) {
1575 XUnmapEvent *ev = &e->xunmap;
1577 if((c = getclient(ev->window)))
1587 XineramaScreenInfo *info = NULL;
1589 /* window area geometry */
1590 if(XineramaIsActive(dpy) && (info = XineramaQueryScreens(dpy, &n))) {
1592 for(c = clients; c; c = c->next)
1595 if(!(mon = (Monitor *)realloc(mon, sizeof(Monitor) * n)))
1596 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;
1609 mon[i].tagset[0] = mon[i].tagset[1] = 1;
1611 mon[i].wx = info[i].x_org;
1612 mon[i].wy = mon[i].showbar && mon[i].topbar ? info[i].y_org + bh : info[i].y_org;
1613 mon[i].ww = info[i].width;
1614 mon[i].wh = mon[i].showbar ? info[i].height - bh : info[i].height;
1618 mon[i].by = mon[i].topbar ? info[i].y_org : mon[i].wy + mon[i].wh;
1622 nmons = (unsigned int)n;
1628 if(XQueryPointer(dpy, root, &dummy, &dummy, &x, &y, &di, &di, &dui))
1629 for(i = 0; i < nmons; i++)
1630 if(INRECT(x, y, info[i].x_org, info[i].y_org, info[i].width, info[i].height)) {
1638 #endif /* XINERAMA */
1642 if(!(mon = (Monitor *)malloc(sizeof(Monitor))))
1643 die("fatal: could not malloc() %u bytes\n", sizeof(Monitor));
1646 mon[0].symbol[0] = '[';
1647 mon[0].symbol[1] = '0';
1648 mon[0].symbol[2] = ']';
1649 mon[0].symbol[3] = 0;
1650 mon[0].mfact = mfact;
1651 mon[0].showbar = showbar;
1652 mon[0].topbar = topbar;
1653 mon[0].tagset[0] = mon[0].tagset[1] = 1;
1656 mon[0].wy = mon[0].showbar && mon[0].topbar ? sy + bh : sy;
1658 mon[0].wh = mon[0].showbar ? sh - bh : sh;
1662 mon[0].by = mon[0].topbar ? sy : mon[0].wy + mon[0].wh;
1670 updatenumlockmask(void) {
1672 XModifierKeymap *modmap;
1675 modmap = XGetModifierMapping(dpy);
1676 for(i = 0; i < 8; i++)
1677 for(j = 0; j < modmap->max_keypermod; j++)
1678 if(modmap->modifiermap[i * modmap->max_keypermod + j]
1679 == XKeysymToKeycode(dpy, XK_Num_Lock))
1680 numlockmask = (1 << i);
1681 XFreeModifiermap(modmap);
1685 updatesizehints(Client *c) {
1689 if(!XGetWMNormalHints(dpy, c->win, &size, &msize))
1690 /* size is uninitialized, ensure that size.flags aren't used */
1692 if(size.flags & PBaseSize) {
1693 c->basew = size.base_width;
1694 c->baseh = size.base_height;
1696 else if(size.flags & PMinSize) {
1697 c->basew = size.min_width;
1698 c->baseh = size.min_height;
1701 c->basew = c->baseh = 0;
1702 if(size.flags & PResizeInc) {
1703 c->incw = size.width_inc;
1704 c->inch = size.height_inc;
1707 c->incw = c->inch = 0;
1708 if(size.flags & PMaxSize) {
1709 c->maxw = size.max_width;
1710 c->maxh = size.max_height;
1713 c->maxw = c->maxh = 0;
1714 if(size.flags & PMinSize) {
1715 c->minw = size.min_width;
1716 c->minh = size.min_height;
1718 else if(size.flags & PBaseSize) {
1719 c->minw = size.base_width;
1720 c->minh = size.base_height;
1723 c->minw = c->minh = 0;
1724 if(size.flags & PAspect) {
1725 c->mina = (float)size.min_aspect.y / (float)size.min_aspect.x;
1726 c->maxa = (float)size.max_aspect.x / (float)size.max_aspect.y;
1729 c->maxa = c->mina = 0.0;
1730 c->isfixed = (c->maxw && c->minw && c->maxh && c->minh
1731 && c->maxw == c->minw && c->maxh == c->minh);
1735 updatetitle(Client *c) {
1736 if(!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
1737 gettextprop(c->win, XA_WM_NAME, c->name, sizeof c->name);
1742 if(!gettextprop(root, XA_WM_NAME, stext, sizeof(stext)))
1743 strcpy(stext, "dwm-"VERSION);
1748 updatewmhints(Client *c) {
1751 if((wmh = XGetWMHints(dpy, c->win))) {
1752 if(c == sel && wmh->flags & XUrgencyHint) {
1753 wmh->flags &= ~XUrgencyHint;
1754 XSetWMHints(dpy, c->win, wmh);
1757 c->isurgent = (wmh->flags & XUrgencyHint) ? True : False;
1764 view(const Arg *arg) {
1765 if((arg->ui & TAGMASK) == selmon->tagset[selmon->seltags])
1767 selmon->seltags ^= 1; /* toggle sel tagset */
1768 if(arg->ui & TAGMASK)
1769 selmon->tagset[selmon->seltags] = arg->ui & TAGMASK;
1773 /* There's no way to check accesses to destroyed windows, thus those cases are
1774 * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
1775 * default error handler, which may call exit. */
1777 xerror(Display *dpy, XErrorEvent *ee) {
1778 if(ee->error_code == BadWindow
1779 || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1780 || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1781 || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1782 || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1783 || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1784 || (ee->request_code == X_GrabButton && ee->error_code == BadAccess)
1785 || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1786 || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1788 fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1789 ee->request_code, ee->error_code);
1790 return xerrorxlib(dpy, ee); /* may call exit */
1794 xerrordummy(Display *dpy, XErrorEvent *ee) {
1798 /* Startup Error handler to check if another window manager
1799 * is already running. */
1801 xerrorstart(Display *dpy, XErrorEvent *ee) {
1807 zoom(const Arg *arg) {
1810 if(!lt[selmon->sellt]->arrange || lt[selmon->sellt]->arrange == monocle || (sel && sel->isfloating))
1812 if(c == nexttiled(selmon, clients))
1813 if(!c || !(c = nexttiled(selmon, c->next)))
1822 main(int argc, char *argv[]) {
1823 if(argc == 2 && !strcmp("-v", argv[1]))
1824 die("dwm-"VERSION", © 2006-2009 dwm engineers, see LICENSE for details\n");
1826 die("usage: dwm [-v]\n");
1828 if(!setlocale(LC_CTYPE, "") || !XSupportsLocale())
1829 fputs("warning: no locale support\n", stderr);
1831 if(!(dpy = XOpenDisplay(NULL)))
1832 die("dwm: cannot open display\n");