+void
+eprintf(const char *fmt, ...) {
+ va_list ap;
+
+ va_start(ap, fmt);
+ vfprintf(stderr, fmt, ap);
+ va_end(ap);
+
+ if(fmt[0] != '\0' && fmt[strlen(fmt)-1] == ':') {
+ fputc(' ', stderr);
+ perror(NULL);
+ }
+ exit(EXIT_FAILURE);
+}
+
+void
+freedc(DC *dc) {
+ if(dc->font.set)
+ XFreeFontSet(dc->dpy, dc->font.set);
+ if(dc->font.xfont)
+ XFreeFont(dc->dpy, dc->font.xfont);
+ if(dc->canvas)
+ XFreePixmap(dc->dpy, dc->canvas);
+ XFreeGC(dc->dpy, dc->gc);
+ XCloseDisplay(dc->dpy);
+ free(dc);
+}
+
+unsigned long
+getcolor(DC *dc, const char *colstr) {
+ Colormap cmap = DefaultColormap(dc->dpy, DefaultScreen(dc->dpy));
+ XColor color;
+
+ if(!XAllocNamedColor(dc->dpy, cmap, colstr, &color, &color))
+ eprintf("cannot allocate color '%s'\n", colstr);
+ return color.pixel;
+}
+
+DC *
+initdc(void) {
+ DC *dc;
+
+ if(!setlocale(LC_CTYPE, "") || !XSupportsLocale())
+ fputs("no locale support\n", stderr);
+ if(!(dc = calloc(1, sizeof *dc)))
+ eprintf("cannot malloc %u bytes:", sizeof *dc);
+ if(!(dc->dpy = XOpenDisplay(NULL)))
+ eprintf("cannot open display\n");
+
+ dc->gc = XCreateGC(dc->dpy, DefaultRootWindow(dc->dpy), 0, NULL);
+ XSetLineAttributes(dc->dpy, dc->gc, 1, LineSolid, CapButt, JoinMiter);
+ return dc;
+}
+
+void
+initfont(DC *dc, const char *fontstr) {
+ if(!loadfont(dc, fontstr ? fontstr : DEFAULTFN)) {
+ if(fontstr != NULL)
+ fprintf(stderr, "cannot load font '%s'\n", fontstr);
+ if(fontstr == NULL || !loadfont(dc, DEFAULTFN))
+ eprintf("cannot load font '%s'\n", DEFAULTFN);
+ }
+ dc->font.height = dc->font.ascent + dc->font.descent;
+}
+
+Bool
+loadfont(DC *dc, const char *fontstr) {
+ char *def, **missing, **names;
+ int i, n;
+ XFontStruct **xfonts;
+
+ if(!*fontstr)
+ return False;
+ if((dc->font.set = XCreateFontSet(dc->dpy, fontstr, &missing, &n, &def))) {
+ n = XFontsOfFontSet(dc->font.set, &xfonts, &names);
+ for(i = 0; i < n; i++) {
+ dc->font.ascent = MAX(dc->font.ascent, xfonts[i]->ascent);
+ dc->font.descent = MAX(dc->font.descent, xfonts[i]->descent);
+ dc->font.width = MAX(dc->font.width, xfonts[i]->max_bounds.width);
+ }
+ }
+ else if((dc->font.xfont = XLoadQueryFont(dc->dpy, fontstr))) {
+ dc->font.ascent = dc->font.xfont->ascent;
+ dc->font.descent = dc->font.xfont->descent;
+ dc->font.width = dc->font.xfont->max_bounds.width;
+ }
+ if(missing)
+ XFreeStringList(missing);
+ return dc->font.set || dc->font.xfont;
+}
+
+void
+mapdc(DC *dc, Window win, unsigned int w, unsigned int h) {
+ XCopyArea(dc->dpy, dc->canvas, win, dc->gc, 0, 0, w, h, 0, 0);