1 /* See LICENSE file for copyright and license details.
3 * dynamic window manager is designed like any other X client as well. It is
4 * driven through handling X events. In contrast to other X clients, a window
5 * manager selects for SubstructureRedirectMask on the root window, to receive
6 * events about window (dis-)appearance. Only one X connection at a time is
7 * allowed to select for this event mask.
9 * The event handlers of dwm are organized in an array which is accessed
10 * whenever a new event has been fetched. This allows event dispatching
13 * Each child of the root window is called a client, except windows which have
14 * set the override_redirect flag. Clients are organized in a global
15 * linked client list, the focus history is remembered through a global
16 * stack list. Each client contains a bit array to indicate the tags of a
19 * Keys and tagging rules are organized as arrays and defined in config.h.
21 * To understand everything else, start reading main().
31 #include <sys/types.h>
33 #include <X11/cursorfont.h>
34 #include <X11/keysym.h>
35 #include <X11/Xatom.h>
37 #include <X11/Xproto.h>
38 #include <X11/Xutil.h>
40 #include <X11/extensions/Xinerama.h>
44 #define BUTTONMASK (ButtonPressMask|ButtonReleaseMask)
45 #define CLEANMASK(mask) (mask & ~(numlockmask|LockMask))
46 #define INRECT(X,Y,RX,RY,RW,RH) ((X) >= (RX) && (X) < (RX) + (RW) && (Y) >= (RY) && (Y) < (RY) + (RH))
47 #define ISVISIBLE(x) (x->tags & tagset[mon[x->mon].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 *);
119 int by, btx; /* bar geometry */
120 int wx, wy, ww, wh; /* window area */
121 unsigned int seltags;
130 void (*arrange)(Monitor *);
135 const char *instance;
141 /* function declarations */
142 static void applyrules(Client *c);
143 static Bool applysizehints(Client *c, int *x, int *y, int *w, int *h);
144 static void arrange(void);
145 static void attach(Client *c);
146 static void attachstack(Client *c);
147 static void buttonpress(XEvent *e);
148 static void checkotherwm(void);
149 static void cleanup(void);
150 static void clearurgent(Client *c);
151 static void configure(Client *c);
152 static void configurenotify(XEvent *e);
153 static void configurerequest(XEvent *e);
154 static void destroynotify(XEvent *e);
155 static void detach(Client *c);
156 static void detachstack(Client *c);
157 static void die(const char *errstr, ...);
158 static void drawbar(Monitor *m);
159 static void drawbars();
160 static void drawsquare(Bool filled, Bool empty, Bool invert, unsigned long col[ColLast]);
161 static void drawtext(const char *text, unsigned long col[ColLast], Bool invert);
162 static void enternotify(XEvent *e);
163 static void expose(XEvent *e);
164 static void focus(Client *c);
165 static void focusin(XEvent *e);
166 static void focusstack(const Arg *arg);
167 static Client *getclient(Window w);
168 static unsigned long getcolor(const char *colstr);
169 static long getstate(Window w);
170 static Bool gettextprop(Window w, Atom atom, char *text, unsigned int size);
171 static void grabbuttons(Client *c, Bool focused);
172 static void grabkeys(void);
173 static void initfont(const char *fontstr);
174 static Bool isprotodel(Client *c);
175 static void keypress(XEvent *e);
176 static void killclient(const Arg *arg);
177 static void manage(Window w, XWindowAttributes *wa);
178 static void mappingnotify(XEvent *e);
179 static void maprequest(XEvent *e);
180 static void monocle(Monitor *m);
181 static void movemouse(const Arg *arg);
182 static Client *nexttiled(Monitor *m, Client *c);
183 static void propertynotify(XEvent *e);
184 static void quit(const Arg *arg);
185 static void resize(Client *c, int x, int y, int w, int h);
186 static void resizemouse(const Arg *arg);
187 static void restack(Monitor *m);
188 static void run(void);
189 static void scan(void);
190 static void setclientstate(Client *c, long state);
191 static void setlayout(const Arg *arg);
192 static void setmfact(const Arg *arg);
193 static void setup(void);
194 static void showhide(Client *c);
195 static void sigchld(int signal);
196 static void spawn(const Arg *arg);
197 static void tag(const Arg *arg);
198 static int textnw(const char *text, unsigned int len);
199 static void tile(Monitor *);
200 static void togglebar(const Arg *arg);
201 static void togglefloating(const Arg *arg);
202 static void toggletag(const Arg *arg);
203 static void toggleview(const Arg *arg);
204 static void unmanage(Client *c);
205 static void unmapnotify(XEvent *e);
206 static void updategeom(void);
207 static void updatenumlockmask(void);
208 static void updatesizehints(Client *c);
209 static void updatestatus(void);
210 static void updatetitle(Client *c);
211 static void updatewmhints(Client *c);
212 static void view(const Arg *arg);
213 static int xerror(Display *dpy, XErrorEvent *ee);
214 static int xerrordummy(Display *dpy, XErrorEvent *ee);
215 static int xerrorstart(Display *dpy, XErrorEvent *ee);
216 static void zoom(const Arg *arg);
218 static void focusmon(const Arg *arg);
219 static void tagmon(const Arg *arg);
220 #endif /* XINERAMA */
223 static char stext[256];
225 static int sx, sy, sw, sh; /* X display screen geometry x, y, width, height */
226 static int bh, blw = 0; /* bar geometry */
227 static int (*xerrorxlib)(Display *, XErrorEvent *);
228 static unsigned int numlockmask = 0;
229 static void (*handler[LASTEvent]) (XEvent *) = {
230 [ButtonPress] = buttonpress,
231 [ConfigureRequest] = configurerequest,
232 [ConfigureNotify] = configurenotify,
233 [DestroyNotify] = destroynotify,
234 [EnterNotify] = enternotify,
237 [KeyPress] = keypress,
238 [MappingNotify] = mappingnotify,
239 [MapRequest] = maprequest,
240 [PropertyNotify] = propertynotify,
241 [UnmapNotify] = unmapnotify
243 static Atom wmatom[WMLast], netatom[NetLast];
245 static Bool running = True;
246 static Client *clients = NULL;
247 static Client *sel = NULL;
248 static Client *stack = NULL;
249 static Cursor cursor[CurLast];
252 static Layout *lt[] = { NULL, NULL };
253 static Monitor *mon = NULL, *selmon = NULL;
254 static unsigned int nmons;
256 /* configuration, allows nested code to access above variables */
259 /* compile-time check if all tags fit into an unsigned int bit array. */
260 struct NumTags { char limitexceeded[sizeof(unsigned int) * 8 < LENGTH(tags) ? -1 : 1]; };
262 /* function implementations */
264 applyrules(Client *c) {
267 XClassHint ch = { 0 };
270 c->isfloating = c->tags = 0;
271 if(XGetClassHint(dpy, c->win, &ch)) {
272 for(i = 0; i < LENGTH(rules); i++) {
274 if((!r->title || strstr(c->name, r->title))
275 && (!r->class || (ch.res_class && strstr(ch.res_class, r->class)))
276 && (!r->instance || (ch.res_name && strstr(ch.res_name, r->instance)))) {
277 c->isfloating = r->isfloating;
286 c->tags = c->tags & TAGMASK ? c->tags & TAGMASK : tagset[mon[c->mon].seltags];
290 applysizehints(Client *c, int *x, int *y, int *w, int *h) {
293 /* set minimum possible */
301 if(*x + *w + 2 * c->bw < sx)
303 if(*y + *h + 2 * c->bw < sy)
310 if(resizehints || c->isfloating) {
311 /* see last two sentences in ICCCM 4.1.2.3 */
312 baseismin = c->basew == c->minw && c->baseh == c->minh;
314 if(!baseismin) { /* temporarily remove base dimensions */
319 /* adjust for aspect limits */
320 if(c->mina > 0 && c->maxa > 0) {
321 if(c->maxa < (float)*w / *h)
323 else if(c->mina < (float)*h / *w)
327 if(baseismin) { /* increment calculation requires this */
332 /* adjust for increment value */
338 /* restore base dimensions */
342 *w = MAX(*w, c->minw);
343 *h = MAX(*h, c->minh);
346 *w = MIN(*w, c->maxw);
349 *h = MIN(*h, c->maxh);
351 return *x != c->x || *y != c->y || *w != c->w || *h != c->h;
359 for(i = 0; i < nmons; i++) {
360 if(lt[mon[i].sellt]->arrange)
361 lt[mon[i].sellt]->arrange(&mon[i]);
373 attachstack(Client *c) {
379 buttonpress(XEvent *e) {
380 unsigned int i, x, click;
383 XButtonPressedEvent *ev = &e->xbutton;
386 if(ev->window == selmon->barwin) {
391 while(ev->x >= x && ++i < LENGTH(tags));
392 if(i < LENGTH(tags)) {
396 else if(ev->x < x + blw)
398 else if(ev->x > selmon->wx + selmon->ww - TEXTW(stext))
399 click = ClkStatusText;
403 else if((c = getclient(ev->window))) {
405 click = ClkClientWin;
408 for(i = 0; i < LENGTH(buttons); i++)
409 if(click == buttons[i].click && buttons[i].func && buttons[i].button == ev->button
410 && CLEANMASK(buttons[i].mask) == CLEANMASK(ev->state))
411 buttons[i].func(click == ClkTagBar && buttons[i].arg.i == 0 ? &arg : &buttons[i].arg);
417 xerrorxlib = XSetErrorHandler(xerrorstart);
419 /* this causes an error if some other window manager is running */
420 XSelectInput(dpy, DefaultRootWindow(dpy), SubstructureRedirectMask);
423 die("dwm: another window manager is already running\n");
424 XSetErrorHandler(xerror);
432 Layout foo = { "", NULL };
435 lt[selmon->sellt] = &foo;
439 XFreeFontSet(dpy, dc.font.set);
441 XFreeFont(dpy, dc.font.xfont);
442 XUngrabKey(dpy, AnyKey, AnyModifier, root);
443 XFreePixmap(dpy, dc.drawable);
445 XFreeCursor(dpy, cursor[CurNormal]);
446 XFreeCursor(dpy, cursor[CurResize]);
447 XFreeCursor(dpy, cursor[CurMove]);
448 for(i = 0; i < nmons; i++)
449 XDestroyWindow(dpy, mon[i].barwin);
452 XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime);
456 clearurgent(Client *c) {
460 if(!(wmh = XGetWMHints(dpy, c->win)))
462 wmh->flags &= ~XUrgencyHint;
463 XSetWMHints(dpy, c->win, wmh);
468 configure(Client *c) {
471 ce.type = ConfigureNotify;
479 ce.border_width = c->bw;
481 ce.override_redirect = False;
482 XSendEvent(dpy, c->win, False, StructureNotifyMask, (XEvent *)&ce);
486 configurenotify(XEvent *e) {
488 XConfigureEvent *ev = &e->xconfigure;
490 if(ev->window == root && (ev->width != sw || ev->height != sh)) {
495 XFreePixmap(dpy, dc.drawable);
496 dc.drawable = XCreatePixmap(dpy, root, DisplayWidth(dpy, screen), bh, DefaultDepth(dpy, screen));
497 for(i = 0; i < nmons; i++)
498 XMoveResizeWindow(dpy, mon[i].barwin, mon[i].wx, mon[i].by, mon[i].ww, bh);
504 configurerequest(XEvent *e) {
506 XConfigureRequestEvent *ev = &e->xconfigurerequest;
509 if((c = getclient(ev->window))) {
510 if(ev->value_mask & CWBorderWidth)
511 c->bw = ev->border_width;
512 else if(c->isfloating || !lt[selmon->sellt]->arrange) {
513 if(ev->value_mask & CWX)
515 if(ev->value_mask & CWY)
517 if(ev->value_mask & CWWidth)
519 if(ev->value_mask & CWHeight)
521 if((c->x - sx + c->w) > sw && c->isfloating)
522 c->x = sx + (sw / 2 - c->w / 2); /* center in x direction */
523 if((c->y - sy + c->h) > sh && c->isfloating)
524 c->y = sy + (sh / 2 - c->h / 2); /* center in y direction */
525 if((ev->value_mask & (CWX|CWY)) && !(ev->value_mask & (CWWidth|CWHeight)))
528 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h);
536 wc.width = ev->width;
537 wc.height = ev->height;
538 wc.border_width = ev->border_width;
539 wc.sibling = ev->above;
540 wc.stack_mode = ev->detail;
541 XConfigureWindow(dpy, ev->window, ev->value_mask, &wc);
547 destroynotify(XEvent *e) {
549 XDestroyWindowEvent *ev = &e->xdestroywindow;
551 if((c = getclient(ev->window)))
559 for(tc = &clients; *tc && *tc != c; tc = &(*tc)->next);
564 detachstack(Client *c) {
567 for(tc = &stack; *tc && *tc != c; tc = &(*tc)->snext);
572 die(const char *errstr, ...) {
575 va_start(ap, errstr);
576 vfprintf(stderr, errstr, ap);
582 drawbar(Monitor *m) {
584 unsigned int i, occ = 0, urg = 0;
588 for(c = clients; c; c = c->next) {
589 if(m == &mon[c->mon]) {
599 dc.w = TEXTW(m->symbol);
600 drawtext(m->symbol, selmon == m ? dc.sel : dc.norm, False);
603 #endif /* XINERAMA */
605 for(i = 0; i < LENGTH(tags); i++) {
606 dc.w = TEXTW(tags[i]);
607 col = tagset[m->seltags] & 1 << i ? dc.sel : dc.norm;
608 drawtext(tags[i], col, urg & 1 << i);
609 drawsquare(m == selmon && sel && sel->tags & 1 << i,
610 occ & 1 << i, urg & 1 << i, col);
615 drawtext(lt[m->sellt]->symbol, dc.norm, False);
627 drawtext(stext, dc.norm, False);
628 if((dc.w = dc.x - x) > bh) {
631 drawtext(sel->name, dc.sel, False);
632 drawsquare(sel->isfixed, sel->isfloating, False, dc.sel);
635 drawtext(NULL, dc.norm, False);
640 drawtext(NULL, dc.norm, False);
642 XCopyArea(dpy, dc.drawable, m->barwin, dc.gc, 0, 0, m->ww, bh, 0, 0);
650 for(i = 0; i < nmons; i++)
655 drawsquare(Bool filled, Bool empty, Bool invert, unsigned long col[ColLast]) {
658 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
660 gcv.foreground = col[invert ? ColBG : ColFG];
661 XChangeGC(dpy, dc.gc, GCForeground, &gcv);
662 x = (dc.font.ascent + dc.font.descent + 2) / 4;
666 r.width = r.height = x + 1;
667 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
670 r.width = r.height = x;
671 XDrawRectangles(dpy, dc.drawable, dc.gc, &r, 1);
676 drawtext(const char *text, unsigned long col[ColLast], Bool invert) {
678 int i, x, y, h, len, olen;
679 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
681 XSetForeground(dpy, dc.gc, col[invert ? ColFG : ColBG]);
682 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
686 h = dc.font.ascent + dc.font.descent;
687 y = dc.y + (dc.h / 2) - (h / 2) + dc.font.ascent;
689 /* shorten text if necessary */
690 for(len = MIN(olen, sizeof buf); len && textnw(text, len) > dc.w - h; len--);
693 memcpy(buf, text, len);
695 for(i = len; i && i > len - 3; buf[--i] = '.');
696 XSetForeground(dpy, dc.gc, col[invert ? ColBG : ColFG]);
698 XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
700 XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
704 enternotify(XEvent *e) {
706 XCrossingEvent *ev = &e->xcrossing;
708 if((ev->mode != NotifyNormal || ev->detail == NotifyInferior) && ev->window != root)
710 if((c = getclient(ev->window)))
719 XExposeEvent *ev = &e->xexpose;
721 for(i = 0; i < nmons; i++)
722 if(ev->count == 0 && (ev->window == mon[i].barwin)) {
730 if(!c || !ISVISIBLE(c))
731 for(c = stack; c && !ISVISIBLE(c); c = c->snext);
732 if(sel && sel != c) {
733 grabbuttons(sel, False);
734 XSetWindowBorder(dpy, sel->win, dc.norm[ColBorder]);
741 grabbuttons(c, True);
742 XSetWindowBorder(dpy, c->win, dc.sel[ColBorder]);
743 XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
746 XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
749 selmon = &mon[c->mon];
754 focusin(XEvent *e) { /* there are some broken focus acquiring clients */
755 XFocusChangeEvent *ev = &e->xfocus;
757 if(sel && ev->window != sel->win)
758 XSetInputFocus(dpy, sel->win, RevertToPointerRoot, CurrentTime);
763 focusmon(const Arg *arg) {
766 selmon = &mon[arg->ui];
770 #endif /* XINERAMA */
773 focusstack(const Arg *arg) {
774 Client *c = NULL, *i;
779 for(c = sel->next; c && !ISVISIBLE(c); c = c->next);
781 for(c = clients; c && !ISVISIBLE(c); c = c->next);
784 for(i = clients; i != sel; i = i->next)
788 for(; i; i = i->next)
799 getclient(Window w) {
802 for(c = clients; c && c->win != w; c = c->next);
807 getcolor(const char *colstr) {
808 Colormap cmap = DefaultColormap(dpy, screen);
811 if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
812 die("error, cannot allocate color '%s'\n", colstr);
820 unsigned char *p = NULL;
821 unsigned long n, extra;
824 status = XGetWindowProperty(dpy, w, wmatom[WMState], 0L, 2L, False, wmatom[WMState],
825 &real, &format, &n, &extra, (unsigned char **)&p);
826 if(status != Success)
835 gettextprop(Window w, Atom atom, char *text, unsigned int size) {
840 if(!text || size == 0)
843 XGetTextProperty(dpy, w, &name, atom);
846 if(name.encoding == XA_STRING)
847 strncpy(text, (char *)name.value, size - 1);
849 if(XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success
851 strncpy(text, *list, size - 1);
852 XFreeStringList(list);
855 text[size - 1] = '\0';
861 grabbuttons(Client *c, Bool focused) {
865 unsigned int modifiers[] = { 0, LockMask, numlockmask, numlockmask|LockMask };
866 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
868 for(i = 0; i < LENGTH(buttons); i++)
869 if(buttons[i].click == ClkClientWin)
870 for(j = 0; j < LENGTH(modifiers); j++)
871 XGrabButton(dpy, buttons[i].button,
872 buttons[i].mask | modifiers[j],
873 c->win, False, BUTTONMASK,
874 GrabModeAsync, GrabModeSync, None, None);
876 XGrabButton(dpy, AnyButton, AnyModifier, c->win, False,
877 BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
886 unsigned int modifiers[] = { 0, LockMask, numlockmask, numlockmask|LockMask };
889 XUngrabKey(dpy, AnyKey, AnyModifier, root);
890 for(i = 0; i < LENGTH(keys); i++) {
891 if((code = XKeysymToKeycode(dpy, keys[i].keysym)))
892 for(j = 0; j < LENGTH(modifiers); j++)
893 XGrabKey(dpy, code, keys[i].mod | modifiers[j], root,
894 True, GrabModeAsync, GrabModeAsync);
900 initfont(const char *fontstr) {
901 char *def, **missing;
905 dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
908 fprintf(stderr, "dwm: missing fontset: %s\n", missing[n]);
909 XFreeStringList(missing);
912 XFontSetExtents *font_extents;
913 XFontStruct **xfonts;
915 dc.font.ascent = dc.font.descent = 0;
916 font_extents = XExtentsOfFontSet(dc.font.set);
917 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
918 for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
919 dc.font.ascent = MAX(dc.font.ascent, (*xfonts)->ascent);
920 dc.font.descent = MAX(dc.font.descent,(*xfonts)->descent);
925 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr))
926 && !(dc.font.xfont = XLoadQueryFont(dpy, "fixed")))
927 die("error, cannot load font: '%s'\n", fontstr);
928 dc.font.ascent = dc.font.xfont->ascent;
929 dc.font.descent = dc.font.xfont->descent;
931 dc.font.height = dc.font.ascent + dc.font.descent;
935 isprotodel(Client *c) {
940 if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
941 for(i = 0; !ret && i < n; i++)
942 if(protocols[i] == wmatom[WMDelete])
950 keypress(XEvent *e) {
956 keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
957 for(i = 0; i < LENGTH(keys); i++)
958 if(keysym == keys[i].keysym
959 && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state)
961 keys[i].func(&(keys[i].arg));
965 killclient(const Arg *arg) {
970 if(isprotodel(sel)) {
971 ev.type = ClientMessage;
972 ev.xclient.window = sel->win;
973 ev.xclient.message_type = wmatom[WMProtocols];
974 ev.xclient.format = 32;
975 ev.xclient.data.l[0] = wmatom[WMDelete];
976 ev.xclient.data.l[1] = CurrentTime;
977 XSendEvent(dpy, sel->win, False, NoEventMask, &ev);
980 XKillClient(dpy, sel->win);
984 manage(Window w, XWindowAttributes *wa) {
986 Client *c, *t = NULL;
990 if(!(c = malloc(sizeof(Client))))
991 die("fatal: could not malloc() %u bytes\n", sizeof(Client));
994 for(c->mon = 0; selmon != &mon[c->mon]; c->mon++);
1001 c->oldbw = wa->border_width;
1002 if(c->w == sw && c->h == sh) {
1008 if(c->x + WIDTH(c) > sx + sw)
1009 c->x = sx + sw - WIDTH(c);
1010 if(c->y + HEIGHT(c) > sy + sh)
1011 c->y = sy + sh - HEIGHT(c);
1012 c->x = MAX(c->x, sx);
1013 /* only fix client y-offset, if the client center might cover the bar */
1014 c->y = MAX(c->y, ((selmon->by == 0) && (c->x + (c->w / 2) >= selmon->wx)
1015 && (c->x + (c->w / 2) < selmon->wx + selmon->ww)) ? bh : sy);
1019 wc.border_width = c->bw;
1020 XConfigureWindow(dpy, w, CWBorderWidth, &wc);
1021 XSetWindowBorder(dpy, w, dc.norm[ColBorder]);
1022 configure(c); /* propagates border_width, if size doesn't change */
1024 XSelectInput(dpy, w, EnterWindowMask|FocusChangeMask|PropertyChangeMask|StructureNotifyMask);
1025 grabbuttons(c, False);
1027 if(XGetTransientForHint(dpy, w, &trans))
1028 t = getclient(trans);
1034 c->isfloating = trans != None || c->isfixed;
1036 XRaiseWindow(dpy, c->win);
1039 XMoveResizeWindow(dpy, c->win, c->x + 2 * sw, c->y, c->w, c->h); /* some windows require this */
1040 XMapWindow(dpy, c->win);
1041 setclientstate(c, NormalState);
1046 mappingnotify(XEvent *e) {
1047 XMappingEvent *ev = &e->xmapping;
1049 XRefreshKeyboardMapping(ev);
1050 if(ev->request == MappingKeyboard)
1055 maprequest(XEvent *e) {
1056 static XWindowAttributes wa;
1057 XMapRequestEvent *ev = &e->xmaprequest;
1059 if(!XGetWindowAttributes(dpy, ev->window, &wa))
1061 if(wa.override_redirect)
1063 if(!getclient(ev->window))
1064 manage(ev->window, &wa);
1068 monocle(Monitor *m) {
1071 for(c = nexttiled(m, clients); c; c = nexttiled(m, c->next))
1072 resize(c, m->wx, m->wy, m->ww - 2 * c->bw, m->wh - 2 * c->bw);
1076 movemouse(const Arg *arg) {
1077 int x, y, ocx, ocy, di, nx, ny;
1088 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1089 None, cursor[CurMove], CurrentTime) != GrabSuccess)
1091 XQueryPointer(dpy, root, &dummy, &dummy, &x, &y, &di, &di, &dui);
1093 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
1095 case ConfigureRequest:
1098 handler[ev.type](&ev);
1101 nx = ocx + (ev.xmotion.x - x);
1102 ny = ocy + (ev.xmotion.y - y);
1103 if(snap && nx >= selmon->wx && nx <= selmon->wx + selmon->ww
1104 && ny >= selmon->wy && ny <= selmon->wy + selmon->wh) {
1105 if(abs(selmon->wx - nx) < snap)
1107 else if(abs((selmon->wx + selmon->ww) - (nx + WIDTH(c))) < snap)
1108 nx = selmon->wx + selmon->ww - WIDTH(c);
1109 if(abs(selmon->wy - ny) < snap)
1111 else if(abs((selmon->wy + selmon->wh) - (ny + HEIGHT(c))) < snap)
1112 ny = selmon->wy + selmon->wh - HEIGHT(c);
1113 if(!c->isfloating && lt[selmon->sellt]->arrange
1114 && (abs(nx - c->x) > snap || abs(ny - c->y) > snap))
1115 togglefloating(NULL);
1117 if(!lt[selmon->sellt]->arrange || c->isfloating)
1118 resize(c, nx, ny, c->w, c->h);
1122 while(ev.type != ButtonRelease);
1123 XUngrabPointer(dpy, CurrentTime);
1127 nexttiled(Monitor *m, Client *c) {
1129 for(; c && (c->isfloating || m != &mon[c->mon] || !ISVISIBLE(c)); c = c->next);
1134 propertynotify(XEvent *e) {
1137 XPropertyEvent *ev = &e->xproperty;
1139 if((ev->window == root) && (ev->atom == XA_WM_NAME))
1141 else if(ev->state == PropertyDelete)
1142 return; /* ignore */
1143 else if((c = getclient(ev->window))) {
1146 case XA_WM_TRANSIENT_FOR:
1147 XGetTransientForHint(dpy, c->win, &trans);
1148 if(!c->isfloating && (c->isfloating = (getclient(trans) != NULL)))
1151 case XA_WM_NORMAL_HINTS:
1159 if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
1168 quit(const Arg *arg) {
1173 resize(Client *c, int x, int y, int w, int h) {
1176 if(applysizehints(c, &x, &y, &w, &h)) {
1179 c->w = wc.width = w;
1180 c->h = wc.height = h;
1181 wc.border_width = c->bw;
1182 XConfigureWindow(dpy, c->win,
1183 CWX|CWY|CWWidth|CWHeight|CWBorderWidth, &wc);
1190 resizemouse(const Arg *arg) {
1201 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1202 None, cursor[CurResize], CurrentTime) != GrabSuccess)
1204 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->bw - 1, c->h + c->bw - 1);
1206 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
1208 case ConfigureRequest:
1211 handler[ev.type](&ev);
1214 nw = MAX(ev.xmotion.x - ocx - 2 * c->bw + 1, 1);
1215 nh = MAX(ev.xmotion.y - ocy - 2 * c->bw + 1, 1);
1217 if(snap && nw >= selmon->wx && nw <= selmon->wx + selmon->ww
1218 && nh >= selmon->wy && nh <= selmon->wy + selmon->wh) {
1219 if(!c->isfloating && lt[selmon->sellt]->arrange
1220 && (abs(nw - c->w) > snap || abs(nh - c->h) > snap))
1221 togglefloating(NULL);
1223 if(!lt[selmon->sellt]->arrange || c->isfloating)
1224 resize(c, c->x, c->y, nw, nh);
1228 while(ev.type != ButtonRelease);
1229 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->bw - 1, c->h + c->bw - 1);
1230 XUngrabPointer(dpy, CurrentTime);
1231 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1235 restack(Monitor *m) {
1243 if(m == selmon && (sel->isfloating || !lt[m->sellt]->arrange))
1244 XRaiseWindow(dpy, sel->win);
1245 if(lt[m->sellt]->arrange) {
1246 wc.stack_mode = Below;
1247 wc.sibling = m->barwin;
1248 for(c = stack; c; c = c->snext)
1249 if(!c->isfloating && m == &mon[c->mon] && ISVISIBLE(c)) {
1250 XConfigureWindow(dpy, c->win, CWSibling|CWStackMode, &wc);
1251 wc.sibling = c->win;
1255 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1262 /* main event loop */
1264 while(running && !XNextEvent(dpy, &ev)) {
1265 if(handler[ev.type])
1266 (handler[ev.type])(&ev); /* call handler */
1272 unsigned int i, num;
1273 Window d1, d2, *wins = NULL;
1274 XWindowAttributes wa;
1276 if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1277 for(i = 0; i < num; i++) {
1278 if(!XGetWindowAttributes(dpy, wins[i], &wa)
1279 || wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1281 if(wa.map_state == IsViewable || getstate(wins[i]) == IconicState)
1282 manage(wins[i], &wa);
1284 for(i = 0; i < num; i++) { /* now the transients */
1285 if(!XGetWindowAttributes(dpy, wins[i], &wa))
1287 if(XGetTransientForHint(dpy, wins[i], &d1)
1288 && (wa.map_state == IsViewable || getstate(wins[i]) == IconicState))
1289 manage(wins[i], &wa);
1297 setclientstate(Client *c, long state) {
1298 long data[] = {state, None};
1300 XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1301 PropModeReplace, (unsigned char *)data, 2);
1305 setlayout(const Arg *arg) {
1306 if(!arg || !arg->v || arg->v != lt[selmon->sellt])
1309 lt[selmon->sellt] = (Layout *)arg->v;
1316 /* arg > 1.0 will set mfact absolutly */
1318 setmfact(const Arg *arg) {
1321 if(!arg || !lt[selmon->sellt]->arrange)
1323 f = arg->f < 1.0 ? arg->f + mfact : arg->f - 1.0;
1324 if(f < 0.1 || f > 0.9)
1334 XSetWindowAttributes wa;
1337 screen = DefaultScreen(dpy);
1338 root = RootWindow(dpy, screen);
1342 sw = DisplayWidth(dpy, screen);
1343 sh = DisplayHeight(dpy, screen);
1344 bh = dc.h = dc.font.height + 2;
1345 lt[0] = &layouts[0];
1346 lt[1] = &layouts[1 % LENGTH(layouts)];
1350 wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1351 wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1352 wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1353 netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1354 netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1357 wa.cursor = cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1358 cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1359 cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1361 /* init appearance */
1362 dc.norm[ColBorder] = getcolor(normbordercolor);
1363 dc.norm[ColBG] = getcolor(normbgcolor);
1364 dc.norm[ColFG] = getcolor(normfgcolor);
1365 dc.sel[ColBorder] = getcolor(selbordercolor);
1366 dc.sel[ColBG] = getcolor(selbgcolor);
1367 dc.sel[ColFG] = getcolor(selfgcolor);
1368 dc.drawable = XCreatePixmap(dpy, root, DisplayWidth(dpy, screen), bh, DefaultDepth(dpy, screen));
1369 dc.gc = XCreateGC(dpy, root, 0, NULL);
1370 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
1372 XSetFont(dpy, dc.gc, dc.font.xfont->fid);
1375 wa.override_redirect = True;
1376 wa.background_pixmap = ParentRelative;
1377 wa.event_mask = ButtonPressMask|ExposureMask;
1378 for(blw = i = 0; LENGTH(layouts) > 1 && i < LENGTH(layouts); i++) {
1379 w = TEXTW(layouts[i].symbol);
1383 for(i = 0; i < nmons; i++) {
1384 mon[i].barwin = XCreateWindow(dpy, root, mon[i].wx, mon[i].by, mon[i].ww, bh, 0, DefaultDepth(dpy, screen),
1386 CopyFromParent, DefaultVisual(dpy, screen),
1387 CWOverrideRedirect|CWBackPixmap|CWEventMask, &wa);
1388 XDefineCursor(dpy, mon[i].barwin, cursor[CurNormal]);
1389 XMapRaised(dpy, mon[i].barwin);
1393 /* EWMH support per view */
1394 XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1395 PropModeReplace, (unsigned char *) netatom, NetLast);
1397 /* select for events */
1398 wa.event_mask = SubstructureRedirectMask|SubstructureNotifyMask|ButtonPressMask
1399 |EnterWindowMask|LeaveWindowMask|StructureNotifyMask
1400 |PropertyChangeMask;
1401 XChangeWindowAttributes(dpy, root, CWEventMask|CWCursor, &wa);
1402 XSelectInput(dpy, root, wa.event_mask);
1408 showhide(Client *c) {
1411 if(ISVISIBLE(c)) { /* show clients top down */
1412 XMoveWindow(dpy, c->win, c->x, c->y);
1413 if(!lt[selmon->sellt]->arrange || c->isfloating)
1414 resize(c, c->x, c->y, c->w, c->h);
1417 else { /* hide clients bottom up */
1419 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
1425 sigchld(int signal) {
1426 while(0 < waitpid(-1, NULL, WNOHANG));
1430 spawn(const Arg *arg) {
1431 signal(SIGCHLD, sigchld);
1434 close(ConnectionNumber(dpy));
1436 execvp(((char **)arg->v)[0], (char **)arg->v);
1437 fprintf(stderr, "dwm: execvp %s", ((char **)arg->v)[0]);
1444 tag(const Arg *arg) {
1445 if(sel && arg->ui & TAGMASK) {
1446 sel->tags = arg->ui & TAGMASK;
1453 tagmon(const Arg *arg) {
1454 if(!sel || arg->ui >= nmons)
1459 #endif /* XINERAMA */
1462 textnw(const char *text, unsigned int len) {
1466 XmbTextExtents(dc.font.set, text, len, NULL, &r);
1469 return XTextWidth(dc.font.xfont, text, len);
1478 for(n = 0, c = nexttiled(m, clients); c; c = nexttiled(m, c->next), n++);
1483 c = nexttiled(m, clients);
1485 resize(c, m->wx, m->wy, (n == 1 ? m->ww : mw) - 2 * c->bw, m->wh - 2 * c->bw);
1491 x = (m->wx + mw > c->x + c->w) ? c->x + c->w + 2 * c->bw : m->wx + mw;
1493 w = (m->wx + mw > c->x + c->w) ? m->wx + m->ww - x : m->ww - mw;
1498 for(i = 0, c = nexttiled(m, c->next); c; c = nexttiled(m, c->next), i++) {
1499 resize(c, x, y, w - 2 * c->bw, /* remainder */ ((i + 1 == n)
1500 ? m->wy + m->wh - y - 2 * c->bw : h - 2 * c->bw));
1502 y = c->y + HEIGHT(c);
1507 togglebar(const Arg *arg) {
1508 selmon->showbar = !selmon->showbar;
1510 XMoveResizeWindow(dpy, selmon->barwin, selmon->wx, selmon->by, selmon->ww, bh);
1515 togglefloating(const Arg *arg) {
1518 sel->isfloating = !sel->isfloating || sel->isfixed;
1520 resize(sel, sel->x, sel->y, sel->w, sel->h);
1525 toggletag(const Arg *arg) {
1531 mask = sel->tags ^ (arg->ui & TAGMASK);
1539 toggleview(const Arg *arg) {
1540 unsigned int mask = tagset[selmon->seltags] ^ (arg->ui & TAGMASK);
1543 tagset[selmon->seltags] = mask;
1549 unmanage(Client *c) {
1552 wc.border_width = c->oldbw;
1553 /* The server grab construct avoids race conditions. */
1555 XSetErrorHandler(xerrordummy);
1556 XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
1561 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1562 setclientstate(c, WithdrawnState);
1565 XSetErrorHandler(xerror);
1571 unmapnotify(XEvent *e) {
1573 XUnmapEvent *ev = &e->xunmap;
1575 if((c = getclient(ev->window)))
1583 unsigned int dui, i = 0;
1587 XineramaScreenInfo *info = NULL;
1589 /* window area geometry */
1590 if(XineramaIsActive(dpy) && (info = XineramaQueryScreens(dpy, &n))) {
1591 nmons = (unsigned int)n;
1592 for(c = clients; c; c = c->next)
1595 if(!(mon = (Monitor *)realloc(mon, sizeof(Monitor) * nmons)))
1596 die("fatal: could not realloc() %u bytes\n", sizeof(Monitor) * nmons);
1597 pquery = XQueryPointer(dpy, root, &dummy, &dummy, &x, &y, &di, &di, &dui);
1598 for(i = 0; i < nmons; i++) {
1599 /* TODO: consider re-using XineramaScreenInfo */
1600 mon[i].symbol[0] = '[';
1601 mon[i].symbol[1] = '0' + info[i].screen_number;
1602 mon[i].symbol[2] = ']';
1603 mon[i].symbol[3] = 0;
1604 mon[i].showbar = showbar;
1605 mon[i].topbar = topbar;
1606 mon[i].wx = info[i].x_org;
1607 mon[i].wy = mon[i].showbar && mon[i].topbar ? info[i].y_org + bh : info[i].y_org;
1608 mon[i].ww = info[i].width;
1609 mon[i].wh = mon[i].showbar ? info[i].height - bh : info[i].height;
1613 mon[i].by = mon[i].topbar ? info[i].y_org : mon[i].wy + mon[i].wh;
1616 if(pquery && INRECT(x, y, info[i].x_org, info[i].y_org, info[i].width, info[i].height))
1622 #endif /* XINERAMA */
1625 if(!(mon = (Monitor *)realloc(mon, sizeof(Monitor))))
1626 die("fatal: could not realloc() %u bytes\n", sizeof(Monitor));
1628 mon[0].symbol[0] = '[';
1629 mon[0].symbol[1] = '0';
1630 mon[0].symbol[2] = ']';
1631 mon[0].symbol[3] = 0;
1632 mon[0].showbar = showbar;
1633 mon[0].topbar = topbar;
1635 mon[0].wy = mon[0].showbar && mon[0].topbar ? sy + bh : sy;
1637 mon[0].wh = mon[0].showbar ? sh - bh : sh;
1641 mon[0].by = mon[0].topbar ? sy : mon[0].wy + mon[0].wh;
1648 updatenumlockmask(void) {
1650 XModifierKeymap *modmap;
1653 modmap = XGetModifierMapping(dpy);
1654 for(i = 0; i < 8; i++)
1655 for(j = 0; j < modmap->max_keypermod; j++)
1656 if(modmap->modifiermap[i * modmap->max_keypermod + j]
1657 == XKeysymToKeycode(dpy, XK_Num_Lock))
1658 numlockmask = (1 << i);
1659 XFreeModifiermap(modmap);
1663 updatesizehints(Client *c) {
1667 if(!XGetWMNormalHints(dpy, c->win, &size, &msize))
1668 /* size is uninitialized, ensure that size.flags aren't used */
1670 if(size.flags & PBaseSize) {
1671 c->basew = size.base_width;
1672 c->baseh = size.base_height;
1674 else if(size.flags & PMinSize) {
1675 c->basew = size.min_width;
1676 c->baseh = size.min_height;
1679 c->basew = c->baseh = 0;
1680 if(size.flags & PResizeInc) {
1681 c->incw = size.width_inc;
1682 c->inch = size.height_inc;
1685 c->incw = c->inch = 0;
1686 if(size.flags & PMaxSize) {
1687 c->maxw = size.max_width;
1688 c->maxh = size.max_height;
1691 c->maxw = c->maxh = 0;
1692 if(size.flags & PMinSize) {
1693 c->minw = size.min_width;
1694 c->minh = size.min_height;
1696 else if(size.flags & PBaseSize) {
1697 c->minw = size.base_width;
1698 c->minh = size.base_height;
1701 c->minw = c->minh = 0;
1702 if(size.flags & PAspect) {
1703 c->mina = (float)size.min_aspect.y / (float)size.min_aspect.x;
1704 c->maxa = (float)size.max_aspect.x / (float)size.max_aspect.y;
1707 c->maxa = c->mina = 0.0;
1708 c->isfixed = (c->maxw && c->minw && c->maxh && c->minh
1709 && c->maxw == c->minw && c->maxh == c->minh);
1713 updatetitle(Client *c) {
1714 if(!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
1715 gettextprop(c->win, XA_WM_NAME, c->name, sizeof c->name);
1720 if(!gettextprop(root, XA_WM_NAME, stext, sizeof(stext)))
1721 strcpy(stext, "dwm-"VERSION);
1726 updatewmhints(Client *c) {
1729 if((wmh = XGetWMHints(dpy, c->win))) {
1730 if(c == sel && wmh->flags & XUrgencyHint) {
1731 wmh->flags &= ~XUrgencyHint;
1732 XSetWMHints(dpy, c->win, wmh);
1735 c->isurgent = (wmh->flags & XUrgencyHint) ? True : False;
1742 view(const Arg *arg) {
1743 if((arg->ui & TAGMASK) == tagset[selmon->seltags])
1745 selmon->seltags ^= 1; /* toggle sel tagset */
1746 if(arg->ui & TAGMASK)
1747 tagset[selmon->seltags] = arg->ui & TAGMASK;
1751 /* There's no way to check accesses to destroyed windows, thus those cases are
1752 * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
1753 * default error handler, which may call exit. */
1755 xerror(Display *dpy, XErrorEvent *ee) {
1756 if(ee->error_code == BadWindow
1757 || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1758 || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1759 || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1760 || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1761 || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1762 || (ee->request_code == X_GrabButton && ee->error_code == BadAccess)
1763 || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1764 || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1766 fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1767 ee->request_code, ee->error_code);
1768 return xerrorxlib(dpy, ee); /* may call exit */
1772 xerrordummy(Display *dpy, XErrorEvent *ee) {
1776 /* Startup Error handler to check if another window manager
1777 * is already running. */
1779 xerrorstart(Display *dpy, XErrorEvent *ee) {
1785 zoom(const Arg *arg) {
1788 if(!lt[selmon->sellt]->arrange || lt[selmon->sellt]->arrange == monocle || (sel && sel->isfloating))
1790 if(c == nexttiled(selmon, clients))
1791 if(!c || !(c = nexttiled(selmon, c->next)))
1800 main(int argc, char *argv[]) {
1801 if(argc == 2 && !strcmp("-v", argv[1]))
1802 die("dwm-"VERSION", © 2006-2009 dwm engineers, see LICENSE for details\n");
1804 die("usage: dwm [-v]\n");
1806 if(!setlocale(LC_CTYPE, "") || !XSupportsLocale())
1807 fputs("warning: no locale support\n", stderr);
1809 if(!(dpy = XOpenDisplay(NULL)))
1810 die("dwm: cannot open display\n");