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(C) ((C->tags & C->mon->tagset[C->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 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];
143 const char *instance;
149 /* function declarations */
150 static void applyrules(Client *c);
151 static Bool applysizehints(Client *c, int *x, int *y, int *w, int *h);
152 static void arrange(void);
153 static void attach(Client *c);
154 static void attachstack(Client *c);
155 static void buttonpress(XEvent *e);
156 static void checkotherwm(void);
157 static void cleanup(void);
158 static void cleanupmons(void);
159 static void clearurgent(Client *c);
160 static void configure(Client *c);
161 static void configurenotify(XEvent *e);
162 static void configurerequest(XEvent *e);
163 static void destroynotify(XEvent *e);
164 static void detach(Client *c);
165 static void detachstack(Client *c);
166 static void die(const char *errstr, ...);
167 static void drawbar(Monitor *m);
168 static void drawbars();
169 static void drawsquare(Bool filled, Bool empty, Bool invert, unsigned long col[ColLast]);
170 static void drawtext(const char *text, unsigned long col[ColLast], Bool invert);
171 static void enternotify(XEvent *e);
172 static void expose(XEvent *e);
173 static void focus(Client *c);
174 static void focusin(XEvent *e);
175 static void focusstack(const Arg *arg);
176 static Client *getclient(Window w);
177 static unsigned long getcolor(const char *colstr);
178 static long getstate(Window w);
179 static Bool gettextprop(Window w, Atom atom, char *text, unsigned int size);
180 static void grabbuttons(Client *c, Bool focused);
181 static void grabkeys(void);
182 static void initfont(const char *fontstr);
183 static Bool isprotodel(Client *c);
184 static void keypress(XEvent *e);
185 static void killclient(const Arg *arg);
186 static void manage(Window w, XWindowAttributes *wa);
187 static void mappingnotify(XEvent *e);
188 static void maprequest(XEvent *e);
189 static void monocle(Monitor *m);
190 static void movemouse(const Arg *arg);
191 static Client *nexttiled(Client *c);
192 static void propertynotify(XEvent *e);
193 static void quit(const Arg *arg);
194 static void resize(Client *c, int x, int y, int w, int h);
195 static void resizemouse(const Arg *arg);
196 static void restack(Monitor *m);
197 static void run(void);
198 static void scan(void);
199 static void setclientstate(Client *c, long state);
200 static void setlayout(const Arg *arg);
201 static void setmfact(const Arg *arg);
202 static void setup(void);
203 static void showhide(Client *c);
204 static void sigchld(int signal);
205 static void spawn(const Arg *arg);
206 static void tag(const Arg *arg);
207 static int textnw(const char *text, unsigned int len);
208 static void tile(Monitor *);
209 static void togglebar(const Arg *arg);
210 static void togglefloating(const Arg *arg);
211 static void toggletag(const Arg *arg);
212 static void toggleview(const Arg *arg);
213 static void unmanage(Client *c);
214 static void unmapnotify(XEvent *e);
215 static void updategeom(void);
216 static void updatebarpos(Monitor *m);
217 static void updatebars(void);
218 static void updatenumlockmask(void);
219 static void updatesizehints(Client *c);
220 static void updatestatus(void);
221 static void updatetitle(Client *c);
222 static void updatewmhints(Client *c);
223 static void view(const Arg *arg);
224 static int xerror(Display *dpy, XErrorEvent *ee);
225 static int xerrordummy(Display *dpy, XErrorEvent *ee);
226 static int xerrorstart(Display *dpy, XErrorEvent *ee);
227 static void zoom(const Arg *arg);
229 static void focusmon(const Arg *arg);
230 static void tagmon(const Arg *arg);
231 #endif /* XINERAMA */
234 static char stext[256];
236 static int sx, sy, sw, sh; /* X display screen geometry x, y, width, height */
237 static int bh, blw = 0; /* bar geometry */
238 static int (*xerrorxlib)(Display *, XErrorEvent *);
239 static unsigned int numlockmask = 0;
240 static void (*handler[LASTEvent]) (XEvent *) = {
241 [ButtonPress] = buttonpress,
242 [ConfigureRequest] = configurerequest,
243 [ConfigureNotify] = configurenotify,
244 [DestroyNotify] = destroynotify,
245 [EnterNotify] = enternotify,
248 [KeyPress] = keypress,
249 [MappingNotify] = mappingnotify,
250 [MapRequest] = maprequest,
251 [PropertyNotify] = propertynotify,
252 [UnmapNotify] = unmapnotify
254 static Atom wmatom[WMLast], netatom[NetLast];
256 static Bool running = True;
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->mon->tagset[c->mon->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;
365 /* optimise two loops into one, check focus(NULL) */
366 for(m = mons; m; m = m->next)
369 for(m = mons; m; m = m->next) {
370 if(lt[m->sellt]->arrange)
371 lt[m->sellt]->arrange(m);
378 c->next = c->mon->clients;
383 attachstack(Client *c) {
384 c->snext = c->mon->stack;
389 buttonpress(XEvent *e) {
390 unsigned int i, x, click;
393 XButtonPressedEvent *ev = &e->xbutton;
396 if(ev->window == selmon->barwin && ev->x >= selmon->btx) {
401 while(ev->x >= x && ++i < LENGTH(tags));
402 if(i < LENGTH(tags)) {
406 else if(ev->x < x + blw)
408 else if(ev->x > selmon->wx + selmon->ww - TEXTW(stext))
409 click = ClkStatusText;
413 else if((c = getclient(ev->window))) {
415 click = ClkClientWin;
418 for(i = 0; i < LENGTH(buttons); i++)
419 if(click == buttons[i].click && buttons[i].func && buttons[i].button == ev->button
420 && CLEANMASK(buttons[i].mask) == CLEANMASK(ev->state))
421 buttons[i].func(click == ClkTagBar && buttons[i].arg.i == 0 ? &arg : &buttons[i].arg);
427 xerrorxlib = XSetErrorHandler(xerrorstart);
429 /* this causes an error if some other window manager is running */
430 XSelectInput(dpy, DefaultRootWindow(dpy), SubstructureRedirectMask);
433 die("dwm: another window manager is already running\n");
434 XSetErrorHandler(xerror);
441 Layout foo = { "", NULL };
445 lt[selmon->sellt] = &foo;
447 /* TODO: consider simplifying cleanup code of the stack, perhaps do that in cleanmons() ? */
448 for(m = mons; m; m = m->next)
452 XFreeFontSet(dpy, dc.font.set);
454 XFreeFont(dpy, dc.font.xfont);
455 XUngrabKey(dpy, AnyKey, AnyModifier, root);
456 XFreePixmap(dpy, dc.drawable);
458 XFreeCursor(dpy, cursor[CurNormal]);
459 XFreeCursor(dpy, cursor[CurResize]);
460 XFreeCursor(dpy, cursor[CurMove]);
463 XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime);
472 XUnmapWindow(dpy, mons->barwin);
473 XDestroyWindow(dpy, mons->barwin);
480 clearurgent(Client *c) {
484 if(!(wmh = XGetWMHints(dpy, c->win)))
486 wmh->flags &= ~XUrgencyHint;
487 XSetWMHints(dpy, c->win, wmh);
492 configure(Client *c) {
495 ce.type = ConfigureNotify;
503 ce.border_width = c->bw;
505 ce.override_redirect = False;
506 XSendEvent(dpy, c->win, False, StructureNotifyMask, (XEvent *)&ce);
510 configurenotify(XEvent *e) {
512 XConfigureEvent *ev = &e->xconfigure;
514 if(ev->window == root && (ev->width != sw || ev->height != sh)) {
519 XFreePixmap(dpy, dc.drawable);
520 dc.drawable = XCreatePixmap(dpy, root, sw, bh, DefaultDepth(dpy, screen));
522 for(m = mons; m; m = m->next)
523 XMoveResizeWindow(dpy, m->barwin, m->wx, m->by, m->ww, bh);
529 configurerequest(XEvent *e) {
531 XConfigureRequestEvent *ev = &e->xconfigurerequest;
534 if((c = getclient(ev->window))) {
535 if(ev->value_mask & CWBorderWidth)
536 c->bw = ev->border_width;
537 else if(c->isfloating || !lt[selmon->sellt]->arrange) {
538 if(ev->value_mask & CWX)
540 if(ev->value_mask & CWY)
542 if(ev->value_mask & CWWidth)
544 if(ev->value_mask & CWHeight)
546 if((c->x - sx + c->w) > sw && c->isfloating)
547 c->x = sx + (sw / 2 - c->w / 2); /* center in x direction */
548 if((c->y - sy + c->h) > sh && c->isfloating)
549 c->y = sy + (sh / 2 - c->h / 2); /* center in y direction */
550 if((ev->value_mask & (CWX|CWY)) && !(ev->value_mask & (CWWidth|CWHeight)))
553 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h);
561 wc.width = ev->width;
562 wc.height = ev->height;
563 wc.border_width = ev->border_width;
564 wc.sibling = ev->above;
565 wc.stack_mode = ev->detail;
566 XConfigureWindow(dpy, ev->window, ev->value_mask, &wc);
572 destroynotify(XEvent *e) {
574 XDestroyWindowEvent *ev = &e->xdestroywindow;
576 if((c = getclient(ev->window)))
584 for(tc = &c->mon->clients; *tc && *tc != c; tc = &(*tc)->next);
589 detachstack(Client *c) {
592 for(tc = &c->mon->stack; *tc && *tc != c; tc = &(*tc)->snext);
597 die(const char *errstr, ...) {
600 va_start(ap, errstr);
601 vfprintf(stderr, errstr, ap);
607 drawbar(Monitor *m) {
609 unsigned int i, occ = 0, urg = 0;
613 for(c = m->clients; c; c = c->next) {
623 buf[0] = m->screen_number + '0';
626 drawtext(buf, selmon == m ? dc.sel : dc.norm, True);
629 #endif /* XINERAMA */
631 for(i = 0; i < LENGTH(tags); i++) {
632 dc.w = TEXTW(tags[i]);
633 col = m->tagset[m->seltags] & 1 << i ? dc.sel : dc.norm;
634 drawtext(tags[i], col, urg & 1 << i);
635 drawsquare(m == selmon && selmon->sel && selmon->sel->tags & 1 << i,
636 occ & 1 << i, urg & 1 << i, col);
641 drawtext(lt[m->sellt]->symbol, dc.norm, False);
653 drawtext(stext, dc.norm, False);
654 if((dc.w = dc.x - x) > bh) {
657 drawtext(selmon->sel->name, dc.sel, False);
658 drawsquare(selmon->sel->isfixed, selmon->sel->isfloating, False, dc.sel);
661 drawtext(NULL, dc.norm, False);
667 drawtext(NULL, dc.norm, False);
669 XCopyArea(dpy, dc.drawable, m->barwin, dc.gc, 0, 0, m->ww, bh, 0, 0);
677 for(m = mons; m; m = m->next)
682 drawsquare(Bool filled, Bool empty, Bool invert, unsigned long col[ColLast]) {
685 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
687 gcv.foreground = col[invert ? ColBG : ColFG];
688 XChangeGC(dpy, dc.gc, GCForeground, &gcv);
689 x = (dc.font.ascent + dc.font.descent + 2) / 4;
693 r.width = r.height = x + 1;
694 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
697 r.width = r.height = x;
698 XDrawRectangles(dpy, dc.drawable, dc.gc, &r, 1);
703 drawtext(const char *text, unsigned long col[ColLast], Bool invert) {
705 int i, x, y, h, len, olen;
706 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
708 XSetForeground(dpy, dc.gc, col[invert ? ColFG : ColBG]);
709 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
713 h = dc.font.ascent + dc.font.descent;
714 y = dc.y + (dc.h / 2) - (h / 2) + dc.font.ascent;
716 /* shorten text if necessary */
717 for(len = MIN(olen, sizeof buf); len && textnw(text, len) > dc.w - h; len--);
720 memcpy(buf, text, len);
722 for(i = len; i && i > len - 3; buf[--i] = '.');
723 XSetForeground(dpy, dc.gc, col[invert ? ColBG : ColFG]);
725 XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
727 XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
731 enternotify(XEvent *e) {
733 XCrossingEvent *ev = &e->xcrossing;
735 if((ev->mode != NotifyNormal || ev->detail == NotifyInferior) && ev->window != root)
737 if((c = getclient(ev->window)))
746 XExposeEvent *ev = &e->xexpose;
749 for(m = mons; m; m = m->next)
750 if(ev->window == m->barwin) {
758 if(!c || !ISVISIBLE(c))
759 for(c = selmon->stack; c && !ISVISIBLE(c); c = c->snext);
760 if(selmon->sel && selmon->sel != c) {
761 grabbuttons(selmon->sel, False);
762 XSetWindowBorder(dpy, selmon->sel->win, dc.norm[ColBorder]);
769 grabbuttons(c, True);
770 XSetWindowBorder(dpy, c->win, dc.sel[ColBorder]);
771 XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
774 XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
780 focusin(XEvent *e) { /* there are some broken focus acquiring clients */
781 XFocusChangeEvent *ev = &e->xfocus;
783 if(selmon->sel && ev->window != selmon->sel->win)
784 XSetInputFocus(dpy, selmon->sel->win, RevertToPointerRoot, CurrentTime);
789 focusmon(const Arg *arg) {
793 for(i = 0, m = mons; m; m = m->next, i++)
801 #endif /* XINERAMA */
804 focusstack(const Arg *arg) {
805 Client *c = NULL, *i;
810 for(c = selmon->sel->next; c && !ISVISIBLE(c); c = c->next);
812 for(c = selmon->clients; c && !ISVISIBLE(c); c = c->next);
815 for(i = selmon->clients; i != selmon->sel; i = i->next)
819 for(; i; i = i->next)
830 getclient(Window w) {
834 for(m = mons; m; m = m->next)
835 for(c = m->clients; c && c->win != w; c = c->next);
840 getcolor(const char *colstr) {
841 Colormap cmap = DefaultColormap(dpy, screen);
844 if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
845 die("error, cannot allocate color '%s'\n", colstr);
853 unsigned char *p = NULL;
854 unsigned long n, extra;
857 status = XGetWindowProperty(dpy, w, wmatom[WMState], 0L, 2L, False, wmatom[WMState],
858 &real, &format, &n, &extra, (unsigned char **)&p);
859 if(status != Success)
868 gettextprop(Window w, Atom atom, char *text, unsigned int size) {
873 if(!text || size == 0)
876 XGetTextProperty(dpy, w, &name, atom);
879 if(name.encoding == XA_STRING)
880 strncpy(text, (char *)name.value, size - 1);
882 if(XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success
884 strncpy(text, *list, size - 1);
885 XFreeStringList(list);
888 text[size - 1] = '\0';
894 grabbuttons(Client *c, Bool focused) {
898 unsigned int modifiers[] = { 0, LockMask, numlockmask, numlockmask|LockMask };
899 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
901 for(i = 0; i < LENGTH(buttons); i++)
902 if(buttons[i].click == ClkClientWin)
903 for(j = 0; j < LENGTH(modifiers); j++)
904 XGrabButton(dpy, buttons[i].button,
905 buttons[i].mask | modifiers[j],
906 c->win, False, BUTTONMASK,
907 GrabModeAsync, GrabModeSync, None, None);
909 XGrabButton(dpy, AnyButton, AnyModifier, c->win, False,
910 BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
919 unsigned int modifiers[] = { 0, LockMask, numlockmask, numlockmask|LockMask };
922 XUngrabKey(dpy, AnyKey, AnyModifier, root);
923 for(i = 0; i < LENGTH(keys); i++) {
924 if((code = XKeysymToKeycode(dpy, keys[i].keysym)))
925 for(j = 0; j < LENGTH(modifiers); j++)
926 XGrabKey(dpy, code, keys[i].mod | modifiers[j], root,
927 True, GrabModeAsync, GrabModeAsync);
933 initfont(const char *fontstr) {
934 char *def, **missing;
938 dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
941 fprintf(stderr, "dwm: missing fontset: %s\n", missing[n]);
942 XFreeStringList(missing);
945 XFontSetExtents *font_extents;
946 XFontStruct **xfonts;
948 dc.font.ascent = dc.font.descent = 0;
949 font_extents = XExtentsOfFontSet(dc.font.set);
950 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
951 for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
952 dc.font.ascent = MAX(dc.font.ascent, (*xfonts)->ascent);
953 dc.font.descent = MAX(dc.font.descent,(*xfonts)->descent);
958 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr))
959 && !(dc.font.xfont = XLoadQueryFont(dpy, "fixed")))
960 die("error, cannot load font: '%s'\n", fontstr);
961 dc.font.ascent = dc.font.xfont->ascent;
962 dc.font.descent = dc.font.xfont->descent;
964 dc.font.height = dc.font.ascent + dc.font.descent;
968 isprotodel(Client *c) {
973 if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
974 for(i = 0; !ret && i < n; i++)
975 if(protocols[i] == wmatom[WMDelete])
983 keypress(XEvent *e) {
989 keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
990 for(i = 0; i < LENGTH(keys); i++)
991 if(keysym == keys[i].keysym
992 && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state)
994 keys[i].func(&(keys[i].arg));
998 killclient(const Arg *arg) {
1003 if(isprotodel(selmon->sel)) {
1004 ev.type = ClientMessage;
1005 ev.xclient.window = selmon->sel->win;
1006 ev.xclient.message_type = wmatom[WMProtocols];
1007 ev.xclient.format = 32;
1008 ev.xclient.data.l[0] = wmatom[WMDelete];
1009 ev.xclient.data.l[1] = CurrentTime;
1010 XSendEvent(dpy, selmon->sel->win, False, NoEventMask, &ev);
1013 XKillClient(dpy, selmon->sel->win);
1017 manage(Window w, XWindowAttributes *wa) {
1019 Client *c, *t = NULL;
1020 Window trans = None;
1023 if(!(c = malloc(sizeof(Client))))
1024 die("fatal: could not malloc() %u bytes\n", sizeof(Client));
1034 c->oldbw = wa->border_width;
1035 if(c->w == sw && c->h == sh) {
1041 if(c->x + WIDTH(c) > sx + sw)
1042 c->x = sx + sw - WIDTH(c);
1043 if(c->y + HEIGHT(c) > sy + sh)
1044 c->y = sy + sh - HEIGHT(c);
1045 c->x = MAX(c->x, sx);
1046 /* only fix client y-offset, if the client center might cover the bar */
1047 c->y = MAX(c->y, ((selmon->by == 0) && (c->x + (c->w / 2) >= selmon->wx)
1048 && (c->x + (c->w / 2) < selmon->wx + selmon->ww)) ? bh : sy);
1052 wc.border_width = c->bw;
1053 XConfigureWindow(dpy, w, CWBorderWidth, &wc);
1054 XSetWindowBorder(dpy, w, dc.norm[ColBorder]);
1055 configure(c); /* propagates border_width, if size doesn't change */
1057 XSelectInput(dpy, w, EnterWindowMask|FocusChangeMask|PropertyChangeMask|StructureNotifyMask);
1058 grabbuttons(c, False);
1060 if(XGetTransientForHint(dpy, w, &trans))
1061 t = getclient(trans);
1067 c->isfloating = trans != None || c->isfixed;
1069 XRaiseWindow(dpy, c->win);
1072 XMoveResizeWindow(dpy, c->win, c->x + 2 * sw, c->y, c->w, c->h); /* some windows require this */
1073 XMapWindow(dpy, c->win);
1074 setclientstate(c, NormalState);
1079 mappingnotify(XEvent *e) {
1080 XMappingEvent *ev = &e->xmapping;
1082 XRefreshKeyboardMapping(ev);
1083 if(ev->request == MappingKeyboard)
1088 maprequest(XEvent *e) {
1089 static XWindowAttributes wa;
1090 XMapRequestEvent *ev = &e->xmaprequest;
1092 if(!XGetWindowAttributes(dpy, ev->window, &wa))
1094 if(wa.override_redirect)
1096 if(!getclient(ev->window))
1097 manage(ev->window, &wa);
1101 monocle(Monitor *m) {
1104 for(c = nexttiled(m->clients); c; c = nexttiled(c->next))
1105 resize(c, m->wx, m->wy, m->ww - 2 * c->bw, m->wh - 2 * c->bw);
1109 movemouse(const Arg *arg) {
1110 int x, y, ocx, ocy, di, nx, ny;
1116 if(!(c = selmon->sel))
1121 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1122 None, cursor[CurMove], CurrentTime) != GrabSuccess)
1124 XQueryPointer(dpy, root, &dummy, &dummy, &x, &y, &di, &di, &dui);
1126 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
1128 case ConfigureRequest:
1131 handler[ev.type](&ev);
1134 nx = ocx + (ev.xmotion.x - x);
1135 ny = ocy + (ev.xmotion.y - y);
1136 if(snap && nx >= selmon->wx && nx <= selmon->wx + selmon->ww
1137 && ny >= selmon->wy && ny <= selmon->wy + selmon->wh) {
1138 if(abs(selmon->wx - nx) < snap)
1140 else if(abs((selmon->wx + selmon->ww) - (nx + WIDTH(c))) < snap)
1141 nx = selmon->wx + selmon->ww - WIDTH(c);
1142 if(abs(selmon->wy - ny) < snap)
1144 else if(abs((selmon->wy + selmon->wh) - (ny + HEIGHT(c))) < snap)
1145 ny = selmon->wy + selmon->wh - HEIGHT(c);
1146 if(!c->isfloating && lt[selmon->sellt]->arrange
1147 && (abs(nx - c->x) > snap || abs(ny - c->y) > snap))
1148 togglefloating(NULL);
1150 if(!lt[selmon->sellt]->arrange || c->isfloating)
1151 resize(c, nx, ny, c->w, c->h);
1155 while(ev.type != ButtonRelease);
1156 XUngrabPointer(dpy, CurrentTime);
1160 nexttiled(Client *c) {
1162 for(; c && (c->isfloating || !ISVISIBLE(c)); c = c->next);
1167 propertynotify(XEvent *e) {
1170 XPropertyEvent *ev = &e->xproperty;
1172 if((ev->window == root) && (ev->atom == XA_WM_NAME))
1174 else if(ev->state == PropertyDelete)
1175 return; /* ignore */
1176 else if((c = getclient(ev->window))) {
1179 case XA_WM_TRANSIENT_FOR:
1180 XGetTransientForHint(dpy, c->win, &trans);
1181 if(!c->isfloating && (c->isfloating = (getclient(trans) != NULL)))
1184 case XA_WM_NORMAL_HINTS:
1192 if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
1194 if(c == selmon->sel)
1201 quit(const Arg *arg) {
1206 resize(Client *c, int x, int y, int w, int h) {
1209 if(applysizehints(c, &x, &y, &w, &h)) {
1212 c->w = wc.width = w;
1213 c->h = wc.height = h;
1214 wc.border_width = c->bw;
1215 XConfigureWindow(dpy, c->win,
1216 CWX|CWY|CWWidth|CWHeight|CWBorderWidth, &wc);
1223 resizemouse(const Arg *arg) {
1229 if(!(c = selmon->sel))
1234 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1235 None, cursor[CurResize], CurrentTime) != GrabSuccess)
1237 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->bw - 1, c->h + c->bw - 1);
1239 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
1241 case ConfigureRequest:
1244 handler[ev.type](&ev);
1247 nw = MAX(ev.xmotion.x - ocx - 2 * c->bw + 1, 1);
1248 nh = MAX(ev.xmotion.y - ocy - 2 * c->bw + 1, 1);
1250 if(snap && nw >= selmon->wx && nw <= selmon->wx + selmon->ww
1251 && nh >= selmon->wy && nh <= selmon->wy + selmon->wh) {
1252 if(!c->isfloating && lt[selmon->sellt]->arrange
1253 && (abs(nw - c->w) > snap || abs(nh - c->h) > snap))
1254 togglefloating(NULL);
1256 if(!lt[selmon->sellt]->arrange || c->isfloating)
1257 resize(c, c->x, c->y, nw, nh);
1261 while(ev.type != ButtonRelease);
1262 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->bw - 1, c->h + c->bw - 1);
1263 XUngrabPointer(dpy, CurrentTime);
1264 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1268 restack(Monitor *m) {
1276 if(m == selmon && (selmon->sel->isfloating || !lt[m->sellt]->arrange))
1277 XRaiseWindow(dpy, selmon->sel->win);
1278 if(lt[m->sellt]->arrange) {
1279 wc.stack_mode = Below;
1280 wc.sibling = m->barwin;
1281 for(c = m->stack; c; c = c->snext)
1282 if(!c->isfloating && ISVISIBLE(c)) {
1283 XConfigureWindow(dpy, c->win, CWSibling|CWStackMode, &wc);
1284 wc.sibling = c->win;
1288 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1295 /* main event loop */
1297 while(running && !XNextEvent(dpy, &ev)) {
1298 if(handler[ev.type])
1299 (handler[ev.type])(&ev); /* call handler */
1305 unsigned int i, num;
1306 Window d1, d2, *wins = NULL;
1307 XWindowAttributes wa;
1309 if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1310 for(i = 0; i < num; i++) {
1311 if(!XGetWindowAttributes(dpy, wins[i], &wa)
1312 || wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1314 if(wa.map_state == IsViewable || getstate(wins[i]) == IconicState)
1315 manage(wins[i], &wa);
1317 for(i = 0; i < num; i++) { /* now the transients */
1318 if(!XGetWindowAttributes(dpy, wins[i], &wa))
1320 if(XGetTransientForHint(dpy, wins[i], &d1)
1321 && (wa.map_state == IsViewable || getstate(wins[i]) == IconicState))
1322 manage(wins[i], &wa);
1330 setclientstate(Client *c, long state) {
1331 long data[] = {state, None};
1333 XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1334 PropModeReplace, (unsigned char *)data, 2);
1338 setlayout(const Arg *arg) {
1339 if(!arg || !arg->v || arg->v != lt[selmon->sellt])
1342 lt[selmon->sellt] = (Layout *)arg->v;
1349 /* arg > 1.0 will set mfact absolutly */
1351 setmfact(const Arg *arg) {
1354 if(!arg || !lt[selmon->sellt]->arrange)
1356 f = arg->f < 1.0 ? arg->f + selmon->mfact : arg->f - 1.0;
1357 if(f < 0.1 || f > 0.9)
1367 XSetWindowAttributes wa;
1370 screen = DefaultScreen(dpy);
1371 root = RootWindow(dpy, screen);
1375 sw = DisplayWidth(dpy, screen);
1376 sh = DisplayHeight(dpy, screen);
1377 bh = dc.h = dc.font.height + 2;
1378 lt[0] = &layouts[0];
1379 lt[1] = &layouts[1 % LENGTH(layouts)];
1383 wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1384 wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1385 wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1386 netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1387 netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1390 cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1391 cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1392 cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1394 /* init appearance */
1395 dc.norm[ColBorder] = getcolor(normbordercolor);
1396 dc.norm[ColBG] = getcolor(normbgcolor);
1397 dc.norm[ColFG] = getcolor(normfgcolor);
1398 dc.sel[ColBorder] = getcolor(selbordercolor);
1399 dc.sel[ColBG] = getcolor(selbgcolor);
1400 dc.sel[ColFG] = getcolor(selfgcolor);
1401 dc.drawable = XCreatePixmap(dpy, root, DisplayWidth(dpy, screen), bh, DefaultDepth(dpy, screen));
1402 dc.gc = XCreateGC(dpy, root, 0, NULL);
1403 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
1405 XSetFont(dpy, dc.gc, dc.font.xfont->fid);
1408 for(blw = i = 0; LENGTH(layouts) > 1 && i < LENGTH(layouts); i++) {
1409 w = TEXTW(layouts[i].symbol);
1415 /* EWMH support per view */
1416 XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1417 PropModeReplace, (unsigned char *) netatom, NetLast);
1419 /* select for events */
1420 wa.cursor = cursor[CurNormal];
1421 wa.event_mask = SubstructureRedirectMask|SubstructureNotifyMask|ButtonPressMask
1422 |EnterWindowMask|LeaveWindowMask|StructureNotifyMask
1423 |PropertyChangeMask;
1424 XChangeWindowAttributes(dpy, root, CWEventMask|CWCursor, &wa);
1425 XSelectInput(dpy, root, wa.event_mask);
1431 showhide(Client *c) {
1434 if(ISVISIBLE(c)) { /* show clients top down */
1435 XMoveWindow(dpy, c->win, c->x, c->y);
1436 if(!lt[c->mon->sellt]->arrange || c->isfloating)
1437 resize(c, c->x, c->y, c->w, c->h);
1440 else { /* hide clients bottom up */
1442 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
1448 sigchld(int signal) {
1449 while(0 < waitpid(-1, NULL, WNOHANG));
1453 spawn(const Arg *arg) {
1454 signal(SIGCHLD, sigchld);
1457 close(ConnectionNumber(dpy));
1459 execvp(((char **)arg->v)[0], (char **)arg->v);
1460 fprintf(stderr, "dwm: execvp %s", ((char **)arg->v)[0]);
1467 tag(const Arg *arg) {
1468 if(selmon->sel && arg->ui & TAGMASK) {
1469 selmon->sel->tags = arg->ui & TAGMASK;
1476 tagmon(const Arg *arg) {
1481 if(!(c = selmon->sel))
1483 for(i = 0, m = mons; m; m = m->next, i++)
1490 selmon->sel = selmon->stack;
1496 #endif /* XINERAMA */
1499 textnw(const char *text, unsigned int len) {
1503 XmbTextExtents(dc.font.set, text, len, NULL, &r);
1506 return XTextWidth(dc.font.xfont, text, len);
1515 for(n = 0, c = nexttiled(m->clients); c; c = nexttiled(c->next), n++);
1520 c = nexttiled(m->clients);
1521 mw = m->mfact * m->ww;
1522 resize(c, m->wx, m->wy, (n == 1 ? m->ww : mw) - 2 * c->bw, m->wh - 2 * c->bw);
1528 x = (m->wx + mw > c->x + c->w) ? c->x + c->w + 2 * c->bw : m->wx + mw;
1530 w = (m->wx + mw > c->x + c->w) ? m->wx + m->ww - x : m->ww - mw;
1535 for(i = 0, c = nexttiled(c->next); c; c = nexttiled(c->next), i++) {
1536 resize(c, x, y, w - 2 * c->bw, /* remainder */ ((i + 1 == n)
1537 ? m->wy + m->wh - y - 2 * c->bw : h - 2 * c->bw));
1539 y = c->y + HEIGHT(c);
1544 togglebar(const Arg *arg) {
1545 selmon->showbar = !selmon->showbar;
1546 updatebarpos(selmon);
1547 XMoveResizeWindow(dpy, selmon->barwin, selmon->wx, selmon->by, selmon->ww, bh);
1552 togglefloating(const Arg *arg) {
1555 selmon->sel->isfloating = !selmon->sel->isfloating || selmon->sel->isfixed;
1556 if(selmon->sel->isfloating)
1557 resize(selmon->sel, selmon->sel->x, selmon->sel->y, selmon->sel->w, selmon->sel->h);
1562 toggletag(const Arg *arg) {
1568 mask = selmon->sel->tags ^ (arg->ui & TAGMASK);
1570 selmon->sel->tags = mask;
1576 toggleview(const Arg *arg) {
1577 unsigned int mask = selmon->tagset[selmon->seltags] ^ (arg->ui & TAGMASK);
1580 selmon->tagset[selmon->seltags] = mask;
1586 unmanage(Client *c) {
1589 wc.border_width = c->oldbw;
1590 /* The server grab construct avoids race conditions. */
1592 XSetErrorHandler(xerrordummy);
1593 XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
1596 if(selmon->sel == c)
1598 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1599 setclientstate(c, WithdrawnState);
1602 XSetErrorHandler(xerror);
1608 unmapnotify(XEvent *e) {
1610 XUnmapEvent *ev = &e->xunmap;
1612 if((c = getclient(ev->window)))
1619 XSetWindowAttributes wa;
1621 wa.override_redirect = True;
1622 wa.background_pixmap = ParentRelative;
1623 wa.event_mask = ButtonPressMask|ExposureMask;
1625 for(m = mons; m; m = m->next) {
1626 m->barwin = XCreateWindow(dpy, root, m->wx, m->by, m->ww, bh, 0, DefaultDepth(dpy, screen),
1628 CopyFromParent, DefaultVisual(dpy, screen),
1629 CWOverrideRedirect|CWBackPixmap|CWEventMask, &wa);
1630 XDefineCursor(dpy, m->barwin, cursor[CurNormal]);
1631 XMapRaised(dpy, m->barwin);
1636 updatebarpos(Monitor *m) {
1641 m->by = m->topbar ? m->wy : m->wy + m->wh;
1642 m->wy = m->topbar ? m->wy + bh : m->wy;
1652 Monitor *newmons = NULL, *m, *tm;
1655 XineramaScreenInfo *info = NULL;
1657 if(XineramaIsActive(dpy))
1658 info = XineramaQueryScreens(dpy, &n);
1660 /* allocate monitor(s) for the new geometry setup */
1661 for(i = 0; i < n; i++) {
1662 m = (Monitor *)malloc(sizeof(Monitor));
1667 /* initialise monitor(s) */
1669 if(XineramaIsActive(dpy)) {
1670 for(i = 0, m = newmons; m; m = m->next, i++) {
1671 m->screen_number = info[i].screen_number;
1672 m->wx = info[i].x_org;
1673 m->my = m->wy = info[i].y_org;
1674 m->ww = info[i].width;
1675 m->mh = m->wh = info[i].height;
1681 /* default monitor setup */
1683 m->screen_number = 0;
1690 /* bar geometry setup */
1691 for(m = newmons; m; m = m->next) {
1692 /* TODO: consider removing the following values from config.h */
1698 m->tagset[0] = m->tagset[1] = 1;
1700 m->showbar = showbar;
1703 /* reassign all clients with same screen number */
1704 for(tm = mons; tm; tm = tm->next)
1705 if(tm->screen_number == m->screen_number) {
1706 m->clients = tm->clients;
1707 m->sel = m->stack = tm->stack;
1710 for(c = m->clients; c; c = c->next)
1715 /* reassign left over clients of disappeared monitors */
1716 for(tm = mons; tm; tm = tm->next) {
1717 while((c = tm->clients)) {
1726 /* select focused monitor */
1732 if(XQueryPointer(dpy, root, &dummy, &dummy, &x, &y, &di, &di, &dui))
1733 for(m = newmons; m; m = m->next)
1734 if(INRECT(x, y, m->wx, m->wy, m->ww, m->wh)) {
1740 /* final assignment of new monitors */
1746 updatenumlockmask(void) {
1748 XModifierKeymap *modmap;
1751 modmap = XGetModifierMapping(dpy);
1752 for(i = 0; i < 8; i++)
1753 for(j = 0; j < modmap->max_keypermod; j++)
1754 if(modmap->modifiermap[i * modmap->max_keypermod + j]
1755 == XKeysymToKeycode(dpy, XK_Num_Lock))
1756 numlockmask = (1 << i);
1757 XFreeModifiermap(modmap);
1761 updatesizehints(Client *c) {
1765 if(!XGetWMNormalHints(dpy, c->win, &size, &msize))
1766 /* size is uninitialized, ensure that size.flags aren't used */
1768 if(size.flags & PBaseSize) {
1769 c->basew = size.base_width;
1770 c->baseh = size.base_height;
1772 else if(size.flags & PMinSize) {
1773 c->basew = size.min_width;
1774 c->baseh = size.min_height;
1777 c->basew = c->baseh = 0;
1778 if(size.flags & PResizeInc) {
1779 c->incw = size.width_inc;
1780 c->inch = size.height_inc;
1783 c->incw = c->inch = 0;
1784 if(size.flags & PMaxSize) {
1785 c->maxw = size.max_width;
1786 c->maxh = size.max_height;
1789 c->maxw = c->maxh = 0;
1790 if(size.flags & PMinSize) {
1791 c->minw = size.min_width;
1792 c->minh = size.min_height;
1794 else if(size.flags & PBaseSize) {
1795 c->minw = size.base_width;
1796 c->minh = size.base_height;
1799 c->minw = c->minh = 0;
1800 if(size.flags & PAspect) {
1801 c->mina = (float)size.min_aspect.y / (float)size.min_aspect.x;
1802 c->maxa = (float)size.max_aspect.x / (float)size.max_aspect.y;
1805 c->maxa = c->mina = 0.0;
1806 c->isfixed = (c->maxw && c->minw && c->maxh && c->minh
1807 && c->maxw == c->minw && c->maxh == c->minh);
1811 updatetitle(Client *c) {
1812 if(!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
1813 gettextprop(c->win, XA_WM_NAME, c->name, sizeof c->name);
1818 if(!gettextprop(root, XA_WM_NAME, stext, sizeof(stext)))
1819 strcpy(stext, "dwm-"VERSION);
1824 updatewmhints(Client *c) {
1827 if((wmh = XGetWMHints(dpy, c->win))) {
1828 if(c == selmon->sel && wmh->flags & XUrgencyHint) {
1829 wmh->flags &= ~XUrgencyHint;
1830 XSetWMHints(dpy, c->win, wmh);
1833 c->isurgent = (wmh->flags & XUrgencyHint) ? True : False;
1840 view(const Arg *arg) {
1841 if((arg->ui & TAGMASK) == selmon->tagset[selmon->seltags])
1843 selmon->seltags ^= 1; /* toggle sel tagset */
1844 if(arg->ui & TAGMASK)
1845 selmon->tagset[selmon->seltags] = arg->ui & TAGMASK;
1849 /* There's no way to check accesses to destroyed windows, thus those cases are
1850 * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
1851 * default error handler, which may call exit. */
1853 xerror(Display *dpy, XErrorEvent *ee) {
1854 if(ee->error_code == BadWindow
1855 || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1856 || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1857 || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1858 || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1859 || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1860 || (ee->request_code == X_GrabButton && ee->error_code == BadAccess)
1861 || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1862 || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1864 fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1865 ee->request_code, ee->error_code);
1866 return xerrorxlib(dpy, ee); /* may call exit */
1870 xerrordummy(Display *dpy, XErrorEvent *ee) {
1874 /* Startup Error handler to check if another window manager
1875 * is already running. */
1877 xerrorstart(Display *dpy, XErrorEvent *ee) {
1883 zoom(const Arg *arg) {
1884 Client *c = selmon->sel;
1886 if(!lt[selmon->sellt]->arrange || lt[selmon->sellt]->arrange == monocle || (selmon->sel && selmon->sel->isfloating))
1888 if(c == nexttiled(selmon->clients))
1889 if(!c || !(c = nexttiled(c->next)))
1898 main(int argc, char *argv[]) {
1899 if(argc == 2 && !strcmp("-v", argv[1]))
1900 die("dwm-"VERSION", © 2006-2009 dwm engineers, see LICENSE for details\n");
1902 die("usage: dwm [-v]\n");
1904 if(!setlocale(LC_CTYPE, "") || !XSupportsLocale())
1905 fputs("warning: no locale support\n", stderr);
1907 if(!(dpy = XOpenDisplay(NULL)))
1908 die("dwm: cannot open display\n");