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().
30 #include <sys/signal.h>
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[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))
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 Client Client;
86 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 void (*arrange)(void);
124 const char *instance;
130 /* function declarations */
131 static void applyrules(Client *c);
132 static void arrange(void);
133 static void attach(Client *c);
134 static void attachstack(Client *c);
135 static void buttonpress(XEvent *e);
136 static void checkotherwm(void);
137 static void cleanup(void);
138 static void clearurgent(Client *c);
139 static void configure(Client *c);
140 static void configurenotify(XEvent *e);
141 static void configurerequest(XEvent *e);
142 static void destroynotify(XEvent *e);
143 static void detach(Client *c);
144 static void detachstack(Client *c);
145 static void die(const char *errstr, ...);
146 static void drawbar(void);
147 static void drawsquare(Bool filled, Bool empty, Bool invert, unsigned long col[ColLast]);
148 static void drawtext(const char *text, unsigned long col[ColLast], Bool invert);
149 static void enternotify(XEvent *e);
150 static void expose(XEvent *e);
151 static void focus(Client *c);
152 static void focusin(XEvent *e);
153 static void focusstack(const Arg *arg);
154 static Client *getclient(Window w);
155 static unsigned long getcolor(const char *colstr);
156 static long getstate(Window w);
157 static Bool gettextprop(Window w, Atom atom, char *text, unsigned int size);
158 static void grabbuttons(Client *c, Bool focused);
159 static void grabkeys(void);
160 static void initfont(const char *fontstr);
161 static Bool isprotodel(Client *c);
162 static void keypress(XEvent *e);
163 static void killclient(const Arg *arg);
164 static void manage(Window w, XWindowAttributes *wa);
165 static void mappingnotify(XEvent *e);
166 static void maprequest(XEvent *e);
167 static void monocle(void);
168 static void movemouse(const Arg *arg);
169 static Client *nexttiled(Client *c);
170 static void propertynotify(XEvent *e);
171 static void quit(const Arg *arg);
172 static void resize(Client *c, int x, int y, int w, int h, Bool sizehints);
173 static void resizemouse(const Arg *arg);
174 static void restack(void);
175 static void run(void);
176 static void scan(void);
177 static void setclientstate(Client *c, long state);
178 static void setlayout(const Arg *arg);
179 static void setmfact(const Arg *arg);
180 static void setup(void);
181 static void showhide(Client *c);
182 static void sigchld(int signal);
183 static void spawn(const Arg *arg);
184 static void tag(const Arg *arg);
185 static int textnw(const char *text, unsigned int len);
186 static void tile(void);
187 static void togglebar(const Arg *arg);
188 static void togglefloating(const Arg *arg);
189 static void toggletag(const Arg *arg);
190 static void toggleview(const Arg *arg);
191 static void unmanage(Client *c);
192 static void unmapnotify(XEvent *e);
193 static void updatebar(void);
194 static void updategeom(void);
195 static void updatenumlockmask(void);
196 static void updatesizehints(Client *c);
197 static void updatestatus(void);
198 static void updatetitle(Client *c);
199 static void updatewmhints(Client *c);
200 static void view(const Arg *arg);
201 static int xerror(Display *dpy, XErrorEvent *ee);
202 static int xerrordummy(Display *dpy, XErrorEvent *ee);
203 static int xerrorstart(Display *dpy, XErrorEvent *ee);
204 static void zoom(const Arg *arg);
207 static char stext[256];
209 static int sx, sy, sw, sh; /* X display screen geometry x, y, width, height */
210 static int by, bh, blw; /* bar geometry y, height and layout symbol width */
211 static int wx, wy, ww, wh; /* window area geometry x, y, width, height, bar excluded */
212 static unsigned int seltags = 0, sellt = 0;
213 static int (*xerrorxlib)(Display *, XErrorEvent *);
214 static unsigned int numlockmask = 0;
215 static void (*handler[LASTEvent]) (XEvent *) = {
216 [ButtonPress] = buttonpress,
217 [ConfigureRequest] = configurerequest,
218 [ConfigureNotify] = configurenotify,
219 [DestroyNotify] = destroynotify,
220 [EnterNotify] = enternotify,
223 [KeyPress] = keypress,
224 [MappingNotify] = mappingnotify,
225 [MapRequest] = maprequest,
226 [PropertyNotify] = propertynotify,
227 [UnmapNotify] = unmapnotify
229 static Atom wmatom[WMLast], netatom[NetLast];
231 static Bool running = True;
232 static Client *clients = NULL;
233 static Client *sel = NULL;
234 static Client *stack = NULL;
235 static Cursor cursor[CurLast];
238 static Layout *lt[] = { NULL, NULL };
239 static Window root, barwin;
240 /* configuration, allows nested code to access above variables */
243 /* compile-time check if all tags fit into an unsigned int bit array. */
244 struct NumTags { char limitexceeded[sizeof(unsigned int) * 8 < LENGTH(tags) ? -1 : 1]; };
246 /* function implementations */
248 applyrules(Client *c) {
251 XClassHint ch = { 0 };
254 if(XGetClassHint(dpy, c->win, &ch)) {
255 for(i = 0; i < LENGTH(rules); i++) {
257 if((!r->title || strstr(c->name, r->title))
258 && (!r->class || (ch.res_class && strstr(ch.res_class, r->class)))
259 && (!r->instance || (ch.res_name && strstr(ch.res_name, r->instance)))) {
260 c->isfloating = r->isfloating;
261 c->tags |= r->tags & TAGMASK;
270 c->tags = tagset[seltags];
277 if(lt[sellt]->arrange)
278 lt[sellt]->arrange();
289 attachstack(Client *c) {
295 buttonpress(XEvent *e) {
296 unsigned int i, x, click;
299 XButtonPressedEvent *ev = &e->xbutton;
302 if(ev->window == barwin) {
304 do x += TEXTW(tags[i]); while(ev->x >= x && ++i < LENGTH(tags));
305 if(i < LENGTH(tags)) {
309 else if(ev->x < x + blw)
311 else if(ev->x > wx + ww - TEXTW(stext))
312 click = ClkStatusText;
316 else if((c = getclient(ev->window))) {
318 click = ClkClientWin;
321 for(i = 0; i < LENGTH(buttons); i++)
322 if(click == buttons[i].click && buttons[i].func && buttons[i].button == ev->button
323 && CLEANMASK(buttons[i].mask) == CLEANMASK(ev->state))
324 buttons[i].func(click == ClkTagBar && buttons[i].arg.i == 0 ? &arg : &buttons[i].arg);
330 xerrorxlib = XSetErrorHandler(xerrorstart);
332 /* this causes an error if some other window manager is running */
333 XSelectInput(dpy, DefaultRootWindow(dpy), SubstructureRedirectMask);
336 die("dwm: another window manager is already running\n");
337 XSetErrorHandler(xerror);
344 Layout foo = { "", NULL };
352 XFreeFontSet(dpy, dc.font.set);
354 XFreeFont(dpy, dc.font.xfont);
355 XUngrabKey(dpy, AnyKey, AnyModifier, root);
356 XFreePixmap(dpy, dc.drawable);
358 XFreeCursor(dpy, cursor[CurNormal]);
359 XFreeCursor(dpy, cursor[CurResize]);
360 XFreeCursor(dpy, cursor[CurMove]);
361 XDestroyWindow(dpy, barwin);
363 XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime);
367 clearurgent(Client *c) {
371 if(!(wmh = XGetWMHints(dpy, c->win)))
373 wmh->flags &= ~XUrgencyHint;
374 XSetWMHints(dpy, c->win, wmh);
379 configure(Client *c) {
382 ce.type = ConfigureNotify;
390 ce.border_width = c->bw;
392 ce.override_redirect = False;
393 XSendEvent(dpy, c->win, False, StructureNotifyMask, (XEvent *)&ce);
397 configurenotify(XEvent *e) {
398 XConfigureEvent *ev = &e->xconfigure;
400 if(ev->window == root && (ev->width != sw || ev->height != sh)) {
410 configurerequest(XEvent *e) {
412 XConfigureRequestEvent *ev = &e->xconfigurerequest;
415 if((c = getclient(ev->window))) {
416 if(ev->value_mask & CWBorderWidth)
417 c->bw = ev->border_width;
418 else if(c->isfloating || !lt[sellt]->arrange) {
419 if(ev->value_mask & CWX)
421 if(ev->value_mask & CWY)
423 if(ev->value_mask & CWWidth)
425 if(ev->value_mask & CWHeight)
427 if((c->x - sx + c->w) > sw && c->isfloating)
428 c->x = sx + (sw / 2 - c->w / 2); /* center in x direction */
429 if((c->y - sy + c->h) > sh && c->isfloating)
430 c->y = sy + (sh / 2 - c->h / 2); /* center in y direction */
431 if((ev->value_mask & (CWX|CWY)) && !(ev->value_mask & (CWWidth|CWHeight)))
434 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h);
442 wc.width = ev->width;
443 wc.height = ev->height;
444 wc.border_width = ev->border_width;
445 wc.sibling = ev->above;
446 wc.stack_mode = ev->detail;
447 XConfigureWindow(dpy, ev->window, ev->value_mask, &wc);
453 destroynotify(XEvent *e) {
455 XDestroyWindowEvent *ev = &e->xdestroywindow;
457 if((c = getclient(ev->window)))
465 for(tc = &clients; *tc && *tc != c; tc = &(*tc)->next);
470 detachstack(Client *c) {
473 for(tc = &stack; *tc && *tc != c; tc = &(*tc)->snext);
478 die(const char *errstr, ...) {
481 va_start(ap, errstr);
482 vfprintf(stderr, errstr, ap);
490 unsigned int i, occ = 0, urg = 0;
494 for(c = clients; c; c = c->next) {
501 for(i = 0; i < LENGTH(tags); i++) {
502 dc.w = TEXTW(tags[i]);
503 col = tagset[seltags] & 1 << i ? dc.sel : dc.norm;
504 drawtext(tags[i], col, urg & 1 << i);
505 drawsquare(sel && sel->tags & 1 << i, occ & 1 << i, urg & 1 << i, col);
510 drawtext(lt[sellt]->symbol, dc.norm, False);
521 drawtext(stext, dc.norm, False);
522 if((dc.w = dc.x - x) > bh) {
525 drawtext(sel->name, dc.sel, False);
526 drawsquare(sel->isfixed, sel->isfloating, False, dc.sel);
529 drawtext(NULL, dc.norm, False);
531 XCopyArea(dpy, dc.drawable, barwin, dc.gc, 0, 0, ww, bh, 0, 0);
536 drawsquare(Bool filled, Bool empty, Bool invert, unsigned long col[ColLast]) {
539 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
541 gcv.foreground = col[invert ? ColBG : ColFG];
542 XChangeGC(dpy, dc.gc, GCForeground, &gcv);
543 x = (dc.font.ascent + dc.font.descent + 2) / 4;
547 r.width = r.height = x + 1;
548 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
551 r.width = r.height = x;
552 XDrawRectangles(dpy, dc.drawable, dc.gc, &r, 1);
557 drawtext(const char *text, unsigned long col[ColLast], Bool invert) {
559 int i, x, y, h, len, olen;
560 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
562 XSetForeground(dpy, dc.gc, col[invert ? ColFG : ColBG]);
563 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
567 h = dc.font.ascent + dc.font.descent;
568 y = dc.y + (dc.h / 2) - (h / 2) + dc.font.ascent;
570 /* shorten text if necessary */
571 for(len = MIN(olen, sizeof buf); len && textnw(text, len) > dc.w - h; len--);
574 memcpy(buf, text, len);
576 for(i = len; i && i > len - 3; buf[--i] = '.');
577 XSetForeground(dpy, dc.gc, col[invert ? ColBG : ColFG]);
579 XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
581 XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
585 enternotify(XEvent *e) {
587 XCrossingEvent *ev = &e->xcrossing;
589 if((ev->mode != NotifyNormal || ev->detail == NotifyInferior) && ev->window != root)
591 if((c = getclient(ev->window)))
599 XExposeEvent *ev = &e->xexpose;
601 if(ev->count == 0 && (ev->window == barwin))
607 if(!c || !ISVISIBLE(c))
608 for(c = stack; c && !ISVISIBLE(c); c = c->snext);
609 if(sel && sel != c) {
610 grabbuttons(sel, False);
611 XSetWindowBorder(dpy, sel->win, dc.norm[ColBorder]);
618 grabbuttons(c, True);
619 XSetWindowBorder(dpy, c->win, dc.sel[ColBorder]);
620 XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
623 XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
629 focusin(XEvent *e) { /* there are some broken focus acquiring clients */
630 XFocusChangeEvent *ev = &e->xfocus;
632 if(sel && ev->window != sel->win)
633 XSetInputFocus(dpy, sel->win, RevertToPointerRoot, CurrentTime);
637 focusstack(const Arg *arg) {
638 Client *c = NULL, *i;
643 for(c = sel->next; c && !ISVISIBLE(c); c = c->next);
645 for(c = clients; c && !ISVISIBLE(c); c = c->next);
648 for(i = clients; i != sel; i = i->next)
652 for(; i; i = i->next)
663 getclient(Window w) {
666 for(c = clients; c && c->win != w; c = c->next);
671 getcolor(const char *colstr) {
672 Colormap cmap = DefaultColormap(dpy, screen);
675 if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
676 die("error, cannot allocate color '%s'\n", colstr);
684 unsigned char *p = NULL;
685 unsigned long n, extra;
688 status = XGetWindowProperty(dpy, w, wmatom[WMState], 0L, 2L, False, wmatom[WMState],
689 &real, &format, &n, &extra, (unsigned char **)&p);
690 if(status != Success)
699 gettextprop(Window w, Atom atom, char *text, unsigned int size) {
704 if(!text || size == 0)
707 XGetTextProperty(dpy, w, &name, atom);
710 if(name.encoding == XA_STRING)
711 strncpy(text, (char *)name.value, size - 1);
713 if(XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success
715 strncpy(text, *list, size - 1);
716 XFreeStringList(list);
719 text[size - 1] = '\0';
725 grabbuttons(Client *c, Bool focused) {
729 unsigned int modifiers[] = { 0, LockMask, numlockmask, numlockmask|LockMask };
730 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
732 for(i = 0; i < LENGTH(buttons); i++)
733 if(buttons[i].click == ClkClientWin)
734 for(j = 0; j < LENGTH(modifiers); j++)
735 XGrabButton(dpy, buttons[i].button, buttons[i].mask | modifiers[j], c->win, False, BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
737 XGrabButton(dpy, AnyButton, AnyModifier, c->win, False,
738 BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
747 unsigned int modifiers[] = { 0, LockMask, numlockmask, numlockmask|LockMask };
750 XUngrabKey(dpy, AnyKey, AnyModifier, root);
751 for(i = 0; i < LENGTH(keys); i++) {
752 if((code = XKeysymToKeycode(dpy, keys[i].keysym)))
753 for(j = 0; j < LENGTH(modifiers); j++)
754 XGrabKey(dpy, code, keys[i].mod | modifiers[j], root,
755 True, GrabModeAsync, GrabModeAsync);
761 initfont(const char *fontstr) {
762 char *def, **missing;
766 dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
769 fprintf(stderr, "dwm: missing fontset: %s\n", missing[n]);
770 XFreeStringList(missing);
773 XFontSetExtents *font_extents;
774 XFontStruct **xfonts;
776 dc.font.ascent = dc.font.descent = 0;
777 font_extents = XExtentsOfFontSet(dc.font.set);
778 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
779 for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
780 dc.font.ascent = MAX(dc.font.ascent, (*xfonts)->ascent);
781 dc.font.descent = MAX(dc.font.descent,(*xfonts)->descent);
786 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr))
787 && !(dc.font.xfont = XLoadQueryFont(dpy, "fixed")))
788 die("error, cannot load font: '%s'\n", fontstr);
789 dc.font.ascent = dc.font.xfont->ascent;
790 dc.font.descent = dc.font.xfont->descent;
792 dc.font.height = dc.font.ascent + dc.font.descent;
796 isprotodel(Client *c) {
801 if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
802 for(i = 0; !ret && i < n; i++)
803 if(protocols[i] == wmatom[WMDelete])
811 keypress(XEvent *e) {
817 keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
818 for(i = 0; i < LENGTH(keys); i++)
819 if(keysym == keys[i].keysym
820 && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state)
822 keys[i].func(&(keys[i].arg));
826 killclient(const Arg *arg) {
831 if(isprotodel(sel)) {
832 ev.type = ClientMessage;
833 ev.xclient.window = sel->win;
834 ev.xclient.message_type = wmatom[WMProtocols];
835 ev.xclient.format = 32;
836 ev.xclient.data.l[0] = wmatom[WMDelete];
837 ev.xclient.data.l[1] = CurrentTime;
838 XSendEvent(dpy, sel->win, False, NoEventMask, &ev);
841 XKillClient(dpy, sel->win);
845 manage(Window w, XWindowAttributes *wa) {
847 Client *c, *t = NULL;
851 if(!(c = malloc(sizeof(Client))))
852 die("fatal: could not malloc() %u bytes\n", sizeof(Client));
861 c->oldbw = wa->border_width;
862 if(c->w == sw && c->h == sh) {
868 if(c->x + WIDTH(c) > sx + sw)
869 c->x = sx + sw - WIDTH(c);
870 if(c->y + HEIGHT(c) > sy + sh)
871 c->y = sy + sh - HEIGHT(c);
872 c->x = MAX(c->x, sx);
873 /* only fix client y-offset, if the client center might cover the bar */
874 c->y = MAX(c->y, ((by == 0) && (c->x + (c->w / 2) >= wx) && (c->x + (c->w / 2) < wx + ww)) ? bh : sy);
878 wc.border_width = c->bw;
879 XConfigureWindow(dpy, w, CWBorderWidth, &wc);
880 XSetWindowBorder(dpy, w, dc.norm[ColBorder]);
881 configure(c); /* propagates border_width, if size doesn't change */
883 XSelectInput(dpy, w, EnterWindowMask|FocusChangeMask|PropertyChangeMask|StructureNotifyMask);
884 grabbuttons(c, False);
886 if(XGetTransientForHint(dpy, w, &trans))
887 t = getclient(trans);
893 c->isfloating = trans != None || c->isfixed;
895 XRaiseWindow(dpy, c->win);
898 XMoveResizeWindow(dpy, c->win, c->x + 2 * sw, c->y, c->w, c->h); /* some windows require this */
899 XMapWindow(dpy, c->win);
900 setclientstate(c, NormalState);
905 mappingnotify(XEvent *e) {
906 XMappingEvent *ev = &e->xmapping;
908 XRefreshKeyboardMapping(ev);
909 if(ev->request == MappingKeyboard)
914 maprequest(XEvent *e) {
915 static XWindowAttributes wa;
916 XMapRequestEvent *ev = &e->xmaprequest;
918 if(!XGetWindowAttributes(dpy, ev->window, &wa))
920 if(wa.override_redirect)
922 if(!getclient(ev->window))
923 manage(ev->window, &wa);
930 for(c = nexttiled(clients); c; c = nexttiled(c->next))
931 resize(c, wx, wy, ww - 2 * c->bw, wh - 2 * c->bw, resizehints);
935 movemouse(const Arg *arg) {
936 int x, y, ocx, ocy, di, nx, ny;
947 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
948 None, cursor[CurMove], CurrentTime) != GrabSuccess)
950 XQueryPointer(dpy, root, &dummy, &dummy, &x, &y, &di, &di, &dui);
954 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
956 case ConfigureRequest:
959 handler[ev.type](&ev);
962 nx = ocx + (ev.xmotion.x - x);
963 ny = ocy + (ev.xmotion.y - y);
964 if(snap && nx >= wx && nx <= wx + ww
965 && ny >= wy && ny <= wy + wh) {
966 if(abs(wx - nx) < snap)
968 else if(abs((wx + ww) - (nx + WIDTH(c))) < snap)
969 nx = wx + ww - WIDTH(c);
970 if(abs(wy - ny) < snap)
972 else if(abs((wy + wh) - (ny + HEIGHT(c))) < snap)
973 ny = wy + wh - HEIGHT(c);
974 if(!c->isfloating && lt[sellt]->arrange && (abs(nx - c->x) > snap || abs(ny - c->y) > snap))
975 togglefloating(NULL);
977 if(!lt[sellt]->arrange || c->isfloating)
978 resize(c, nx, ny, c->w, c->h, False);
982 while(ev.type != ButtonRelease);
985 XUngrabPointer(dpy, CurrentTime);
989 nexttiled(Client *c) {
990 for(; c && (c->isfloating || !ISVISIBLE(c)); c = c->next);
995 propertynotify(XEvent *e) {
998 XPropertyEvent *ev = &e->xproperty;
1000 if((ev->window == root) && (ev->atom = XA_WM_NAME))
1002 else if(ev->state == PropertyDelete)
1003 return; /* ignore */
1004 else if((c = getclient(ev->window))) {
1007 case XA_WM_TRANSIENT_FOR:
1008 XGetTransientForHint(dpy, c->win, &trans);
1009 if(!c->isfloating && (c->isfloating = (getclient(trans) != NULL)))
1012 case XA_WM_NORMAL_HINTS:
1020 if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
1029 quit(const Arg *arg) {
1034 resize(Client *c, int x, int y, int w, int h, Bool sizehints) {
1038 /* see last two sentences in ICCCM 4.1.2.3 */
1039 Bool baseismin = c->basew == c->minw && c->baseh == c->minh;
1041 /* set minimum possible */
1045 if(!baseismin) { /* temporarily remove base dimensions */
1050 /* adjust for aspect limits */
1051 if(c->mina > 0 && c->maxa > 0) {
1052 if(c->maxa < (float)w / h)
1054 else if(c->mina < (float)h / w)
1058 if(baseismin) { /* increment calculation requires this */
1063 /* adjust for increment value */
1069 /* restore base dimensions */
1073 w = MAX(w, c->minw);
1074 h = MAX(h, c->minh);
1077 w = MIN(w, c->maxw);
1080 h = MIN(h, c->maxh);
1082 if(w <= 0 || h <= 0)
1088 if(x + w + 2 * c->bw < sx)
1090 if(y + h + 2 * c->bw < sy)
1096 if(c->x != x || c->y != y || c->w != w || c->h != h) {
1099 c->w = wc.width = w;
1100 c->h = wc.height = h;
1101 wc.border_width = c->bw;
1102 XConfigureWindow(dpy, c->win,
1103 CWX|CWY|CWWidth|CWHeight|CWBorderWidth, &wc);
1110 resizemouse(const Arg *arg) {
1121 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1122 None, cursor[CurResize], CurrentTime) != GrabSuccess)
1124 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->bw - 1, c->h + c->bw - 1);
1128 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
1130 case ConfigureRequest:
1133 handler[ev.type](&ev);
1136 nw = MAX(ev.xmotion.x - ocx - 2*c->bw + 1, 1);
1137 nh = MAX(ev.xmotion.y - ocy - 2*c->bw + 1, 1);
1139 if(snap && nw >= wx && nw <= wx + ww
1140 && nh >= wy && nh <= wy + wh) {
1141 if(!c->isfloating && lt[sellt]->arrange
1142 && (abs(nw - c->w) > snap || abs(nh - c->h) > snap))
1143 togglefloating(NULL);
1145 if(!lt[sellt]->arrange || c->isfloating)
1146 resize(c, c->x, c->y, nw, nh, True);
1150 while(ev.type != ButtonRelease);
1153 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->bw - 1, c->h + c->bw - 1);
1154 XUngrabPointer(dpy, CurrentTime);
1155 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1167 if(sel->isfloating || !lt[sellt]->arrange)
1168 XRaiseWindow(dpy, sel->win);
1169 if(lt[sellt]->arrange) {
1170 wc.stack_mode = Below;
1171 wc.sibling = barwin;
1172 for(c = stack; c; c = c->snext)
1173 if(!c->isfloating && ISVISIBLE(c)) {
1174 XConfigureWindow(dpy, c->win, CWSibling|CWStackMode, &wc);
1175 wc.sibling = c->win;
1179 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1186 /* main event loop */
1188 while(running && !XNextEvent(dpy, &ev)) {
1189 if(handler[ev.type])
1190 (handler[ev.type])(&ev); /* call handler */
1196 unsigned int i, num;
1197 Window d1, d2, *wins = NULL;
1198 XWindowAttributes wa;
1200 if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1201 for(i = 0; i < num; i++) {
1202 if(!XGetWindowAttributes(dpy, wins[i], &wa)
1203 || wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1205 if(wa.map_state == IsViewable || getstate(wins[i]) == IconicState)
1206 manage(wins[i], &wa);
1208 for(i = 0; i < num; i++) { /* now the transients */
1209 if(!XGetWindowAttributes(dpy, wins[i], &wa))
1211 if(XGetTransientForHint(dpy, wins[i], &d1)
1212 && (wa.map_state == IsViewable || getstate(wins[i]) == IconicState))
1213 manage(wins[i], &wa);
1221 setclientstate(Client *c, long state) {
1222 long data[] = {state, None};
1224 XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1225 PropModeReplace, (unsigned char *)data, 2);
1229 setlayout(const Arg *arg) {
1230 if(!arg || !arg->v || arg->v != lt[sellt])
1233 lt[sellt] = (Layout *)arg->v;
1240 /* arg > 1.0 will set mfact absolutly */
1242 setmfact(const Arg *arg) {
1245 if(!arg || !lt[sellt]->arrange)
1247 f = arg->f < 1.0 ? arg->f + mfact : arg->f - 1.0;
1248 if(f < 0.1 || f > 0.9)
1258 XSetWindowAttributes wa;
1261 screen = DefaultScreen(dpy);
1262 root = RootWindow(dpy, screen);
1266 sw = DisplayWidth(dpy, screen);
1267 sh = DisplayHeight(dpy, screen);
1268 bh = dc.h = dc.font.height + 2;
1269 lt[0] = &layouts[0];
1270 lt[1] = &layouts[1 % LENGTH(layouts)];
1274 wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1275 wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1276 wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1277 netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1278 netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1281 wa.cursor = cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1282 cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1283 cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1285 /* init appearance */
1286 dc.norm[ColBorder] = getcolor(normbordercolor);
1287 dc.norm[ColBG] = getcolor(normbgcolor);
1288 dc.norm[ColFG] = getcolor(normfgcolor);
1289 dc.sel[ColBorder] = getcolor(selbordercolor);
1290 dc.sel[ColBG] = getcolor(selbgcolor);
1291 dc.sel[ColFG] = getcolor(selfgcolor);
1292 dc.drawable = XCreatePixmap(dpy, root, DisplayWidth(dpy, screen), bh, DefaultDepth(dpy, screen));
1293 dc.gc = XCreateGC(dpy, root, 0, 0);
1294 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
1296 XSetFont(dpy, dc.gc, dc.font.xfont->fid);
1299 for(blw = i = 0; LENGTH(layouts) > 1 && i < LENGTH(layouts); i++) {
1300 w = TEXTW(layouts[i].symbol);
1304 wa.override_redirect = 1;
1305 wa.background_pixmap = ParentRelative;
1306 wa.event_mask = ButtonPressMask|ExposureMask;
1308 barwin = XCreateWindow(dpy, root, wx, by, ww, bh, 0, DefaultDepth(dpy, screen),
1309 CopyFromParent, DefaultVisual(dpy, screen),
1310 CWOverrideRedirect|CWBackPixmap|CWEventMask, &wa);
1311 XDefineCursor(dpy, barwin, cursor[CurNormal]);
1312 XMapRaised(dpy, barwin);
1315 /* EWMH support per view */
1316 XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1317 PropModeReplace, (unsigned char *) netatom, NetLast);
1319 /* select for events */
1320 wa.event_mask = SubstructureRedirectMask|SubstructureNotifyMask|ButtonPressMask
1321 |EnterWindowMask|LeaveWindowMask|StructureNotifyMask
1322 |PropertyChangeMask;
1323 XChangeWindowAttributes(dpy, root, CWEventMask|CWCursor, &wa);
1324 XSelectInput(dpy, root, wa.event_mask);
1330 showhide(Client *c) {
1333 if(ISVISIBLE(c)) { /* show clients top down */
1334 XMoveWindow(dpy, c->win, c->x, c->y);
1335 if(!lt[sellt]->arrange || c->isfloating)
1336 resize(c, c->x, c->y, c->w, c->h, True);
1339 else { /* hide clients bottom up */
1341 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
1347 sigchld(int signal) {
1348 while(0 < waitpid(-1, NULL, WNOHANG));
1352 spawn(const Arg *arg) {
1353 signal(SIGCHLD, sigchld);
1356 close(ConnectionNumber(dpy));
1358 execvp(((char **)arg->v)[0], (char **)arg->v);
1359 fprintf(stderr, "dwm: execvp %s", ((char **)arg->v)[0]);
1366 tag(const Arg *arg) {
1367 if(sel && arg->ui & TAGMASK) {
1368 sel->tags = arg->ui & TAGMASK;
1374 textnw(const char *text, unsigned int len) {
1378 XmbTextExtents(dc.font.set, text, len, NULL, &r);
1381 return XTextWidth(dc.font.xfont, text, len);
1390 for(n = 0, c = nexttiled(clients); c; c = nexttiled(c->next), n++);
1395 c = nexttiled(clients);
1397 resize(c, wx, wy, (n == 1 ? ww : mw) - 2 * c->bw, wh - 2 * c->bw, resizehints);
1403 x = (wx + mw > c->x + c->w) ? c->x + c->w + 2 * c->bw : wx + mw;
1405 w = (wx + mw > c->x + c->w) ? wx + ww - x : ww - mw;
1410 for(i = 0, c = nexttiled(c->next); c; c = nexttiled(c->next), i++) {
1411 resize(c, x, y, w - 2 * c->bw, /* remainder */ ((i + 1 == n)
1412 ? wy + wh - y - 2 * c->bw : h - 2 * c->bw), resizehints);
1414 y = c->y + HEIGHT(c);
1419 togglebar(const Arg *arg) {
1427 togglefloating(const Arg *arg) {
1430 sel->isfloating = !sel->isfloating || sel->isfixed;
1432 resize(sel, sel->x, sel->y, sel->w, sel->h, True);
1437 toggletag(const Arg *arg) {
1443 mask = sel->tags ^ (arg->ui & TAGMASK);
1451 toggleview(const Arg *arg) {
1452 unsigned int mask = tagset[seltags] ^ (arg->ui & TAGMASK);
1455 tagset[seltags] = mask;
1461 unmanage(Client *c) {
1464 wc.border_width = c->oldbw;
1465 /* The server grab construct avoids race conditions. */
1467 XSetErrorHandler(xerrordummy);
1468 XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
1473 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1474 setclientstate(c, WithdrawnState);
1477 XSetErrorHandler(xerror);
1483 unmapnotify(XEvent *e) {
1485 XUnmapEvent *ev = &e->xunmap;
1487 if((c = getclient(ev->window)))
1493 if(dc.drawable != 0)
1494 XFreePixmap(dpy, dc.drawable);
1495 dc.drawable = XCreatePixmap(dpy, root, ww, bh, DefaultDepth(dpy, screen));
1496 XMoveResizeWindow(dpy, barwin, wx, by, ww, bh);
1503 XineramaScreenInfo *info = NULL;
1505 /* window area geometry */
1506 if(XineramaIsActive(dpy) && (info = XineramaQueryScreens(dpy, &n))) {
1511 if(XQueryPointer(dpy, root, &dummy, &dummy, &x, &y, &di, &di, &dui))
1512 for(i = 0; i < n; i++)
1513 if(INRECT(x, y, info[i].x_org, info[i].y_org, info[i].width, info[i].height))
1517 wy = showbar && topbar ? info[i].y_org + bh : info[i].y_org;
1519 wh = showbar ? info[i].height - bh : info[i].height;
1526 wy = showbar && topbar ? sy + bh : sy;
1528 wh = showbar ? sh - bh : sh;
1532 by = showbar ? (topbar ? wy - bh : wy + wh) : -bh;
1536 updatenumlockmask(void) {
1538 XModifierKeymap *modmap;
1541 modmap = XGetModifierMapping(dpy);
1542 for(i = 0; i < 8; i++)
1543 for(j = 0; j < modmap->max_keypermod; j++)
1544 if(modmap->modifiermap[i * modmap->max_keypermod + j] == XKeysymToKeycode(dpy, XK_Num_Lock))
1545 numlockmask = (1 << i);
1546 XFreeModifiermap(modmap);
1550 updatesizehints(Client *c) {
1554 if(!XGetWMNormalHints(dpy, c->win, &size, &msize))
1555 /* size is uninitialized, ensure that size.flags aren't used */
1557 if(size.flags & PBaseSize) {
1558 c->basew = size.base_width;
1559 c->baseh = size.base_height;
1561 else if(size.flags & PMinSize) {
1562 c->basew = size.min_width;
1563 c->baseh = size.min_height;
1566 c->basew = c->baseh = 0;
1567 if(size.flags & PResizeInc) {
1568 c->incw = size.width_inc;
1569 c->inch = size.height_inc;
1572 c->incw = c->inch = 0;
1573 if(size.flags & PMaxSize) {
1574 c->maxw = size.max_width;
1575 c->maxh = size.max_height;
1578 c->maxw = c->maxh = 0;
1579 if(size.flags & PMinSize) {
1580 c->minw = size.min_width;
1581 c->minh = size.min_height;
1583 else if(size.flags & PBaseSize) {
1584 c->minw = size.base_width;
1585 c->minh = size.base_height;
1588 c->minw = c->minh = 0;
1589 if(size.flags & PAspect) {
1590 c->mina = (float)size.min_aspect.y / (float)size.min_aspect.x;
1591 c->maxa = (float)size.max_aspect.x / (float)size.max_aspect.y;
1594 c->maxa = c->mina = 0.0;
1595 c->isfixed = (c->maxw && c->minw && c->maxh && c->minh
1596 && c->maxw == c->minw && c->maxh == c->minh);
1600 updatetitle(Client *c) {
1601 if(!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
1602 gettextprop(c->win, XA_WM_NAME, c->name, sizeof c->name);
1607 if(!gettextprop(root, XA_WM_NAME, stext, sizeof(stext)))
1608 strcpy(stext, "dwm-"VERSION);
1613 updatewmhints(Client *c) {
1616 if((wmh = XGetWMHints(dpy, c->win))) {
1617 if(c == sel && wmh->flags & XUrgencyHint) {
1618 wmh->flags &= ~XUrgencyHint;
1619 XSetWMHints(dpy, c->win, wmh);
1622 c->isurgent = (wmh->flags & XUrgencyHint) ? True : False;
1629 view(const Arg *arg) {
1630 if((arg->ui & TAGMASK) == tagset[seltags])
1632 seltags ^= 1; /* toggle sel tagset */
1633 if(arg->ui & TAGMASK)
1634 tagset[seltags] = arg->ui & TAGMASK;
1638 /* There's no way to check accesses to destroyed windows, thus those cases are
1639 * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
1640 * default error handler, which may call exit. */
1642 xerror(Display *dpy, XErrorEvent *ee) {
1643 if(ee->error_code == BadWindow
1644 || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1645 || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1646 || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1647 || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1648 || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1649 || (ee->request_code == X_GrabButton && ee->error_code == BadAccess)
1650 || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1651 || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1653 fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1654 ee->request_code, ee->error_code);
1655 return xerrorxlib(dpy, ee); /* may call exit */
1659 xerrordummy(Display *dpy, XErrorEvent *ee) {
1663 /* Startup Error handler to check if another window manager
1664 * is already running. */
1666 xerrorstart(Display *dpy, XErrorEvent *ee) {
1672 zoom(const Arg *arg) {
1675 if(!lt[sellt]->arrange || lt[sellt]->arrange == monocle || (sel && sel->isfloating))
1677 if(c == nexttiled(clients))
1678 if(!c || !(c = nexttiled(c->next)))
1687 main(int argc, char *argv[]) {
1688 if(argc == 2 && !strcmp("-v", argv[1]))
1689 die("dwm-"VERSION", © 2006-2008 dwm engineers, see LICENSE for details\n");
1691 die("usage: dwm [-v]\n");
1693 if(!setlocale(LC_CTYPE, "") || !XSupportsLocale())
1694 fprintf(stderr, "warning: no locale support\n");
1696 if(!(dpy = XOpenDisplay(0)))
1697 die("dwm: cannot open display\n");