Cotton code
309 lines · 15.8 KB · PythonRaw
#!/usr/bin/env python3"""Makes the site's pictures and fonts from the repository's own sources, asapps.json names them:  static/icons/<id>.png          the app's store icon, 180 px (and <id>-512.png for link previews)  static/shots/<id>/<file>.webp  each screenshot at 360 px wide, and <file>@2x.webp at 720 px  static/fonts/<file>            the app's typeface, cut to Latin and packed as WOFF2  static/og/<id>.png, home.png   the picture a shared link shows (1200 x 630)  static/shots/<id>/manifest.json  what the build checks (src/site/checks.ts checkShots): each screen's                                 sha256, how far it is from one flat colour, and the pen mark it was                                 measured with and how much is drawn under it  python3 tools/site_pictures.py            every app  python3 tools/site_pictures.py days words only these  python3 tools/site_pictures.py --measure  only re-measure the screens and their marks (after moving a mark)Needs Pillow, fontTools and brotli (pip install pillow fonttools brotli).The screenshots themselves come from the apps with invented data:tools/site_shots.sh retakes them on an Android emulator; this script onlysizes what apps.json points at."""import json, os, sysfrom pathlib import Pathtry:    from PIL import Image    from fontTools import subset    import brotli  # noqa: F401  (fontTools needs it for WOFF2)except ImportError as e:    sys.exit(f"site_pictures.py needs Pillow, fontTools and brotli ({e}). pip install pillow fonttools brotli")SITE = Path(__file__).resolve().parent.parentREPO = SITE.parent.parentSTATIC = SITE / "static"LATIN = "U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+2000-206F,U+2074,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD"def icon(app):    src = Image.open(REPO / app["iconSource"]).convert("RGB")    (STATIC / "icons").mkdir(parents=True, exist_ok=True)    src.resize((180, 180), Image.LANCZOS).save(STATIC / "icons" / f"{app['id']}.png", optimize=True)    src.resize((512, 512), Image.LANCZOS).save(STATIC / "icons" / f"{app['id']}-512.png", optimize=True)    src.resize((256, 256), Image.LANCZOS).save(STATIC / "icons" / f"{app['id']}.webp", "WEBP", quality=88, method=6)def shots(app):    out = STATIC / "shots" / app["id"]    out.mkdir(parents=True, exist_ok=True)    keep = {"manifest.json"}    for s in app["shots"]:        im = Image.open(REPO / s["source"]).convert("RGB")        for w, suffix in ((360, ""), (720, "@2x")):            h = round(im.height * w / im.width)            name = f"{s['file']}{suffix}.webp"            im.resize((w, h), Image.LANCZOS).save(out / name, "WEBP", quality=82, method=6)            keep.add(name)    for f in out.iterdir():        if f.name not in keep:            f.unlink()def _measure(im, box=None):    """How much is drawn: the spread of grey levels, and the share of the commonest grey (1.0 is one flat colour)."""    from PIL import ImageStat    g = im.convert("L")    if box:        x0, y0, x1, y1 = box        g = g.crop((max(0, x0), max(0, y0), min(g.width, x1), min(g.height, y1)))    hist = g.histogram()    return round(ImageStat.Stat(g).stddev[0], 1), round(max(hist) / max(1, sum(hist)), 3)def _mark_box(mark, w, h):    if "ring" in mark:        cx, cy, rw, rh = mark["ring"]        return (round((cx - rw / 2) * w / 100), round((cy - rh / 2) * h / 100), round((cx + rw / 2) * w / 100), round((cy + rh / 2) * h / 100))    x1, y1, x2, y2 = mark["arrow"]    # What an arrow names is where it ends: the patch round its head.    return (round((x2 - 6) * w / 100), round((y2 - 3) * h / 100), round((x2 + 6) * w / 100), round((y2 + 3) * h / 100))def manifest(app):    """What the build checks for each screen, measured on the very file it serves."""    import hashlib    out = STATIC / "shots" / app["id"]    m = {}    for s in app["shots"]:        f = out / f"{s['file']}.webp"        im = Image.open(f).convert("RGB")        spread, flat = _measure(im)        e = {"sha256": hashlib.sha256(f.read_bytes()).hexdigest(), "spread": spread, "flat": flat}        if s.get("mark"):            e["mark"] = s["mark"]            e["markSpread"], e["markFlat"] = _measure(im, _mark_box(s["mark"], im.width, im.height))        m[s["file"]] = e    (out / "manifest.json").write_text(json.dumps(m, indent=1) + "\n")def font(app):    """The site's fonts are the design's own, served as they are from static/fonts; nothing is made per app."""    returndef _ttf(path, size):    """A font Pillow can draw with, from a .ttf, or a .woff2 unpacked first."""    from PIL import ImageFont    from fontTools.ttLib import TTFont    import io    p = Path(path)    if p.suffix == ".woff2":        f = TTFont(str(p)); f.flavor = None; buf = io.BytesIO(); f.save(buf); buf.seek(0)        return ImageFont.truetype(buf, size)    return ImageFont.truetype(str(p), size)def _wrap(draw, text, font, width):    lines, line = [], ""    for word in text.split():        trial = f"{line} {word}".strip()        if draw.textlength(trial, font=font) <= width: line = trial        else: lines.append(line); line = word    return lines + [line]def _hex(h): return tuple(int(h[i:i+2], 16) for i in (1, 3, 5))# ── the link previews (1200 x 630): each page's own look, drawn at twice the size and halved ─────────────────## They follow the pages as built (src/site/pages.ts, cotton.css): the home's headline in Fraunces as the cover sets it,# with its thread and the owner's photo; each app's name in its page's own type, flourish and paper, with its line from# apps.json. Remade with the pages (SHARE CARD, 24 Nov 2026): a card that says what the page no longer says is wrong.X2 = 2  # drawn at twice the size# The pages' own marks (src/site/html.ts), as paths.RING = "M34 20C74 3 150 1 181 27c24 21 6 58-60 66C60 100 9 88 8 56 7 29 42 9 98 7c24-1 45 3 60 9"THREAD = "M2 7C28 2 52 10 80 6s52-3 78 1c14 2 28 1 40-3"def _path(d, steps=24):    """An SVG path (M, C, S, L, A, Z and their relative forms) as polylines of points, one list per subpath."""    import re, math    toks = re.findall(r"[MmCcSsLlAaZz]|-?(?:\d+\.?\d*|\.\d+)(?:e-?\d+)?", d)    out, cur, pos, start, last_ctrl, cmd, k = [], [], (0.0, 0.0), (0.0, 0.0), None, None, 0    def num():        nonlocal k; v = float(toks[k]); k += 1; return v    def cubic(p0, p1, p2, p3):        for n in range(1, steps + 1):            t = n / steps; u = 1 - t            cur.append((u**3*p0[0] + 3*u*u*t*p1[0] + 3*u*t*t*p2[0] + t**3*p3[0], u**3*p0[1] + 3*u*u*t*p1[1] + 3*u*t*t*p2[1] + t**3*p3[1]))    while k < len(toks):        if re.match(r"[A-Za-z]", toks[k]):            cmd = toks[k]; k += 1        rel = cmd.islower(); c = cmd.upper()        o = pos if rel else (0.0, 0.0)        if c == "M":            if cur: out.append(cur)            pos = (o[0] + num(), o[1] + num()); start = pos; cur = [pos]; last_ctrl = None            cmd = "l" if rel else "L"        elif c == "L":            pos = (o[0] + num(), o[1] + num()); cur.append(pos); last_ctrl = None        elif c == "C":            p1 = (o[0] + num(), o[1] + num()); p2 = (o[0] + num(), o[1] + num()); p3 = (o[0] + num(), o[1] + num())            cubic(pos, p1, p2, p3); last_ctrl = p2; pos = p3        elif c == "S":            p1 = (2*pos[0] - last_ctrl[0], 2*pos[1] - last_ctrl[1]) if last_ctrl else pos            p2 = (o[0] + num(), o[1] + num()); p3 = (o[0] + num(), o[1] + num())            cubic(pos, p1, p2, p3); last_ctrl = p2; pos = p3        elif c == "A":            rx, ry, _rot, large, sweep = num(), num(), num(), num(), num()            end = (o[0] + num(), o[1] + num())            # Circular arcs only (the quote's): the centre from the chord, then the angles.            r = rx; (x1, y1), (x2, y2) = pos, end            mx, my = (x1 + x2) / 2, (y1 + y2) / 2; dx, dy = x2 - x1, y2 - y1; q = math.hypot(dx, dy)            h = math.sqrt(max(r*r - (q/2)**2, 0)); sign = 1 if large != sweep else -1            cx, cy = mx - sign * h * dy / q, my + sign * h * dx / q            a1, a2 = math.atan2(y1 - cy, x1 - cx), math.atan2(y2 - cy, x2 - cx)            if sweep and a2 < a1: a2 += 2 * math.pi            if not sweep and a2 > a1: a2 -= 2 * math.pi            for n in range(1, steps * 2 + 1):                a = a1 + (a2 - a1) * n / (steps * 2); cur.append((cx + r * math.cos(a), cy + r * math.sin(a)))            pos = end; last_ctrl = None        elif c == "Z":            cur.append(start); pos = start; out.append(cur); cur = []; last_ctrl = None    if cur: out.append(cur)    return outdef _stroke(d, path, box, view, width, colour):    """`path` (in its `view` (w, h) box) stretched into `box` (x, y, w, h), as the pages' preserveAspectRatio="none" does."""    x, y, w, h = box    for line in _path(path):        pts = [(x + px / view[0] * w, y + py / view[1] * h) for px, py in line]        d.line(pts, fill=colour, width=width, joint="curve")        for px, py in (pts[0], pts[-1]):            d.ellipse((px - width / 2, py - width / 2, px + width / 2, py + width / 2), fill=colour)def _face(name, size, **axes):    """A site font at `size` (already doubled), its variable axes set by name (wght, opsz, SOFT)."""    files = {"serif": "Fraunces.woff2", "sans": "Figtree.woff2", "type": "CourierPrime-Regular.woff2", "type-bold": "CourierPrime-Bold.woff2"}    f = _ttf(STATIC / "fonts" / files[name], size)    if axes:        names = {b"Weight": "wght", b"Optical Size": "opsz", b"Softness": "SOFT"}        f.set_variation_by_axes([axes.get(names.get(a["name"], ""), a["default"]) for a in f.get_variation_axes()])    return fdef _icon(im, app, at, size, ground, ink):    from PIL import ImageDraw    icon = Image.open(REPO / app["iconSource"]).convert("RGB").resize((size, size), Image.LANCZOS)    radius = int(size * .225)    mask = Image.new("L", (size, size), 0); ImageDraw.Draw(mask).rounded_rectangle((0, 0, size - 1, size - 1), radius, fill=255)    im.paste(icon, at, mask)    ImageDraw.Draw(im).rounded_rectangle((at[0], at[1], at[0] + size - 1, at[1] + size - 1), radius, outline=tuple(int(g * .82 + i * .18) for g, i in zip(_hex(ground), _hex(ink))), width=2 * X2)def _save(im, name):    (STATIC / "og").mkdir(parents=True, exist_ok=True)    im.resize((1200, 630), Image.LANCZOS).save(STATIC / "og" / f"{name}.png", optimize=True)def preview(app):    """The app's link preview, as its page's head: its name in the page's type with its flourish, its line, its icon,    on its own paper (apps.json look.paper; cotton.css .days/.words/.story/.comms)."""    from PIL import ImageDraw    paper = app["look"]["paper"]    ground, ink, soft, accent = (paper[k] for k in ("--ground", "--ink", "--muted", "--accent"))    im = Image.new("RGB", (1200 * X2, 630 * X2), _hex(ground))    d = ImageDraw.Draw(im)    display = paper.get("--display", "var(--serif)")    kind = "type" if "type" in display else "sans" if "sans" in display else "serif"    weight = {"words": 700, "story": 700, "comms": 600}.get(app["id"], 400)    size = 92 * X2    if kind == "type":        name_face = _face("type-bold" if weight >= 700 else "type", size)        line_face = _face("type", 34 * X2)    else:        name_face = _face(kind, size, wght=weight, opsz=144, SOFT=100)        line_face = _face(kind, 38 * X2, wght=400, opsz=24, SOFT=100)    left = 90 * X2    _icon(im, app, (left, 90 * X2), 150 * X2, ground, ink)    top = 300 * X2    flourish = app.get("flourish")    # Comms' quote is its icon's own mark, already on the card: it is not drawn twice.    if flourish == "ring":        # "Cotton " then the name ringed, as the page's title is.        first = "Cotton "; d.text((left, top), first, font=name_face, fill=_hex(ink))        x = left + d.textlength(first, font=name_face); w = d.textlength(app["name"], font=name_face)        d.text((x, top), app["name"], font=name_face, fill=_hex(ink))        asc = name_face.getbbox("Days")        bx, by, bw, bh = x - .16 * w, top + asc[1] - .24 * (asc[3] - asc[1]), w * 1.32, (asc[3] - asc[1]) * 1.5        _stroke(d, RING, (bx, by, bw, bh), (200, 100), int(3.2 * X2), _hex(accent))        end = x + w    else:        d.text((left, top), app["full"], font=name_face, fill=_hex(ink))        end = left + d.textlength(app["full"], font=name_face)        box = name_face.getbbox(app["full"])        if flourish == "cursor":            cap = box[3] - box[1]; d.rectangle((end + .06 * size, top + box[1] + .04 * cap, end + .145 * size, top + box[3]), fill=_hex(accent))        elif flourish == "stop":            d.text((end, top), ".", font=name_face, fill=_hex(accent))    y = top + int(size * 1.32)    for l in _wrap(d, app["line"], line_face, 1000 * X2)[:2]:        d.text((left, y), l, font=line_face, fill=_hex(soft)); y += int(line_face.size * 1.35)    d.text((left, 520 * X2), f"cottondb.com/{app['id']}", font=_face(kind if kind != "type" else "type", 30 * X2, wght=500, opsz=24, SOFT=100) if kind != "type" else _face("type-bold", 30 * X2), fill=_hex(accent))    _save(im, app["id"])def home_preview(apps):    """The site's link preview, as the home's cover: its headline (copy.ts HOME.h1) in Fraunces as .cover h1 sets it,    "and" quiet and "share them" on its thread, the owner's photo beside it, and every app's icon."""    from PIL import ImageDraw    import re    copy = (SITE / "src" / "site" / "copy.ts").read_text()    h1 = dict(re.findall(r'(first|quiet|thread|end): "([^"]*)"', copy.split("h1:", 1)[1].split("}", 1)[0]))    ground, ink, soft = "#F3F3F0", "#18181A", "#5E5E5A"    im = Image.new("RGB", (1200 * X2, 630 * X2), _hex(ground))    d = ImageDraw.Draw(im)    # The photo, as the cover sets it beside the headline on a desktop.    pw, ph = 380 * X2, 506 * X2    photo = Image.open(STATIC / "photos" / "mukesh-800.webp").convert("RGB")    scale = max(pw / photo.width, ph / photo.height)    photo = photo.resize((round(photo.width * scale), round(photo.height * scale)), Image.LANCZOS)    photo = photo.crop(((photo.width - pw) // 2, 0, (photo.width - pw) // 2 + pw, ph))    px, py = 1200 * X2 - pw - 62 * X2, 62 * X2    mask = Image.new("L", (pw, ph), 0); ImageDraw.Draw(mask).rounded_rectangle((0, 0, pw - 1, ph - 1), 28 * X2, fill=255)    im.paste(photo, (px, py), mask)    face = _face("serif", 74 * X2, wght=340, opsz=144, SOFT=100)    left, top, lead = 72 * X2, 92 * X2, int(74 * X2 * 1.04)    d.text((left, top), h1["first"], font=face, fill=_hex(ink))    y = top + lead    x = left    d.text((x, y), h1["quiet"] + " ", font=face, fill=_hex(soft)); x += d.textlength(h1["quiet"] + " ", font=face)    w = d.textlength(h1["thread"], font=face)    d.text((x, y), h1["thread"], font=face, fill=_hex(ink))    base = y + face.getbbox("a")[3]    _stroke(d, THREAD, (x - .02 * w, base + .02 * face.size, w * 1.04, .22 * face.size), (200, 12), int(3 * X2), _hex(ink))    d.text((x + w, y), h1["end"], font=face, fill=_hex(soft))    # The apps, small, under it; and the address.    size, gap = 92 * X2, 22 * X2    for i, app in enumerate(apps[:5]):        _icon(im, app, (left + i * (size + gap), 380 * X2), size, ground, ink)    d.text((left, 530 * X2), "cottondb.com", font=_face("serif", 32 * X2, wght=500, opsz=24, SOFT=100), fill=_hex(ink))    _save(im, "home")def main():    apps = json.loads((SITE / "apps.json").read_text())["apps"]    measure_only = "--measure" in sys.argv    want = set(a for a in sys.argv[1:] if a != "--measure")    unknown = want - {a["id"] for a in apps}    if unknown:        sys.exit(f"Not in apps.json: {', '.join(sorted(unknown))}")    for app in apps:        if want and app["id"] not in want:            continue        if measure_only:            manifest(app); print(f"{app['id']}: measured"); continue        icon(app); shots(app); manifest(app); font(app); preview(app)        print(f"{app['id']}: icon, {len(app['shots'])} screenshots{', font' if app['look'].get('font') else ''}, link preview")    home_preview(apps)if __name__ == "__main__":    main()