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 * Calls to fetch an X event from the event queue are blocking. Due reading
10 * status text from standard input, a select()-driven main loop has been
11 * implemented which selects for reads on the X connection and STDIN_FILENO to
12 * handle all data smoothly. The event handlers of dwm are organized in an
13 * array which is accessed whenever a new event has been fetched. This allows
14 * event dispatching in O(1) time.
16 * Each child of the root window is called a client, except windows which have
17 * set the override_redirect flag. Clients are organized in a global
18 * doubly-linked client list, the focus history is remembered through a global
19 * stack list. Each client contains a bit array to indicate the tags of a
22 * Keys and tagging rules are organized as arrays and defined in config.h.
24 * To understand everything else, start reading main().
33 #include <sys/select.h>
34 #include <sys/types.h>
36 #include <X11/cursorfont.h>
37 #include <X11/keysym.h>
38 #include <X11/Xatom.h>
40 #include <X11/Xproto.h>
41 #include <X11/Xutil.h>
43 #include <X11/extensions/Xinerama.h>
47 #define MAX(a, b) ((a) > (b) ? (a) : (b))
48 #define MIN(a, b) ((a) < (b) ? (a) : (b))
49 #define BUTTONMASK (ButtonPressMask|ButtonReleaseMask)
50 #define CLEANMASK(mask) (mask & ~(numlockmask|LockMask))
51 #define LENGTH(x) (sizeof x / sizeof x[0])
53 #define MOUSEMASK (BUTTONMASK|PointerMotionMask)
54 #define TAGMASK ((int)((1LL << LENGTH(tags)) - 1))
55 #define TEXTW(x) (textnw(x, strlen(x)) + dc.font.height)
56 #define ISVISIBLE(x) (x->tags & tagset[seltags])
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, WMName, WMState, WMLast };/* default atoms */
63 enum { ClkTagBar, ClkLtSymbol, ClkStatusText, ClkWinTitle,
64 ClkClientWin, ClkRootWin, ClkLast }; /* clicks */
67 typedef unsigned int uint;
68 typedef unsigned long ulong;
81 void (*func)(const Arg *arg);
85 typedef struct Client Client;
90 int basew, baseh, incw, inch, maxw, maxh, minw, minh;
93 Bool isfixed, isfloating, isurgent;
112 } DC; /* draw context */
117 void (*func)(const Arg *);
123 void (*arrange)(void);
128 const char *instance;
134 /* function declarations */
135 static void applyrules(Client *c);
136 static void arrange(void);
137 static void attach(Client *c);
138 static void attachstack(Client *c);
139 static void buttonpress(XEvent *e);
140 static void checkotherwm(void);
141 static void cleanup(void);
142 static void configure(Client *c);
143 static void configurenotify(XEvent *e);
144 static void configurerequest(XEvent *e);
145 static void destroynotify(XEvent *e);
146 static void detach(Client *c);
147 static void detachstack(Client *c);
148 static void drawbar(void);
149 static void drawsquare(Bool filled, Bool empty, Bool invert, ulong col[ColLast]);
150 static void drawtext(const char *text, ulong col[ColLast], Bool invert);
151 static void enternotify(XEvent *e);
152 static void eprint(const char *errstr, ...);
153 static void expose(XEvent *e);
154 static void focus(Client *c);
155 static void focusin(XEvent *e);
156 static void focusstack(const Arg *arg);
157 static Client *getclient(Window w);
158 static ulong getcolor(const char *colstr);
159 static long getstate(Window w);
160 static Bool gettextprop(Window w, Atom atom, char *text, uint size);
161 static void grabbuttons(Client *c, Bool focused);
162 static void grabkeys(void);
163 static void initfont(const char *fontstr);
164 static Bool isoccupied(uint t);
165 static Bool isprotodel(Client *c);
166 static Bool isurgent(uint t);
167 static void keypress(XEvent *e);
168 static void killclient(const Arg *arg);
169 static void manage(Window w, XWindowAttributes *wa);
170 static void mappingnotify(XEvent *e);
171 static void maprequest(XEvent *e);
172 static void monocle(void);
173 static void movemouse(const Arg *arg);
174 static Client *nexttiled(Client *c);
175 static void propertynotify(XEvent *e);
176 static void quit(const Arg *arg);
177 static void resize(Client *c, int x, int y, int w, int h, Bool sizehints);
178 static void resizemouse(const Arg *arg);
179 static void restack(void);
180 static void run(void);
181 static void scan(void);
182 static void setclientstate(Client *c, long state);
183 static void setlayout(const Arg *arg);
184 static void setmfact(const Arg *arg);
185 static void setup(void);
186 static void spawn(const Arg *arg);
187 static void tag(const Arg *arg);
188 static int textnw(const char *text, uint len);
189 static void tile(void);
190 static void togglebar(const Arg *arg);
191 static void togglefloating(const Arg *arg);
192 static void toggletag(const Arg *arg);
193 static void toggleview(const Arg *arg);
194 static void unmanage(Client *c);
195 static void unmapnotify(XEvent *e);
196 static void updatebar(void);
197 static void updategeom(void);
198 static void updatesizehints(Client *c);
199 static void updatetitle(Client *c);
200 static void updatewmhints(Client *c);
201 static void view(const Arg *arg);
202 static int xerror(Display *dpy, XErrorEvent *ee);
203 static int xerrordummy(Display *dpy, XErrorEvent *ee);
204 static int xerrorstart(Display *dpy, XErrorEvent *ee);
205 static void zoom(const Arg *arg);
208 static char stext[256];
209 static int screen, sx, sy, sw, sh;
210 static int by, bh, blw, wx, wy, ww, wh;
211 static uint seltags = 0, sellt = 0;
212 static int (*xerrorxlib)(Display *, XErrorEvent *);
213 static uint numlockmask = 0;
214 static void (*handler[LASTEvent]) (XEvent *) = {
215 [ButtonPress] = buttonpress,
216 [ConfigureRequest] = configurerequest,
217 [ConfigureNotify] = configurenotify,
218 [DestroyNotify] = destroynotify,
219 [EnterNotify] = enternotify,
222 [KeyPress] = keypress,
223 [MappingNotify] = mappingnotify,
224 [MapRequest] = maprequest,
225 [PropertyNotify] = propertynotify,
226 [UnmapNotify] = unmapnotify
228 static Atom wmatom[WMLast], netatom[NetLast];
229 static Bool otherwm, readin;
230 static Bool running = True;
231 static uint tagset[] = {1, 1}; /* after start, first tag is selected */
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 uint bit array. */
244 struct NumTags { char limitexceeded[sizeof(uint) * 8 < LENGTH(tags) ? -1 : 1]; };
246 /* function implementations */
248 applyrules(Client *c) {
251 XClassHint ch = { 0 };
254 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;
269 c->tags = tagset[seltags];
276 for(c = clients; c; c = c->next)
278 XMoveWindow(dpy, c->win, c->x, c->y);
279 if(!lt[sellt]->arrange || c->isfloating)
280 resize(c, c->x, c->y, c->w, c->h, True);
283 XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
287 if(lt[sellt]->arrange)
288 lt[sellt]->arrange();
299 attachstack(Client *c) {
305 buttonpress(XEvent *e) {
309 XButtonPressedEvent *ev = &e->xbutton;
312 if(ev->window == barwin) {
314 do x += TEXTW(tags[i]); while(ev->x >= x && ++i < LENGTH(tags));
315 if(i < LENGTH(tags)) {
319 else if(ev->x < x + blw)
321 else if(ev->x > wx + ww - TEXTW(stext))
322 click = ClkStatusText;
326 else if((c = getclient(ev->window))) {
328 click = ClkClientWin;
331 for(i = 0; i < LENGTH(buttons); i++)
332 if(click == buttons[i].click && buttons[i].func && buttons[i].button == ev->button
333 && CLEANMASK(buttons[i].mask) == CLEANMASK(ev->state))
334 buttons[i].func(click == ClkTagBar ? &arg : &buttons[i].arg);
340 XSetErrorHandler(xerrorstart);
342 /* this causes an error if some other window manager is running */
343 XSelectInput(dpy, DefaultRootWindow(dpy), SubstructureRedirectMask);
346 eprint("dwm: another window manager is already running\n");
347 XSetErrorHandler(NULL);
348 xerrorxlib = XSetErrorHandler(xerror);
355 Layout foo = { "", NULL };
363 XFreeFontSet(dpy, dc.font.set);
365 XFreeFont(dpy, dc.font.xfont);
366 XUngrabKey(dpy, AnyKey, AnyModifier, root);
367 XFreePixmap(dpy, dc.drawable);
369 XFreeCursor(dpy, cursor[CurNormal]);
370 XFreeCursor(dpy, cursor[CurResize]);
371 XFreeCursor(dpy, cursor[CurMove]);
372 XDestroyWindow(dpy, barwin);
374 XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime);
378 configure(Client *c) {
381 ce.type = ConfigureNotify;
389 ce.border_width = c->bw;
391 ce.override_redirect = False;
392 XSendEvent(dpy, c->win, False, StructureNotifyMask, (XEvent *)&ce);
396 configurenotify(XEvent *e) {
397 XConfigureEvent *ev = &e->xconfigure;
399 if(ev->window == root && (ev->width != sw || ev->height != sh)) {
409 configurerequest(XEvent *e) {
411 XConfigureRequestEvent *ev = &e->xconfigurerequest;
414 if((c = getclient(ev->window))) {
415 if(ev->value_mask & CWBorderWidth)
416 c->bw = ev->border_width;
417 else if(c->isfloating || !lt[sellt]->arrange) {
418 if(ev->value_mask & CWX)
420 if(ev->value_mask & CWY)
422 if(ev->value_mask & CWWidth)
424 if(ev->value_mask & CWHeight)
426 if((c->x - sx + c->w) > sw && c->isfloating)
427 c->x = sx + (sw / 2 - c->w / 2); /* center in x direction */
428 if((c->y - sy + c->h) > sh && c->isfloating)
429 c->y = sy + (sh / 2 - c->h / 2); /* center in y direction */
430 if((ev->value_mask & (CWX|CWY)) && !(ev->value_mask & (CWWidth|CWHeight)))
433 XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h);
441 wc.width = ev->width;
442 wc.height = ev->height;
443 wc.border_width = ev->border_width;
444 wc.sibling = ev->above;
445 wc.stack_mode = ev->detail;
446 XConfigureWindow(dpy, ev->window, ev->value_mask, &wc);
452 destroynotify(XEvent *e) {
454 XDestroyWindowEvent *ev = &e->xdestroywindow;
456 if((c = getclient(ev->window)))
464 for(tc = &clients; *tc && *tc != c; tc = &(*tc)->next);
469 detachstack(Client *c) {
472 for(tc = &stack; *tc && *tc != c; tc = &(*tc)->snext);
481 for(i = 0; i < LENGTH(tags); i++) {
482 dc.w = TEXTW(tags[i]);
483 if(tagset[seltags] & 1 << i) {
484 drawtext(tags[i], dc.sel, isurgent(i));
485 drawsquare(sel && sel->tags & 1 << i, isoccupied(i), isurgent(i), dc.sel);
488 drawtext(tags[i], dc.norm, isurgent(i));
489 drawsquare(sel && sel->tags & 1 << i, isoccupied(i), isurgent(i), dc.norm);
495 drawtext(lt[sellt]->symbol, dc.norm, False);
506 drawtext(stext, dc.norm, False);
507 if((dc.w = dc.x - x) > bh) {
510 drawtext(sel->name, dc.sel, False);
511 drawsquare(sel->isfixed, sel->isfloating, False, dc.sel);
514 drawtext(NULL, dc.norm, False);
516 XCopyArea(dpy, dc.drawable, barwin, dc.gc, 0, 0, ww, bh, 0, 0);
521 drawsquare(Bool filled, Bool empty, Bool invert, ulong col[ColLast]) {
524 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
526 gcv.foreground = col[invert ? ColBG : ColFG];
527 XChangeGC(dpy, dc.gc, GCForeground, &gcv);
528 x = (dc.font.ascent + dc.font.descent + 2) / 4;
532 r.width = r.height = x + 1;
533 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
536 r.width = r.height = x;
537 XDrawRectangles(dpy, dc.drawable, dc.gc, &r, 1);
542 drawtext(const char *text, ulong col[ColLast], Bool invert) {
543 int i, x, y, h, len, olen;
544 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
547 XSetForeground(dpy, dc.gc, col[invert ? ColFG : ColBG]);
548 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
552 len = MIN(olen, sizeof buf);
553 memcpy(buf, text, len);
554 h = dc.font.ascent + dc.font.descent;
555 y = dc.y + (dc.h / 2) - (h / 2) + dc.font.ascent;
557 /* shorten text if necessary */
558 for(; len && (i = textnw(buf, len)) > dc.w - h; len--);
562 for(i = len; i && i > len - 3; buf[--i] = '.');
563 XSetForeground(dpy, dc.gc, col[invert ? ColBG : ColFG]);
565 XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
567 XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
571 enternotify(XEvent *e) {
573 XCrossingEvent *ev = &e->xcrossing;
575 if((ev->mode != NotifyNormal || ev->detail == NotifyInferior) && ev->window != root)
577 if((c = getclient(ev->window)))
584 eprint(const char *errstr, ...) {
587 va_start(ap, errstr);
588 vfprintf(stderr, errstr, ap);
595 XExposeEvent *ev = &e->xexpose;
597 if(ev->count == 0 && (ev->window == barwin))
603 if(!c || !ISVISIBLE(c))
604 for(c = stack; c && !ISVISIBLE(c); c = c->snext);
605 if(sel && sel != c) {
606 grabbuttons(sel, False);
607 XSetWindowBorder(dpy, sel->win, dc.norm[ColBorder]);
612 grabbuttons(c, True);
613 XSetWindowBorder(dpy, c->win, dc.sel[ColBorder]);
614 XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
617 XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
623 focusin(XEvent *e) { /* there are some broken focus acquiring clients */
624 XFocusChangeEvent *ev = &e->xfocus;
626 if(sel && ev->window != sel->win)
627 XSetInputFocus(dpy, sel->win, RevertToPointerRoot, CurrentTime);
631 focusstack(const Arg *arg) {
632 Client *c = NULL, *i;
637 for(c = sel->next; c && !ISVISIBLE(c); c = c->next);
639 for(c = clients; c && !ISVISIBLE(c); c = c->next);
642 for(i = clients; i != sel; i = i->next)
646 for(; i; i = i->next)
657 getclient(Window w) {
660 for(c = clients; c && c->win != w; c = c->next);
665 getcolor(const char *colstr) {
666 Colormap cmap = DefaultColormap(dpy, screen);
669 if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
670 eprint("error, cannot allocate color '%s'\n", colstr);
678 unsigned char *p = NULL;
682 status = XGetWindowProperty(dpy, w, wmatom[WMState], 0L, 2L, False, wmatom[WMState],
683 &real, &format, &n, &extra, (unsigned char **)&p);
684 if(status != Success)
693 gettextprop(Window w, Atom atom, char *text, uint size) {
698 if(!text || size == 0)
701 XGetTextProperty(dpy, w, &name, atom);
704 if(name.encoding == XA_STRING)
705 strncpy(text, (char *)name.value, size - 1);
707 if(XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success
709 strncpy(text, *list, size - 1);
710 XFreeStringList(list);
713 text[size - 1] = '\0';
719 grabbuttons(Client *c, Bool focused) {
721 uint modifiers[] = { 0, LockMask, numlockmask, numlockmask|LockMask };
723 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
725 for(i = 0; i < LENGTH(buttons); i++)
726 if(buttons[i].click == ClkClientWin)
727 for(j = 0; j < LENGTH(modifiers); j++)
728 XGrabButton(dpy, buttons[i].button, buttons[i].mask | modifiers[j], c->win, False, BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
730 XGrabButton(dpy, AnyButton, AnyModifier, c->win, False,
731 BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
738 XModifierKeymap *modmap;
740 /* init modifier map */
741 modmap = XGetModifierMapping(dpy);
742 for(i = 0; i < 8; i++)
743 for(j = 0; j < modmap->max_keypermod; j++) {
744 if(modmap->modifiermap[i * modmap->max_keypermod + j] == XKeysymToKeycode(dpy, XK_Num_Lock))
745 numlockmask = (1 << i);
747 XFreeModifiermap(modmap);
749 XUngrabKey(dpy, AnyKey, AnyModifier, root);
750 for(i = 0; i < LENGTH(keys); i++) {
751 code = XKeysymToKeycode(dpy, keys[i].keysym);
752 XGrabKey(dpy, code, keys[i].mod, root, True,
753 GrabModeAsync, GrabModeAsync);
754 XGrabKey(dpy, code, keys[i].mod|LockMask, root, True,
755 GrabModeAsync, GrabModeAsync);
756 XGrabKey(dpy, code, keys[i].mod|numlockmask, root, True,
757 GrabModeAsync, GrabModeAsync);
758 XGrabKey(dpy, code, keys[i].mod|numlockmask|LockMask, root, True,
759 GrabModeAsync, GrabModeAsync);
764 initfont(const char *fontstr) {
765 char *def, **missing;
770 XFreeFontSet(dpy, dc.font.set);
771 dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
774 fprintf(stderr, "dwm: missing fontset: %s\n", missing[n]);
775 XFreeStringList(missing);
778 XFontSetExtents *font_extents;
779 XFontStruct **xfonts;
781 dc.font.ascent = dc.font.descent = 0;
782 font_extents = XExtentsOfFontSet(dc.font.set);
783 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
784 for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
785 dc.font.ascent = MAX(dc.font.ascent, (*xfonts)->ascent);
786 dc.font.descent = MAX(dc.font.descent,(*xfonts)->descent);
792 XFreeFont(dpy, dc.font.xfont);
793 dc.font.xfont = NULL;
794 if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr))
795 && !(dc.font.xfont = XLoadQueryFont(dpy, "fixed")))
796 eprint("error, cannot load font: '%s'\n", fontstr);
797 dc.font.ascent = dc.font.xfont->ascent;
798 dc.font.descent = dc.font.xfont->descent;
800 dc.font.height = dc.font.ascent + dc.font.descent;
807 for(c = clients; c; c = c->next)
814 isprotodel(Client *c) {
819 if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
820 for(i = 0; !ret && i < n; i++)
821 if(protocols[i] == wmatom[WMDelete])
832 for(c = clients; c; c = c->next)
833 if(c->isurgent && c->tags & 1 << t)
839 keypress(XEvent *e) {
845 keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
846 for(i = 0; i < LENGTH(keys); i++)
847 if(keysym == keys[i].keysym
848 && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state)
850 keys[i].func(&(keys[i].arg));
854 killclient(const Arg *arg) {
859 if(isprotodel(sel)) {
860 ev.type = ClientMessage;
861 ev.xclient.window = sel->win;
862 ev.xclient.message_type = wmatom[WMProtocols];
863 ev.xclient.format = 32;
864 ev.xclient.data.l[0] = wmatom[WMDelete];
865 ev.xclient.data.l[1] = CurrentTime;
866 XSendEvent(dpy, sel->win, False, NoEventMask, &ev);
869 XKillClient(dpy, sel->win);
873 manage(Window w, XWindowAttributes *wa) {
874 Client *c, *t = NULL;
879 if(!(c = calloc(1, sizeof(Client))))
880 eprint("fatal: could not calloc() %u bytes\n", sizeof(Client));
888 c->oldbw = wa->border_width;
889 if(c->w == sw && c->h == sh) {
892 c->bw = wa->border_width;
895 if(c->x + c->w + 2 * c->bw > sx + sw)
896 c->x = sx + sw - c->w - 2 * c->bw;
897 if(c->y + c->h + 2 * c->bw > sy + sh)
898 c->y = sy + sh - c->h - 2 * c->bw;
899 c->x = MAX(c->x, sx);
900 /* only fix client y-offset, if the client center might cover the bar */
901 c->y = MAX(c->y, ((by == 0) && (c->x + (c->w / 2) >= wx) && (c->x + (c->w / 2) < wx + ww)) ? bh : sy);
905 wc.border_width = c->bw;
906 XConfigureWindow(dpy, w, CWBorderWidth, &wc);
907 XSetWindowBorder(dpy, w, dc.norm[ColBorder]);
908 configure(c); /* propagates border_width, if size doesn't change */
910 XSelectInput(dpy, w, EnterWindowMask|FocusChangeMask|PropertyChangeMask|StructureNotifyMask);
911 grabbuttons(c, False);
913 if((rettrans = XGetTransientForHint(dpy, w, &trans) == Success))
914 for(t = clients; t && t->win != trans; t = t->next);
920 c->isfloating = (rettrans == Success) || c->isfixed;
922 XRaiseWindow(dpy, c->win);
925 XMoveResizeWindow(dpy, c->win, c->x + 2 * sw, c->y, c->w, c->h); /* some windows require this */
926 XMapWindow(dpy, c->win);
927 setclientstate(c, NormalState);
932 mappingnotify(XEvent *e) {
933 XMappingEvent *ev = &e->xmapping;
935 XRefreshKeyboardMapping(ev);
936 if(ev->request == MappingKeyboard)
941 maprequest(XEvent *e) {
942 static XWindowAttributes wa;
943 XMapRequestEvent *ev = &e->xmaprequest;
945 if(!XGetWindowAttributes(dpy, ev->window, &wa))
947 if(wa.override_redirect)
949 if(!getclient(ev->window))
950 manage(ev->window, &wa);
957 for(c = nexttiled(clients); c; c = nexttiled(c->next))
958 resize(c, wx, wy, ww - 2 * c->bw, wh - 2 * c->bw, resizehints);
962 movemouse(const Arg *arg) {
963 int x1, y1, ocx, ocy, di, nx, ny;
974 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
975 None, cursor[CurMove], CurrentTime) != GrabSuccess)
977 XQueryPointer(dpy, root, &dummy, &dummy, &x1, &y1, &di, &di, &dui);
979 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
982 XUngrabPointer(dpy, CurrentTime);
984 case ConfigureRequest:
987 handler[ev.type](&ev);
991 nx = ocx + (ev.xmotion.x - x1);
992 ny = ocy + (ev.xmotion.y - y1);
993 if(snap && nx >= wx && nx <= wx + ww
994 && ny >= wy && ny <= wy + wh) {
995 if(abs(wx - nx) < snap)
997 else if(abs((wx + ww) - (nx + c->w + 2 * c->bw)) < snap)
998 nx = wx + ww - c->w - 2 * c->bw;
999 if(abs(wy - ny) < snap)
1001 else if(abs((wy + wh) - (ny + c->h + 2 * c->bw)) < snap)
1002 ny = wy + wh - c->h - 2 * c->bw;
1003 if(!c->isfloating && lt[sellt]->arrange && (abs(nx - c->x) > snap || abs(ny - c->y) > snap))
1004 togglefloating(NULL);
1006 if(!lt[sellt]->arrange || c->isfloating)
1007 resize(c, nx, ny, c->w, c->h, False);
1014 nexttiled(Client *c) {
1015 for(; c && (c->isfloating || !ISVISIBLE(c)); c = c->next);
1020 propertynotify(XEvent *e) {
1023 XPropertyEvent *ev = &e->xproperty;
1025 if(ev->state == PropertyDelete)
1026 return; /* ignore */
1027 if((c = getclient(ev->window))) {
1030 case XA_WM_TRANSIENT_FOR:
1031 XGetTransientForHint(dpy, c->win, &trans);
1032 if(!c->isfloating && (c->isfloating = (getclient(trans) != NULL)))
1035 case XA_WM_NORMAL_HINTS:
1043 if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
1052 quit(const Arg *arg) {
1053 readin = running = False;
1057 resize(Client *c, int x, int y, int w, int h, Bool sizehints) {
1061 /* set minimum possible */
1065 /* temporarily remove base dimensions */
1069 /* adjust for aspect limits */
1070 if(c->mina > 0 && c->maxa > 0) {
1071 if(c->maxa < (float) w/h)
1073 else if(c->mina > (float) h/w)
1077 /* adjust for increment value */
1083 /* restore base dimensions */
1087 w = MAX(w, c->minw);
1088 h = MAX(h, c->minh);
1091 w = MIN(w, c->maxw);
1094 h = MIN(h, c->maxh);
1096 if(w <= 0 || h <= 0)
1099 x = sw - w - 2 * c->bw;
1101 y = sh - h - 2 * c->bw;
1102 if(x + w + 2 * c->bw < sx)
1104 if(y + h + 2 * c->bw < sy)
1110 if(c->x != x || c->y != y || c->w != w || c->h != h) {
1113 c->w = wc.width = w;
1114 c->h = wc.height = h;
1115 wc.border_width = c->bw;
1116 XConfigureWindow(dpy, c->win,
1117 CWX|CWY|CWWidth|CWHeight|CWBorderWidth, &wc);
1124 resizemouse(const Arg *arg) {
1135 if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
1136 None, cursor[CurResize], CurrentTime) != GrabSuccess)
1138 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->bw - 1, c->h + c->bw - 1);
1140 XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask , &ev);
1143 XWarpPointer(dpy, None, c->win, 0, 0, 0, 0,
1144 c->w + c->bw - 1, c->h + c->bw - 1);
1145 XUngrabPointer(dpy, CurrentTime);
1146 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1148 case ConfigureRequest:
1151 handler[ev.type](&ev);
1155 nw = MAX(ev.xmotion.x - ocx - 2 * c->bw + 1, 1);
1156 nh = MAX(ev.xmotion.y - ocy - 2 * c->bw + 1, 1);
1158 if(snap && nw >= wx && nw <= wx + ww
1159 && nh >= wy && nh <= wy + wh) {
1160 if(!c->isfloating && lt[sellt]->arrange
1161 && (abs(nw - c->w) > snap || abs(nh - c->h) > snap))
1162 togglefloating(NULL);
1164 if(!lt[sellt]->arrange || c->isfloating)
1165 resize(c, c->x, c->y, nw, nh, True);
1180 if(sel->isfloating || !lt[sellt]->arrange)
1181 XRaiseWindow(dpy, sel->win);
1182 if(lt[sellt]->arrange) {
1183 wc.stack_mode = Below;
1184 wc.sibling = barwin;
1185 for(c = stack; c; c = c->snext)
1186 if(!c->isfloating && ISVISIBLE(c)) {
1187 XConfigureWindow(dpy, c->win, CWSibling|CWStackMode, &wc);
1188 wc.sibling = c->win;
1192 while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
1198 char sbuf[sizeof stext];
1204 /* main event loop, also reads status text from stdin */
1206 xfd = ConnectionNumber(dpy);
1209 len = sizeof stext - 1;
1210 sbuf[len] = stext[len] = '\0'; /* 0-terminator is never touched */
1214 FD_SET(STDIN_FILENO, &rd);
1216 if(select(xfd + 1, &rd, NULL, NULL, NULL) == -1) {
1219 eprint("select failed\n");
1221 if(FD_ISSET(STDIN_FILENO, &rd)) {
1222 switch((r = read(STDIN_FILENO, sbuf + offset, len - offset))) {
1224 strncpy(stext, strerror(errno), len);
1228 strncpy(stext, "EOF", 4);
1232 for(p = sbuf + offset; r > 0; p++, r--, offset++)
1233 if(*p == '\n' || *p == '\0') {
1235 strncpy(stext, sbuf, len);
1236 p += r - 1; /* p is sbuf + offset + r - 1 */
1237 for(r = 0; *(p - r) && *(p - r) != '\n'; r++);
1240 memmove(sbuf, p - r + 1, r);
1247 while(XPending(dpy)) {
1248 XNextEvent(dpy, &ev);
1249 if(handler[ev.type])
1250 (handler[ev.type])(&ev); /* call handler */
1258 Window *wins, d1, d2;
1259 XWindowAttributes wa;
1262 if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
1263 for(i = 0; i < num; i++) {
1264 if(!XGetWindowAttributes(dpy, wins[i], &wa)
1265 || wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
1267 if(wa.map_state == IsViewable || getstate(wins[i]) == IconicState)
1268 manage(wins[i], &wa);
1270 for(i = 0; i < num; i++) { /* now the transients */
1271 if(!XGetWindowAttributes(dpy, wins[i], &wa))
1273 if(XGetTransientForHint(dpy, wins[i], &d1)
1274 && (wa.map_state == IsViewable || getstate(wins[i]) == IconicState))
1275 manage(wins[i], &wa);
1283 setclientstate(Client *c, long state) {
1284 long data[] = {state, None};
1286 XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
1287 PropModeReplace, (unsigned char *)data, 2);
1291 setlayout(const Arg *arg) {
1292 if(!arg || !arg->v || arg->v != lt[sellt])
1295 lt[sellt] = (Layout *)arg->v;
1302 /* arg > 1.0 will set mfact absolutly */
1304 setmfact(const Arg *arg) {
1307 if(!arg || !lt[sellt]->arrange)
1309 f = arg->f < 1.0 ? arg->f + mfact : arg->f - 1.0;
1310 if(f < 0.1 || f > 0.9)
1320 XSetWindowAttributes wa;
1323 screen = DefaultScreen(dpy);
1324 root = RootWindow(dpy, screen);
1328 sw = DisplayWidth(dpy, screen);
1329 sh = DisplayHeight(dpy, screen);
1330 bh = dc.h = dc.font.height + 2;
1331 lt[0] = &layouts[0];
1332 lt[1] = &layouts[1 % LENGTH(layouts)];
1336 wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1337 wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1338 wmatom[WMName] = XInternAtom(dpy, "WM_NAME", False);
1339 wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
1340 netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
1341 netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1344 wa.cursor = cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
1345 cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
1346 cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
1348 /* init appearance */
1349 dc.norm[ColBorder] = getcolor(normbordercolor);
1350 dc.norm[ColBG] = getcolor(normbgcolor);
1351 dc.norm[ColFG] = getcolor(normfgcolor);
1352 dc.sel[ColBorder] = getcolor(selbordercolor);
1353 dc.sel[ColBG] = getcolor(selbgcolor);
1354 dc.sel[ColFG] = getcolor(selfgcolor);
1355 dc.drawable = XCreatePixmap(dpy, root, DisplayWidth(dpy, screen), bh, DefaultDepth(dpy, screen));
1356 dc.gc = XCreateGC(dpy, root, 0, 0);
1357 XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
1359 XSetFont(dpy, dc.gc, dc.font.xfont->fid);
1362 for(blw = i = 0; LENGTH(layouts) > 1 && i < LENGTH(layouts); i++) {
1363 w = TEXTW(layouts[i].symbol);
1367 wa.override_redirect = 1;
1368 wa.background_pixmap = ParentRelative;
1369 wa.event_mask = ButtonPressMask|ExposureMask;
1371 barwin = XCreateWindow(dpy, root, wx, by, ww, bh, 0, DefaultDepth(dpy, screen),
1372 CopyFromParent, DefaultVisual(dpy, screen),
1373 CWOverrideRedirect|CWBackPixmap|CWEventMask, &wa);
1374 XDefineCursor(dpy, barwin, cursor[CurNormal]);
1375 XMapRaised(dpy, barwin);
1376 strcpy(stext, "dwm-"VERSION);
1379 /* EWMH support per view */
1380 XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
1381 PropModeReplace, (unsigned char *) netatom, NetLast);
1383 /* select for events */
1384 wa.event_mask = SubstructureRedirectMask|SubstructureNotifyMask|ButtonPressMask
1385 |EnterWindowMask|LeaveWindowMask|StructureNotifyMask;
1386 XChangeWindowAttributes(dpy, root, CWEventMask|CWCursor, &wa);
1387 XSelectInput(dpy, root, wa.event_mask);
1395 spawn(const Arg *arg) {
1396 /* The double-fork construct avoids zombie processes and keeps the code
1397 * clean from stupid signal handlers. */
1401 close(ConnectionNumber(dpy));
1403 execvp(((char **)arg->v)[0], (char **)arg->v);
1404 fprintf(stderr, "dwm: execvp %s", ((char **)arg->v)[0]);
1413 tag(const Arg *arg) {
1414 if(sel && arg->ui & TAGMASK) {
1415 sel->tags = arg->ui & TAGMASK;
1421 textnw(const char *text, uint len) {
1425 XmbTextExtents(dc.font.set, text, len, NULL, &r);
1428 return XTextWidth(dc.font.xfont, text, len);
1437 for(n = 0, c = nexttiled(clients); c; c = nexttiled(c->next), n++);
1442 c = nexttiled(clients);
1444 resize(c, wx, wy, (n == 1 ? ww : mw) - 2 * c->bw, wh - 2 * c->bw, resizehints);
1450 x = (wx + mw > c->x + c->w) ? c->x + c->w + 2 * c->bw : wx + mw;
1452 w = (wx + mw > c->x + c->w) ? wx + ww - x : ww - mw;
1457 for(i = 0, c = nexttiled(c->next); c; c = nexttiled(c->next), i++) {
1458 resize(c, x, y, w - 2 * c->bw, /* remainder */ ((i + 1 == n)
1459 ? (wy + wh) - y : h) - 2 * c->bw, resizehints);
1461 y = c->y + c->h + 2 * c->bw;
1466 togglebar(const Arg *arg) {
1474 togglefloating(const Arg *arg) {
1477 sel->isfloating = !sel->isfloating || sel->isfixed;
1479 resize(sel, sel->x, sel->y, sel->w, sel->h, True);
1484 toggletag(const Arg *arg) {
1485 uint mask = sel->tags ^ (arg->ui & TAGMASK);
1494 toggleview(const Arg *arg) {
1495 uint mask = tagset[seltags] ^ (arg->ui & TAGMASK);
1498 tagset[seltags] = mask;
1504 unmanage(Client *c) {
1507 wc.border_width = c->oldbw;
1508 /* The server grab construct avoids race conditions. */
1510 XSetErrorHandler(xerrordummy);
1511 XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
1516 XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
1517 setclientstate(c, WithdrawnState);
1520 XSetErrorHandler(xerror);
1526 unmapnotify(XEvent *e) {
1528 XUnmapEvent *ev = &e->xunmap;
1530 if((c = getclient(ev->window)))
1536 if(dc.drawable != 0)
1537 XFreePixmap(dpy, dc.drawable);
1538 dc.drawable = XCreatePixmap(dpy, root, ww, bh, DefaultDepth(dpy, screen));
1539 XMoveResizeWindow(dpy, barwin, wx, by, ww, bh);
1546 XineramaScreenInfo *info = NULL;
1548 /* window area geometry */
1549 if(XineramaIsActive(dpy)) {
1550 info = XineramaQueryScreens(dpy, &i);
1551 wx = info[xidx].x_org;
1552 wy = showbar && topbar ? info[xidx].y_org + bh : info[xidx].y_org;
1553 ww = info[xidx].width;
1554 wh = showbar ? info[xidx].height - bh : info[xidx].height;
1561 wy = showbar && topbar ? sy + bh : sy;
1563 wh = showbar ? sh - bh : sh;
1567 by = showbar ? (topbar ? wy - bh : wy + wh) : -bh;
1571 updatesizehints(Client *c) {
1575 XGetWMNormalHints(dpy, c->win, &size, &msize);
1576 if(size.flags & PBaseSize) {
1577 c->basew = size.base_width;
1578 c->baseh = size.base_height;
1580 else if(size.flags & PMinSize) {
1581 c->basew = size.min_width;
1582 c->baseh = size.min_height;
1585 c->basew = c->baseh = 0;
1586 if(size.flags & PResizeInc) {
1587 c->incw = size.width_inc;
1588 c->inch = size.height_inc;
1591 c->incw = c->inch = 0;
1592 if(size.flags & PMaxSize) {
1593 c->maxw = size.max_width;
1594 c->maxh = size.max_height;
1597 c->maxw = c->maxh = 0;
1598 if(size.flags & PMinSize) {
1599 c->minw = size.min_width;
1600 c->minh = size.min_height;
1602 else if(size.flags & PBaseSize) {
1603 c->minw = size.base_width;
1604 c->minh = size.base_height;
1607 c->minw = c->minh = 0;
1608 if(size.flags & PAspect) {
1609 c->mina = (float)size.min_aspect.y / (float)size.min_aspect.x;
1610 c->maxa = (float)size.max_aspect.x / (float)size.max_aspect.y;
1613 c->maxa = c->mina = 0.0;
1614 c->isfixed = (c->maxw && c->minw && c->maxh && c->minh
1615 && c->maxw == c->minw && c->maxh == c->minh);
1619 updatetitle(Client *c) {
1620 if(!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
1621 gettextprop(c->win, wmatom[WMName], c->name, sizeof c->name);
1625 updatewmhints(Client *c) {
1628 if((wmh = XGetWMHints(dpy, c->win))) {
1630 sel->isurgent = False;
1632 c->isurgent = (wmh->flags & XUrgencyHint) ? True : False;
1638 view(const Arg *arg) {
1639 if(arg && (arg->i & TAGMASK) == tagset[seltags])
1641 seltags ^= 1; /* toggle sel tagset */
1642 if(arg && (arg->ui & TAGMASK))
1643 tagset[seltags] = arg->i & TAGMASK;
1647 /* There's no way to check accesses to destroyed windows, thus those cases are
1648 * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
1649 * default error handler, which may call exit. */
1651 xerror(Display *dpy, XErrorEvent *ee) {
1652 if(ee->error_code == BadWindow
1653 || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
1654 || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
1655 || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
1656 || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
1657 || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
1658 || (ee->request_code == X_GrabButton && ee->error_code == BadAccess)
1659 || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
1660 || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
1662 fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
1663 ee->request_code, ee->error_code);
1664 return xerrorxlib(dpy, ee); /* may call exit */
1668 xerrordummy(Display *dpy, XErrorEvent *ee) {
1672 /* Startup Error handler to check if another window manager
1673 * is already running. */
1675 xerrorstart(Display *dpy, XErrorEvent *ee) {
1681 zoom(const Arg *arg) {
1684 if(!lt[sellt]->arrange || lt[sellt]->arrange == monocle || (sel && sel->isfloating))
1686 if(c == nexttiled(clients))
1687 if(!c || !(c = nexttiled(c->next)))
1696 main(int argc, char *argv[]) {
1697 if(argc == 2 && !strcmp("-v", argv[1]))
1698 eprint("dwm-"VERSION", © 2006-2008 dwm engineers, see LICENSE for details\n");
1700 eprint("usage: dwm [-v]\n");
1702 if(!setlocale(LC_CTYPE, "") || !XSupportsLocale())
1703 fprintf(stderr, "warning: no locale support\n");
1705 if(!(dpy = XOpenDisplay(0)))
1706 eprint("dwm: cannot open display\n");