1 //#define XINULATOR /* debug, simulates dual head */
2 /* See LICENSE file for copyright and license details.
4 * dynamic window manager is designed like any other X client as well. It is
5 * driven through handling X events. In contrast to other X clients, a window
6 * manager selects for SubstructureRedirectMask on the root window, to receive
7 * events about window (dis-)appearance. Only one X connection at a time is
8 * allowed to select for this event mask.
10 * The event handlers of dwm are organized in an array which is accessed
11 * whenever a new event has been fetched. This allows event dispatching
14 * Each child of the root window is called a client, except windows which have
15 * set the override_redirect flag. Clients are organized in a global
16 * linked client list, the focus history is remembered through a global
17 * stack list. Each client contains a bit array to indicate the tags of a
20 * Keys and tagging rules are organized as arrays and defined in config.h.
22 * To understand everything else, start reading main().
32 #include <sys/types.h>
34 #include <X11/cursorfont.h>
35 #include <X11/keysym.h>
36 #include <X11/Xatom.h>
38 #include <X11/Xproto.h>
39 #include <X11/Xutil.h>
41 #include <X11/extensions/Xinerama.h>
45 #define BUTTONMASK (ButtonPressMask|ButtonReleaseMask)
46 #define CLEANMASK(mask) (mask & ~(numlockmask|LockMask))
47 #define INRECT(X,Y,RX,RY,RW,RH) ((X) >= (RX) && (X) < (RX) + (RW) && (Y) >= (RY) && (Y) < (RY) + (RH))
48 #define ISVISIBLE(C) ((C->tags & C->mon->tagset[C->mon->seltags]))
49 #define LENGTH(X) (sizeof X / sizeof X[0])
50 #define MAX(A, B) ((A) > (B) ? (A) : (B))
51 #define MIN(A, B) ((A) < (B) ? (A) : (B))
52 #define MOUSEMASK (BUTTONMASK|PointerMotionMask)
53 #define WIDTH(X) ((X)->w + 2 * (X)->bw)
54 #define HEIGHT(X) ((X)->h + 2 * (X)->bw)
55 #define TAGMASK ((int)((1LL << LENGTH(tags)) - 1))
56 #define TEXTW(X) (textnw(X, strlen(X)) + dc.font.height)
59 enum { CurNormal, CurResize, CurMove, CurLast }; /* cursor */
60 enum { ColBorder, ColFG, ColBG, ColLast }; /* color */
61 enum { NetSupported, NetWMName, NetLast }; /* EWMH atoms */
62 enum { WMProtocols, WMDelete, WMState, WMLast }; /* default atoms */
63 enum { ClkTagBar, ClkLtSymbol, ClkStatusText, ClkWinTitle,
64 ClkClientWin, ClkRootWin, ClkLast }; /* clicks */
77 void (*func)(const Arg *arg);
81 typedef struct Monitor Monitor;
82 typedef struct Client Client;
87 int basew, baseh, incw, inch, maxw, maxh, minw, minh;
90 Bool isfixed, isfloating, isurgent;
99 unsigned long norm[ColLast];
100 unsigned long sel[ColLast];
110 } DC; /* draw context */
115 void (*func)(const Arg *);
121 void (*arrange)(Monitor *);
127 int by, btx; /* bar geometry */
128 int my, mh; /* vertical screen size*/
129 int wx, wy, ww, wh; /* window area */
130 unsigned int seltags;
132 unsigned int tagset[2];
144 const char *instance;
150 /* function declarations */
151 static void applyrules(Client *c);
152 static Bool applysizehints(Client *c, int *x, int *y, int *w, int *h);
153 static void arrange(void);
154 static void attach(Client *c);
155 static void attachstack(Client *c);
156 static void buttonpress(XEvent *e);
157 static void checkotherwm(void);
158 static void cleanup(void);
159 static void cleanupmons(void);
160 static void clearurgent(Client *c);
161 static void configure(Client *c);
162 static void configurenotify(XEvent *e);
163 static void configurerequest(XEvent *e);
164 static void destroynotify(XEvent *e);
165 static void detach(Client *c);
166 static void detachstack(Client *c);
167 static void die(const char *errstr, ...);
168 static void drawbar(Monitor *m);
169 static void drawbars();
170 static void drawsquare(Bool filled, Bool empty, Bool invert, unsigned long col[ColLast]);
171 static void drawtext(const char *text, unsigned long col[ColLast], Bool invert);
172 static void enternotify(XEvent *e);
173 static void expose(XEvent *e);
174 static void focus(Client *c);
175 static void focusin(XEvent *e);
176 static void focusstack(const Arg *arg);
177 static Client *getclient(Window w);
178 static unsigned long getcolor(const char *colstr);
179 static long getstate(Window w);
180 static Bool gettextprop(Window w, Atom atom, char *text, unsigned int size);
181 static void grabbuttons(Client *c, Bool focused);
182 static void grabkeys(void);
183 static void initfont(const char *fontstr);
184 static Bool isprotodel(Client *c);
185 static void keypress(XEvent *e);
186 static void killclient(const Arg *arg);
187 static void manage(Window w, XWindowAttributes *wa);
188 static void mappingnotify(XEvent *e);
189 static void maprequest(XEvent *e);
190 static void monocle(Monitor *m);
191 static void movemouse(const Arg *arg);
192 static Client *nexttiled(Client *c);
193 static void propertynotify(XEvent *e);
194 static void quit(const Arg *arg);
195 static void resize(Client *c, int x, int y, int w, int h);
196 static void resizemouse(const Arg *arg);
197 static void restack(Monitor *m);
198 static void run(void);
199 static void scan(void);
200 static void setclientstate(Client *c, long state);
201 static void setlayout(const Arg *arg);
202 static void setmfact(const Arg *arg);
203 static void setup(void);
204 static void showhide(Client *c);
205 static void sigchld(int signal);
206 static void spawn(const Arg *arg);
207 static void tag(const Arg *arg);
208 static int textnw(const char *text, unsigned int len);
209 static void tile(Monitor *);
210 static void togglebar(const Arg *arg);
211 static void togglefloating(const Arg *arg);
212 static void toggletag(const Arg *arg);
213 static void toggleview(const Arg *arg);
214 static void unfocus(Client *c);
215 static void unmanage(Client *c);
216 static void unmapnotify(XEvent *e);
217 static void updategeom(void);
218 static void updatebarpos(Monitor *m);
219 static void updatebars(void);
220 static void updatenumlockmask(void);
221 static void updatesizehints(Client *c);
222 static void updatestatus(void);
223 static void updatetitle(Client *c);
224 static void updatewmhints(Client *c);
225 static void view(const Arg *arg);
226 static int xerror(Display *dpy, XErrorEvent *ee);
227 static int xerrordummy(Display *dpy, XErrorEvent *ee);
228 static int xerrorstart(Display *dpy, XErrorEvent *ee);
229 static void zoom(const Arg *arg);
231 static void focusmon(const Arg *arg);
232 static void tagmon(const Arg *arg);
233 #endif /* XINERAMA */
236 static char stext[256];
238 static int sx, sy, sw, sh; /* X display screen geometry x, y, width, height */
239 static int bh, blw = 0; /* bar geometry */
240 static int (*xerrorxlib)(Display *, XErrorEvent *);
241 static unsigned int numlockmask = 0;
242 static void (*handler[LASTEvent]) (XEvent *) = {
243 [ButtonPress] = buttonpress,
244 [ConfigureRequest] = configurerequest,
245 [ConfigureNotify] = configurenotify,
246 [DestroyNotify] = destroynotify,
247 [EnterNotify] = enternotify,
250 [KeyPress] = keypress,
251 [MappingNotify] = mappingnotify,
252 [MapRequest] = maprequest,
253 [PropertyNotify] = propertynotify,
254 [UnmapNotify] = unmapnotify
256 static Atom wmatom[WMLast], netatom[NetLast];
258 static Bool running = True;
259 static Cursor cursor[CurLast];
262 static Layout *lt[] = { NULL, NULL };
263 static Monitor *mons = NULL, *selmon = NULL;
265 /* configuration, allows nested code to access above variables */
268 /* compile-time check if all tags fit into an unsigned int bit array. */
269 struct NumTags { char limitexceeded[sizeof(unsigned int) * 8 < LENGTH(tags) ? -1 : 1]; };
271 /* function implementations */
273 applyrules(Client *c) {
276 XClassHint ch = { 0 };
279 c->isfloating = c->tags = 0;
280 if(XGetClassHint(dpy, c->win, &ch)) {
281 for(i = 0; i < LENGTH(rules); i++) {
283 if((!r->title || strstr(c->name, r->title))
284 && (!r->class || (ch.res_class && strstr(ch.res_class, r->class)))
285 && (!r->instance || (ch.res_name && strstr(ch.res_name, r->instance)))) {
286 c->isfloating = r->isfloating;
295 c->tags = c->tags & TAGMASK ? c->tags & TAGMASK : c->mon->tagset[c->mon->seltags];
299 applysizehints(Client *c, int *x, int *y, int *w, int *h) {
302 /* set minimum possible */
310 if(*x + *w + 2 * c->bw < sx)
312 if(*y + *h + 2 * c->bw < sy)
319 if(resizehints || c->isfloating) {
320 /* see last two sentences in ICCCM 4.1.2.3 */
321 baseismin = c->basew == c->minw && c->baseh == c->minh;
323 if(!baseismin) { /* temporarily remove base dimensions */
328 /* adjust for aspect limits */
329 if(c->mina > 0 && c->maxa > 0) {
330 if(c->maxa < (float)*w / *h)
332 else if(c->mina < (float)*h / *w)
336 if(baseismin) { /* increment calculation requires this */
341 /* adjust for increment value */
347 /* restore base dimensions */
351 *w = MAX(*w, c->minw);
352 *h = MAX(*h, c->minh);
355 *w = MIN(*w, c->maxw);
358 *h = MIN(*h, c->maxh);
360 return *x != c->x || *y != c->y || *w != c->w || *h != c->h;
367 /* optimise two loops into one, check focus(NULL) */
368 for(m = mons; m; m = m->next)
371 for(m = mons; m; m = m->next) {
372 if(lt[m->sellt]->arrange)
373 lt[m->sellt]->arrange(m);
380 c->next = c->mon->clients;
385 attachstack(Client *c) {
386 c->snext = c->mon->stack;
391 buttonpress(XEvent *e) {
392 unsigned int i, x, click;
396 XButtonPressedEvent *ev = &e->xbutton;
399 /* focus monitor if necessary */
400 for(m = mons; m; m = m->next)
401 if(ev->window == m->barwin) {
403 unfocus(selmon->stack);
409 if(ev->window == selmon->barwin && ev->x >= selmon->btx) {
414 while(ev->x >= x && ++i < LENGTH(tags));
415 if(i < LENGTH(tags)) {
419 else if(ev->x < x + blw)
421 else if(ev->x > selmon->wx + selmon->ww - TEXTW(stext))
422 click = ClkStatusText;
426 else if((c = getclient(ev->window))) {
428 click = ClkClientWin;
431 for(i = 0; i < LENGTH(buttons); i++)
432 if(click == buttons[i].click && buttons[i].func && buttons[i].button == ev->button
433 && CLEANMASK(buttons[i].mask) == CLEANMASK(ev->state))
434 buttons[i].func(click == ClkTagBar && buttons[i].arg.i == 0 ? &arg : &buttons[i].arg);
440 xerrorxlib = XSetErrorHandler(xerrorstart);
442 /* this causes an error if some other window manager is running */
443 XSelectInput(dpy, DefaultRootWindow(dpy), SubstructureRedirectMask);
446 die("dwm: another window manager is already running\n");
447 XSetErrorHandler(xerror);
454 Layout foo = { "", NULL };
458 lt[selmon->sellt] = &foo;
460 /* TODO: consider simplifying cleanup code of the stack, perhaps do that in cleanmons() ? */
461 for(m = mons; m; m = m->next)
465 XFreeFontSet(dpy, dc.font.set);
467 XFreeFont(dpy, dc.font.xfont);
468 XUngrabKey(dpy, AnyKey, AnyModifier, root);
469 XFreePixmap(dpy, dc.drawable);
471 XFreeCursor(dpy, cursor[CurNormal]);
472 XFreeCursor(dpy, cursor[CurResize]);
473 XFreeCursor(dpy, cursor[CurMove]);
476 XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime);
485 XUnmapWindow(dpy, mons->barwin);
486 XDestroyWindow(dpy, mons->barwin);
493 clearurgent(Client *c) {
497 if(!(wmh = XGetWMHints(dpy, c->win)))
499 wmh->flags &= ~XUrgencyHint;
500 XSetWMHints(dpy, c->win, wmh);
505 configure(Client *c) {
508 ce.type = ConfigureNotify;
516 ce.border_width = c->bw;
518 ce.override_redirect = False;
519 XSendEvent(dpy, c->win, False, StructureNotifyMask, (XEvent *)&ce);
523 configurenotify(XEvent *e) {
525 XConfigureEvent *ev = &e->xconfigure;
527 if(ev->window == root && (ev->width != sw || ev->height != sh)) {
532 XFreePixmap(dpy, dc.drawable);
533 dc.drawable = XCreatePixmap(dpy, root, sw, bh, DefaultDepth(dpy, screen));
535 for(m = mons; m; m = m->next)
536 XMoveResizeWindow(dpy, m->barwin, m->wx, m->by, m->ww, bh);
542 configurerequest(XEvent *e) {
544 XConfigureRequestEvent *ev = &e->xconfigurerequest;
547 if((c = getclient(ev->window))) {
548 if(ev->value_mask & CWBorderWidth)
549 c->bw = ev->border_width;
550 else if(c->isfloating || !lt[selmon->sellt]->arrange) {
551 if(ev->value_mask & CWX)
553 if(ev->value_mask & CWY)
555 if(ev->value_mask & CWWidth)
557 if(ev->value_mask & CWHeight)
559 if((c->x - sx + c->w) > sw && c->isfloating)
560 c->x = sx + (sw / 2 - c->w / 2); /* center in x direction */
561 if((c->y - sy + c->h) > sh && c->isfloating)
562 c->y = sy + (sh / 2 - c->h / 2); /* center in y direction */
563 if((ev->value_mask & (CWX|CWY)) && !(ev->value_mask & (CWWidth|CWHeight)))
566 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h);
574 wc.width = ev->width;
575 wc.height = ev->height;
576 wc.border_width = ev->border_width;
577 wc.sibling = ev->above;
578 wc.stack_mode = ev->detail;
579 XConfigureWindow(dpy, ev->window, ev->value_mask, &wc);
585 destroynotify(XEvent *e) {
587 XDestroyWindowEvent *ev = &e->xdestroywindow;
589 if((c = getclient(ev->window)))
597 for(tc = &c->mon->clients; *tc && *tc != c; tc = &(*tc)->next);
602 detachstack(Client *c) {
605 for(tc = &c->mon->stack; *tc && *tc != c; tc = &(*tc)->snext);
610 die(const char *errstr, ...) {
613 va_start(ap, errstr);
614 vfprintf(stderr, errstr, ap);
620 drawbar(Monitor *m) {
622 unsigned int i, occ = 0, urg = 0;
626 for(c = m->clients; c; c = c->next) {
636 buf[0] = m->screen_number + '0';
639 drawtext(buf, selmon == m ? dc.sel : dc.norm, True);
642 #endif /* XINERAMA */
644 for(i = 0; i < LENGTH(tags); i++) {
645 dc.w = TEXTW(tags[i]);
646 col = m->tagset[m->seltags] & 1 << i ? dc.sel : dc.norm;
647 drawtext(tags[i], col, urg & 1 << i);
648 drawsquare(m == selmon && selmon->sel && selmon->sel->tags & 1 << i,
649 occ & 1 << i, urg & 1 << i, col);
654 drawtext(lt[m->sellt]->symbol, dc.norm, False);
659 if(m == selmon) { /* status is only drawn on selected monitor */
666 drawtext(stext, dc.norm, False);
671 if((dc.w = dc.x - x) > bh) {
674 col = m == selmon ? dc.sel : dc.norm;
675 drawtext(m->sel->name, col, False);
676 drawsquare(m->sel->isfixed, m->sel->isfloating, False, col);
679 drawtext(NULL, dc.norm, False);
681 XCopyArea(dpy, dc.drawable, m->barwin, dc.gc, 0, 0, m->ww, bh, 0, 0);
689 for(m = mons; m; m = m->next)
694 drawsquare(Bool filled, Bool empty, Bool invert, unsigned long col[ColLast]) {
697 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
699 gcv.foreground = col[invert ? ColBG : ColFG];
700 XChangeGC(dpy, dc.gc, GCForeground, &gcv);
701 x = (dc.font.ascent + dc.font.descent + 2) / 4;
705 r.width = r.height = x + 1;
706 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
709 r.width = r.height = x;
710 XDrawRectangles(dpy, dc.drawable, dc.gc, &r, 1);
715 drawtext(const char *text, unsigned long col[ColLast], Bool invert) {
717 int i, x, y, h, len, olen;
718 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
720 XSetForeground(dpy, dc.gc, col[invert ? ColFG : ColBG]);
721 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
725 h = dc.font.ascent + dc.font.descent;
726 y = dc.y + (dc.h / 2) - (h / 2) + dc.font.ascent;
728 /* shorten text if necessary */
729 for(len = MIN(olen, sizeof buf); len && textnw(text, len) > dc.w - h; len--);
732 memcpy(buf, text, len);
734 for(i = len; i && i > len - 3; buf[--i] = '.');
735 XSetForeground(dpy, dc.gc, col[invert ? ColBG : ColFG]);
737 XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
739 XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
743 enternotify(XEvent *e) {
745 XCrossingEvent *ev = &e->xcrossing;
747 if((ev->mode != NotifyNormal || ev->detail == NotifyInferior) && ev->window != root)
749 if((c = getclient(ev->window)))
758 XExposeEvent *ev = &e->xexpose;
761 for(m = mons; m; m = m->next)
762 if(ev->window == m->barwin) {
770 if(!c || !ISVISIBLE(c))
771 for(c = selmon->stack; c && !ISVISIBLE(c); c = c->snext);
773 unfocus(selmon->sel);
781 grabbuttons(c, True);
782 XSetWindowBorder(dpy, c->win, dc.sel[ColBorder]);
783 XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
786 XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
792 focusin(XEvent *e) { /* there are some broken focus acquiring clients */
793 XFocusChangeEvent *ev = &e->xfocus;
795 if(selmon->sel && ev->window != selmon->sel->win)
796 XSetInputFocus(dpy, selmon->sel->win, RevertToPointerRoot, CurrentTime);
801 focusmon(const Arg *arg) {
805 for(i = 0, m = mons; m; m = m->next, i++)
810 unfocus(selmon->stack);
818 #endif /* XINERAMA */
821 focusstack(const Arg *arg) {
822 Client *c = NULL, *i;
827 for(c = selmon->sel->next; c && !ISVISIBLE(c); c = c->next);
829 for(c = selmon->clients; c && !ISVISIBLE(c); c = c->next);
832 for(i = selmon->clients; i != selmon->sel; i = i->next)
836 for(; i; i = i->next)
847 getclient(Window w) {
851 for(m = mons; m; m = m->next)
852 for(c = m->clients; c; c = c->next)
859 getcolor(const char *colstr) {
860 Colormap cmap = DefaultColormap(dpy, screen);
863 if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
864 die("error, cannot allocate color '%s'\n", colstr);
872 unsigned char *p = NULL;
873 unsigned long n, extra;
876 status = XGetWindowProperty(dpy, w, wmatom[WMState], 0L, 2L, False, wmatom[WMState],
877 &real, &format, &n, &extra, (unsigned char **)&p);
878 if(status != Success)
887 gettextprop(Window w, Atom atom, char *text, unsigned int size) {
892 if(!text || size == 0)
895 XGetTextProperty(dpy, w, &name, atom);
898 if(name.encoding == XA_STRING)
899 strncpy(text, (char *)name.value, size - 1);
901 if(XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success
903 strncpy(text, *list, size - 1);
904 XFreeStringList(list);
907 text[size - 1] = '\0';
913 grabbuttons(Client *c, Bool focused) {
917 unsigned int modifiers[] = { 0, LockMask, numlockmask, numlockmask|LockMask };
918 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
920 for(i = 0; i < LENGTH(buttons); i++)
921 if(buttons[i].click == ClkClientWin)
922 for(j = 0; j < LENGTH(modifiers); j++)
923 XGrabButton(dpy, buttons[i].button,
924 buttons[i].mask | modifiers[j],
925 c->win, False, BUTTONMASK,
926 GrabModeAsync, GrabModeSync, None, None);
928 XGrabButton(dpy, AnyButton, AnyModifier, c->win, False,
929 BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
938 unsigned int modifiers[] = { 0, LockMask, numlockmask, numlockmask|LockMask };
941 XUngrabKey(dpy, AnyKey, AnyModifier, root);
942 for(i = 0; i < LENGTH(keys); i++) {
943 if((code = XKeysymToKeycode(dpy, keys[i].keysym)))
944 for(j = 0; j < LENGTH(modifiers); j++)
945 XGrabKey(dpy, code, keys[i].mod | modifiers[j], root,
946 True, GrabModeAsync, GrabModeAsync);
952 initfont(const char *fontstr) {
953 char *def, **missing;
957 dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
960 fprintf(stderr, "dwm: missing fontset: %s\n", missing[n]);
961 XFreeStringList(missing);
964 XFontSetExtents *font_extents;
965 XFontStruct **xfonts;
967 dc.font.ascent = dc.font.descent = 0;
968 font_extents = XExtentsOfFontSet(dc.font.set);
969 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
970 for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
971 dc.font.ascent = MAX(dc.font.ascent, (*xfonts)->ascent);
972 dc.font.descent = MAX(dc.font.descent,(*xfonts)->descent);
977 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr))
978 && !(dc.font.xfont = XLoadQueryFont(dpy, "fixed")))
979 die("error, cannot load font: '%s'\n", fontstr);
980 dc.font.ascent = dc.font.xfont->ascent;
981 dc.font.descent = dc.font.xfont->descent;
983 dc.font.height = dc.font.ascent + dc.font.descent;
987 isprotodel(Client *c) {
992 if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
993 for(i = 0; !ret && i < n; i++)
994 if(protocols[i] == wmatom[WMDelete])
1002 keypress(XEvent *e) {
1008 keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
1009 for(i = 0; i < LENGTH(keys); i++)
1010 if(keysym == keys[i].keysym
1011 && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state)
1013 keys[i].func(&(keys[i].arg));
1017 killclient(const Arg *arg) {
1022 if(isprotodel(selmon->sel)) {
1023 ev.type = ClientMessage;
1024 ev.xclient.window = selmon->sel->win;
1025 ev.xclient.message_type = wmatom[WMProtocols];
1026 ev.xclient.format = 32;
1027 ev.xclient.data.l[0] = wmatom[WMDelete];
1028 ev.xclient.data.l[1] = CurrentTime;
1029 XSendEvent(dpy, selmon->sel->win, False, NoEventMask, &ev);
1032 XKillClient(dpy, selmon->sel->win);
1036 manage(Window w, XWindowAttributes *wa) {
1038 Client *c, *t = NULL;
1039 Window trans = None;
1042 if(!(c = malloc(sizeof(Client))))
1043 die("fatal: could not malloc() %u bytes\n", sizeof(Client));
1053 c->oldbw = wa->border_width;
1054 if(c->w == sw && c->h == sh) {
1060 if(c->x + WIDTH(c) > sx + sw)
1061 c->x = sx + sw - WIDTH(c);
1062 if(c->y + HEIGHT(c) > sy + sh)
1063 c->y = sy + sh - HEIGHT(c);
1064 c->x = MAX(c->x, sx);
1065 /* only fix client y-offset, if the client center might cover the bar */
1066 c->y = MAX(c->y, ((c->mon->by == 0) && (c->x + (c->w / 2) >= c->mon->wx)
1067 && (c->x + (c->w / 2) < c->mon->wx + c->mon->ww)) ? bh : sy);
1071 wc.border_width = c->bw;
1072 XConfigureWindow(dpy, w, CWBorderWidth, &wc);
1073 XSetWindowBorder(dpy, w, dc.norm[ColBorder]);
1074 configure(c); /* propagates border_width, if size doesn't change */
1076 XSelectInput(dpy, w, EnterWindowMask|FocusChangeMask|PropertyChangeMask|StructureNotifyMask);
1077 grabbuttons(c, False);
1079 if(XGetTransientForHint(dpy, w, &trans))
1080 t = getclient(trans);
1086 c->isfloating = trans != None || c->isfixed;
1088 XRaiseWindow(dpy, c->win);
1091 XMoveResizeWindow(dpy, c->win, c->x + 2 * sw, c->y, c->w, c->h); /* some windows require this */
1092 XMapWindow(dpy, c->win);
1093 setclientstate(c, NormalState);
1098 mappingnotify(XEvent *e) {
1099 XMappingEvent *ev = &e->xmapping;
1101 XRefreshKeyboardMapping(ev);
1102 if(ev->request == MappingKeyboard)
1107 maprequest(XEvent *e) {
1108 static XWindowAttributes wa;
1109 XMapRequestEvent *ev = &e->xmaprequest;
1111 if(!XGetWindowAttributes(dpy, ev->window, &wa))
1113 if(wa.override_redirect)
1115 if(!getclient(ev->window))
1116 manage(ev->window, &wa);
1120 monocle(Monitor *m) {
1123 for(c = nexttiled(m->clients); c; c = nexttiled(c->next))
1124 resize(c, m->wx, m->wy, m->ww - 2 * c->bw, m->wh - 2 * c->bw);
1128 movemouse(const Arg *arg) {
1129 int x, y, ocx, ocy, di, nx, ny;
1135 if(!(c = selmon->sel))
1140 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1141 None, cursor[CurMove], CurrentTime) != GrabSuccess)
1143 XQueryPointer(dpy, root, &dummy, &dummy, &x, &y, &di, &di, &dui);
1145 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
1147 case ConfigureRequest:
1150 handler[ev.type](&ev);
1153 nx = ocx + (ev.xmotion.x - x);
1154 ny = ocy + (ev.xmotion.y - y);
1155 if(snap && nx >= selmon->wx && nx <= selmon->wx + selmon->ww
1156 && ny >= selmon->wy && ny <= selmon->wy + selmon->wh) {
1157 if(abs(selmon->wx - nx) < snap)
1159 else if(abs((selmon->wx + selmon->ww) - (nx + WIDTH(c))) < snap)
1160 nx = selmon->wx + selmon->ww - WIDTH(c);
1161 if(abs(selmon->wy - ny) < snap)
1163 else if(abs((selmon->wy + selmon->wh) - (ny + HEIGHT(c))) < snap)
1164 ny = selmon->wy + selmon->wh - HEIGHT(c);
1165 if(!c->isfloating && lt[selmon->sellt]->arrange
1166 && (abs(nx - c->x) > snap || abs(ny - c->y) > snap))
1167 togglefloating(NULL);
1169 if(!lt[selmon->sellt]->arrange || c->isfloating)
1170 resize(c, nx, ny, c->w, c->h);
1174 while(ev.type != ButtonRelease);
1175 XUngrabPointer(dpy, CurrentTime);
1179 nexttiled(Client *c) {
1180 for(; c && (c->isfloating || !ISVISIBLE(c)); c = c->next);
1185 propertynotify(XEvent *e) {
1188 XPropertyEvent *ev = &e->xproperty;
1190 if((ev->window == root) && (ev->atom == XA_WM_NAME))
1192 else if(ev->state == PropertyDelete)
1193 return; /* ignore */
1194 else if((c = getclient(ev->window))) {
1197 case XA_WM_TRANSIENT_FOR:
1198 XGetTransientForHint(dpy, c->win, &trans);
1199 if(!c->isfloating && (c->isfloating = (getclient(trans) != NULL)))
1202 case XA_WM_NORMAL_HINTS:
1210 if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
1212 if(c == selmon->sel)
1219 quit(const Arg *arg) {
1224 resize(Client *c, int x, int y, int w, int h) {
1227 if(applysizehints(c, &x, &y, &w, &h)) {
1230 c->w = wc.width = w;
1231 c->h = wc.height = h;
1232 wc.border_width = c->bw;
1233 XConfigureWindow(dpy, c->win, CWX|CWY|CWWidth|CWHeight|CWBorderWidth, &wc);
1240 resizemouse(const Arg *arg) {
1246 if(!(c = selmon->sel))
1251 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1252 None, cursor[CurResize], CurrentTime) != GrabSuccess)
1254 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->bw - 1, c->h + c->bw - 1);
1256 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
1258 case ConfigureRequest:
1261 handler[ev.type](&ev);
1264 nw = MAX(ev.xmotion.x - ocx - 2 * c->bw + 1, 1);
1265 nh = MAX(ev.xmotion.y - ocy - 2 * c->bw + 1, 1);
1267 if(snap && nw >= selmon->wx && nw <= selmon->wx + selmon->ww
1268 && nh >= selmon->wy && nh <= selmon->wy + selmon->wh) {
1269 if(!c->isfloating && lt[selmon->sellt]->arrange
1270 && (abs(nw - c->w) > snap || abs(nh - c->h) > snap))
1271 togglefloating(NULL);
1273 if(!lt[selmon->sellt]->arrange || c->isfloating)
1274 resize(c, c->x, c->y, nw, nh);
1278 while(ev.type != ButtonRelease);
1279 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->bw - 1, c->h + c->bw - 1);
1280 XUngrabPointer(dpy, CurrentTime);
1281 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1285 restack(Monitor *m) {
1293 if(m->sel->isfloating || !lt[m->sellt]->arrange)
1294 XRaiseWindow(dpy, m->sel->win);
1295 if(lt[m->sellt]->arrange) {
1296 wc.stack_mode = Below;
1297 wc.sibling = m->barwin;
1298 for(c = m->stack; c; c = c->snext)
1299 if(!c->isfloating && ISVISIBLE(c)) {
1300 XConfigureWindow(dpy, c->win, CWSibling|CWStackMode, &wc);
1301 wc.sibling = c->win;
1305 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1312 /* main event loop */
1314 while(running && !XNextEvent(dpy, &ev)) {
1315 if(handler[ev.type])
1316 (handler[ev.type])(&ev); /* call handler */
1322 unsigned int i, num;
1323 Window d1, d2, *wins = NULL;
1324 XWindowAttributes wa;
1326 if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1327 for(i = 0; i < num; i++) {
1328 if(!XGetWindowAttributes(dpy, wins[i], &wa)
1329 || wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1331 if(wa.map_state == IsViewable || getstate(wins[i]) == IconicState)
1332 manage(wins[i], &wa);
1334 for(i = 0; i < num; i++) { /* now the transients */
1335 if(!XGetWindowAttributes(dpy, wins[i], &wa))
1337 if(XGetTransientForHint(dpy, wins[i], &d1)
1338 && (wa.map_state == IsViewable || getstate(wins[i]) == IconicState))
1339 manage(wins[i], &wa);
1347 setclientstate(Client *c, long state) {
1348 long data[] = {state, None};
1350 XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1351 PropModeReplace, (unsigned char *)data, 2);
1355 setlayout(const Arg *arg) {
1356 if(!arg || !arg->v || arg->v != lt[selmon->sellt])
1359 lt[selmon->sellt] = (Layout *)arg->v;
1366 /* arg > 1.0 will set mfact absolutly */
1368 setmfact(const Arg *arg) {
1371 if(!arg || !lt[selmon->sellt]->arrange)
1373 f = arg->f < 1.0 ? arg->f + selmon->mfact : arg->f - 1.0;
1374 if(f < 0.1 || f > 0.9)
1384 XSetWindowAttributes wa;
1387 screen = DefaultScreen(dpy);
1388 root = RootWindow(dpy, screen);
1392 sw = DisplayWidth(dpy, screen);
1393 sh = DisplayHeight(dpy, screen);
1394 bh = dc.h = dc.font.height + 2;
1395 lt[0] = &layouts[0];
1396 lt[1] = &layouts[1 % LENGTH(layouts)];
1400 wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1401 wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1402 wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1403 netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1404 netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1407 cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1408 cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1409 cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1411 /* init appearance */
1412 dc.norm[ColBorder] = getcolor(normbordercolor);
1413 dc.norm[ColBG] = getcolor(normbgcolor);
1414 dc.norm[ColFG] = getcolor(normfgcolor);
1415 dc.sel[ColBorder] = getcolor(selbordercolor);
1416 dc.sel[ColBG] = getcolor(selbgcolor);
1417 dc.sel[ColFG] = getcolor(selfgcolor);
1418 dc.drawable = XCreatePixmap(dpy, root, DisplayWidth(dpy, screen), bh, DefaultDepth(dpy, screen));
1419 dc.gc = XCreateGC(dpy, root, 0, NULL);
1420 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
1422 XSetFont(dpy, dc.gc, dc.font.xfont->fid);
1425 for(blw = i = 0; LENGTH(layouts) > 1 && i < LENGTH(layouts); i++) {
1426 w = TEXTW(layouts[i].symbol);
1432 /* EWMH support per view */
1433 XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1434 PropModeReplace, (unsigned char *) netatom, NetLast);
1436 /* select for events */
1437 wa.cursor = cursor[CurNormal];
1438 wa.event_mask = SubstructureRedirectMask|SubstructureNotifyMask|ButtonPressMask
1439 |EnterWindowMask|LeaveWindowMask|StructureNotifyMask
1440 |PropertyChangeMask;
1441 XChangeWindowAttributes(dpy, root, CWEventMask|CWCursor, &wa);
1442 XSelectInput(dpy, root, wa.event_mask);
1448 showhide(Client *c) {
1451 if(ISVISIBLE(c)) { /* show clients top down */
1452 XMoveWindow(dpy, c->win, c->x, c->y);
1453 if(!lt[c->mon->sellt]->arrange || c->isfloating)
1454 resize(c, c->x, c->y, c->w, c->h);
1457 else { /* hide clients bottom up */
1459 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
1465 sigchld(int signal) {
1466 while(0 < waitpid(-1, NULL, WNOHANG));
1470 spawn(const Arg *arg) {
1471 signal(SIGCHLD, sigchld);
1474 close(ConnectionNumber(dpy));
1476 execvp(((char **)arg->v)[0], (char **)arg->v);
1477 fprintf(stderr, "dwm: execvp %s", ((char **)arg->v)[0]);
1484 tag(const Arg *arg) {
1485 if(selmon->sel && arg->ui & TAGMASK) {
1486 selmon->sel->tags = arg->ui & TAGMASK;
1493 tagmon(const Arg *arg) {
1498 if(!(c = selmon->sel))
1500 for(i = 0, m = mons; m; m = m->next, i++)
1507 selmon->sel = selmon->stack;
1513 #endif /* XINERAMA */
1516 textnw(const char *text, unsigned int len) {
1520 XmbTextExtents(dc.font.set, text, len, NULL, &r);
1523 return XTextWidth(dc.font.xfont, text, len);
1532 for(n = 0, c = nexttiled(m->clients); c; c = nexttiled(c->next), n++);
1537 c = nexttiled(m->clients);
1538 mw = m->mfact * m->ww;
1539 resize(c, m->wx, m->wy, (n == 1 ? m->ww : mw) - 2 * c->bw, m->wh - 2 * c->bw);
1545 x = (m->wx + mw > c->x + c->w) ? c->x + c->w + 2 * c->bw : m->wx + mw;
1547 w = (m->wx + mw > c->x + c->w) ? m->wx + m->ww - x : m->ww - mw;
1552 for(i = 0, c = nexttiled(c->next); c; c = nexttiled(c->next), i++) {
1553 resize(c, x, y, w - 2 * c->bw, /* remainder */ ((i + 1 == n)
1554 ? m->wy + m->wh - y - 2 * c->bw : h - 2 * c->bw));
1556 y = c->y + HEIGHT(c);
1561 togglebar(const Arg *arg) {
1562 selmon->showbar = !selmon->showbar;
1563 updatebarpos(selmon);
1564 XMoveResizeWindow(dpy, selmon->barwin, selmon->wx, selmon->by, selmon->ww, bh);
1569 togglefloating(const Arg *arg) {
1572 selmon->sel->isfloating = !selmon->sel->isfloating || selmon->sel->isfixed;
1573 if(selmon->sel->isfloating)
1574 resize(selmon->sel, selmon->sel->x, selmon->sel->y, selmon->sel->w, selmon->sel->h);
1579 toggletag(const Arg *arg) {
1585 mask = selmon->sel->tags ^ (arg->ui & TAGMASK);
1587 selmon->sel->tags = mask;
1593 toggleview(const Arg *arg) {
1594 unsigned int mask = selmon->tagset[selmon->seltags] ^ (arg->ui & TAGMASK);
1597 selmon->tagset[selmon->seltags] = mask;
1603 unfocus(Client *c) {
1606 grabbuttons(c, False);
1607 XSetWindowBorder(dpy, c->win, dc.norm[ColBorder]);
1608 XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
1612 unmanage(Client *c) {
1615 wc.border_width = c->oldbw;
1616 /* The server grab construct avoids race conditions. */
1618 XSetErrorHandler(xerrordummy);
1619 XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
1622 if(c->mon->sel == c) {
1623 c->mon->sel = c->mon->stack;
1626 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1627 setclientstate(c, WithdrawnState);
1630 XSetErrorHandler(xerror);
1636 unmapnotify(XEvent *e) {
1638 XUnmapEvent *ev = &e->xunmap;
1640 if((c = getclient(ev->window)))
1647 XSetWindowAttributes wa;
1649 wa.override_redirect = True;
1650 wa.background_pixmap = ParentRelative;
1651 wa.event_mask = ButtonPressMask|ExposureMask;
1653 for(m = mons; m; m = m->next) {
1654 m->barwin = XCreateWindow(dpy, root, m->wx, m->by, m->ww, bh, 0, DefaultDepth(dpy, screen),
1656 CopyFromParent, DefaultVisual(dpy, screen),
1657 CWOverrideRedirect|CWBackPixmap|CWEventMask, &wa);
1658 XDefineCursor(dpy, m->barwin, cursor[CurNormal]);
1659 XMapRaised(dpy, m->barwin);
1664 updatebarpos(Monitor *m) {
1669 m->by = m->topbar ? m->wy : m->wy + m->wh;
1670 m->wy = m->topbar ? m->wy + bh : m->wy;
1678 int i, di, n = 1, x, y;
1681 Monitor *newmons = NULL, *m, *tm;
1686 #elif defined(XINERAMA)
1687 XineramaScreenInfo *info = NULL;
1689 if(XineramaIsActive(dpy))
1690 info = XineramaQueryScreens(dpy, &n);
1692 /* allocate monitor(s) for the new geometry setup */
1693 for(i = 0; i < n; i++) {
1694 m = (Monitor *)malloc(sizeof(Monitor));
1699 /* initialise monitor(s) */
1703 m->screen_number = 0;
1707 m->mh = m->wh = sh / 2;
1709 m->screen_number = 1;
1711 m->my = m->wy = sy + sh / 2;
1713 m->mh = m->wh = sh / 2;
1716 #elif defined(XINERAMA)
1717 if(XineramaIsActive(dpy)) {
1718 for(i = 0, m = newmons; m; m = m->next, i++) {
1719 m->screen_number = info[i].screen_number;
1720 m->wx = info[i].x_org;
1721 m->my = m->wy = info[i].y_org;
1722 m->ww = info[i].width;
1723 m->mh = m->wh = info[i].height;
1729 /* default monitor setup */
1731 m->screen_number = 0;
1738 /* bar geometry setup */
1739 for(m = newmons; m; m = m->next) {
1740 /* TODO: consider removing the following values from config.h */
1746 m->tagset[0] = m->tagset[1] = 1;
1748 m->showbar = showbar;
1753 /* reassign left over clients of disappeared monitors */
1754 for(tm = mons; tm; tm = tm->next)
1755 while(tm->clients) {
1757 tm->clients = c->next;
1764 /* select focused monitor */
1766 if(XQueryPointer(dpy, root, &dummy, &dummy, &x, &y, &di, &di, &dui))
1767 for(m = newmons; m; m = m->next)
1768 if(INRECT(x, y, m->wx, m->wy, m->ww, m->wh)) {
1773 /* final assignment of new monitors */
1779 updatenumlockmask(void) {
1781 XModifierKeymap *modmap;
1784 modmap = XGetModifierMapping(dpy);
1785 for(i = 0; i < 8; i++)
1786 for(j = 0; j < modmap->max_keypermod; j++)
1787 if(modmap->modifiermap[i * modmap->max_keypermod + j]
1788 == XKeysymToKeycode(dpy, XK_Num_Lock))
1789 numlockmask = (1 << i);
1790 XFreeModifiermap(modmap);
1794 updatesizehints(Client *c) {
1798 if(!XGetWMNormalHints(dpy, c->win, &size, &msize))
1799 /* size is uninitialized, ensure that size.flags aren't used */
1801 if(size.flags & PBaseSize) {
1802 c->basew = size.base_width;
1803 c->baseh = size.base_height;
1805 else if(size.flags & PMinSize) {
1806 c->basew = size.min_width;
1807 c->baseh = size.min_height;
1810 c->basew = c->baseh = 0;
1811 if(size.flags & PResizeInc) {
1812 c->incw = size.width_inc;
1813 c->inch = size.height_inc;
1816 c->incw = c->inch = 0;
1817 if(size.flags & PMaxSize) {
1818 c->maxw = size.max_width;
1819 c->maxh = size.max_height;
1822 c->maxw = c->maxh = 0;
1823 if(size.flags & PMinSize) {
1824 c->minw = size.min_width;
1825 c->minh = size.min_height;
1827 else if(size.flags & PBaseSize) {
1828 c->minw = size.base_width;
1829 c->minh = size.base_height;
1832 c->minw = c->minh = 0;
1833 if(size.flags & PAspect) {
1834 c->mina = (float)size.min_aspect.y / (float)size.min_aspect.x;
1835 c->maxa = (float)size.max_aspect.x / (float)size.max_aspect.y;
1838 c->maxa = c->mina = 0.0;
1839 c->isfixed = (c->maxw && c->minw && c->maxh && c->minh
1840 && c->maxw == c->minw && c->maxh == c->minh);
1844 updatetitle(Client *c) {
1845 if(!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
1846 gettextprop(c->win, XA_WM_NAME, c->name, sizeof c->name);
1851 if(!gettextprop(root, XA_WM_NAME, stext, sizeof(stext)))
1852 strcpy(stext, "dwm-"VERSION);
1857 updatewmhints(Client *c) {
1860 if((wmh = XGetWMHints(dpy, c->win))) {
1861 if(c == selmon->sel && wmh->flags & XUrgencyHint) {
1862 wmh->flags &= ~XUrgencyHint;
1863 XSetWMHints(dpy, c->win, wmh);
1866 c->isurgent = (wmh->flags & XUrgencyHint) ? True : False;
1873 view(const Arg *arg) {
1874 if((arg->ui & TAGMASK) == selmon->tagset[selmon->seltags])
1876 selmon->seltags ^= 1; /* toggle sel tagset */
1877 if(arg->ui & TAGMASK)
1878 selmon->tagset[selmon->seltags] = arg->ui & TAGMASK;
1882 /* There's no way to check accesses to destroyed windows, thus those cases are
1883 * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
1884 * default error handler, which may call exit. */
1886 xerror(Display *dpy, XErrorEvent *ee) {
1887 if(ee->error_code == BadWindow
1888 || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1889 || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1890 || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1891 || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1892 || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1893 || (ee->request_code == X_GrabButton && ee->error_code == BadAccess)
1894 || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1895 || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1897 fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1898 ee->request_code, ee->error_code);
1899 return xerrorxlib(dpy, ee); /* may call exit */
1903 xerrordummy(Display *dpy, XErrorEvent *ee) {
1907 /* Startup Error handler to check if another window manager
1908 * is already running. */
1910 xerrorstart(Display *dpy, XErrorEvent *ee) {
1916 zoom(const Arg *arg) {
1917 Client *c = selmon->sel;
1919 if(!lt[selmon->sellt]->arrange || lt[selmon->sellt]->arrange == monocle || (selmon->sel && selmon->sel->isfloating))
1921 if(c == nexttiled(selmon->clients))
1922 if(!c || !(c = nexttiled(c->next)))
1931 main(int argc, char *argv[]) {
1932 if(argc == 2 && !strcmp("-v", argv[1]))
1933 die("dwm-"VERSION", © 2006-2009 dwm engineers, see LICENSE for details\n");
1935 die("usage: dwm [-v]\n");
1937 if(!setlocale(LC_CTYPE, "") || !XSupportsLocale())
1938 fputs("warning: no locale support\n", stderr);
1940 if(!(dpy = XOpenDisplay(NULL)))
1941 die("dwm: cannot open display\n");