Cotton code
131 lines · 6.8 KB · PythonRaw
#!/usr/bin/env python3"""The seek walk's two books (WALK_BOOK_FACES=seek): "The Lantern Orchard", aninvented book of twelve chapters, as an EPUB (a nav document, one resourceper chapter) and a PDF (three pages a chapter, an outline entry each). Everyword is made here from a fixed word list, so the files are the same bytes onevery run and belong to nobody.  python3 scripts/gen-seek-fixtures.py   # writes apps/cotton/Tests/CottonUITests/Fixtures/Books/the-lantern-orchard.{epub,pdf}"""import osimport randomimport zipfileimport zlibHERE = os.path.dirname(os.path.abspath(__file__))OUT = os.path.join(HERE, "..", "apps", "cotton", "Tests", "CottonUITests", "Fixtures", "Books")TITLE = "The Lantern Orchard"AUTHOR = "Asha Mercer"CHAPTERS = ["The Gate", "Lamp Oil", "The Ferryman's Ledger", "Windfall", "A Map of the Rows", "The Grafting Knife",            "Night Pickers", "Cider Weather", "The Blight Year", "Smoke on the Terraces", "The Last Ladder", "Harvest Home"]WORDS = ("orchard lantern ferry ledger harbour terrace ladder basket cider graft blossom frost keeper river stone path "         "evening morning quiet amber slow narrow bright cold warm old small tall the a and of in on by with under over "         "walked carried counted lit waited turned gathered remembered opened closed followed kept left found").split()def paragraph(rng, sentences):    out = []    for _ in range(sentences):        words = [rng.choice(WORDS) for _ in range(rng.randint(9, 17))]        out.append(" ".join(words).capitalize() + ".")    return " ".join(out)def epub(path):    rng = random.Random(1892)    stamp = (2026, 1, 1, 0, 0, 0)    def put(z, name, text, method=zipfile.ZIP_DEFLATED):        info = zipfile.ZipInfo(name, stamp)        info.compress_type = method        z.writestr(info, text)    with zipfile.ZipFile(path, "w") as z:        put(z, "mimetype", "application/epub+zip", zipfile.ZIP_STORED)        put(z, "META-INF/container.xml", '<?xml version="1.0"?><container version="1.0" xmlns="urn:oasis:names:tc:opendocument:xmlns:container">'            '<rootfiles><rootfile full-path="OEBPS/content.opf" media-type="application/oebps-package+xml"/></rootfiles></container>')        items = "".join(f'<item id="c{i:02}" href="c{i:02}.xhtml" media-type="application/xhtml+xml"/>' for i in range(1, len(CHAPTERS) + 1))        spine = "".join(f'<itemref idref="c{i:02}"/>' for i in range(1, len(CHAPTERS) + 1))        put(z, "OEBPS/content.opf", '<?xml version="1.0" encoding="UTF-8"?><package xmlns="http://www.idpf.org/2007/opf" version="3.0" unique-identifier="id">'            f'<metadata xmlns:dc="http://purl.org/dc/elements/1.1/"><dc:identifier id="id">urn:cotton:fixture:the-lantern-orchard</dc:identifier>'            f'<dc:title>{TITLE}</dc:title><dc:creator>{AUTHOR}</dc:creator><dc:language>en</dc:language>'            '<meta property="dcterms:modified">2026-01-01T00:00:00Z</meta></metadata>'            f'<manifest><item id="nav" href="nav.xhtml" media-type="application/xhtml+xml" properties="nav"/>{items}</manifest>'            f'<spine>{spine}</spine></package>')        links = "".join(f'<li><a href="c{i:02}.xhtml">{name}</a></li>' for i, name in enumerate(CHAPTERS, 1))        put(z, "OEBPS/nav.xhtml", '<?xml version="1.0" encoding="UTF-8"?><html xmlns="http://www.w3.org/1999/xhtml" xmlns:epub="http://www.idpf.org/2007/ops">'            f'<head><title>{TITLE}</title></head><body><nav epub:type="toc"><h1>Contents</h1><ol>{links}</ol></nav></body></html>')        for i, name in enumerate(CHAPTERS, 1):            body = "".join(f"<p>{paragraph(rng, 5)}</p>" for _ in range(22))            put(z, f"OEBPS/c{i:02}.xhtml", '<?xml version="1.0" encoding="UTF-8"?><html xmlns="http://www.w3.org/1999/xhtml">'                f'<head><title>{name}</title></head><body><h1>{name}</h1>{body}</body></html>')def pdf(path):    rng = random.Random(1893)    per = 3    pages = len(CHAPTERS) * per    objects = {}    def obj(number, body):        objects[number] = body if isinstance(body, bytes) else body.encode("latin-1")    # 1 catalog, 2 pages, 3 font, 4 outlines, then per page: page, content; then outline items.    first_page = 5    first_item = first_page + pages * 2    kids = " ".join(f"{first_page + p * 2} 0 R" for p in range(pages))    obj(1, f"<< /Type /Catalog /Pages 2 0 R /Outlines 4 0 R /PageMode /UseOutlines >>")    obj(2, f"<< /Type /Pages /Kids [{kids}] /Count {pages} >>")    obj(3, "<< /Type /Font /Subtype /Type1 /BaseFont /Times-Roman >>")    obj(4, f"<< /Type /Outlines /First {first_item} 0 R /Last {first_item + len(CHAPTERS) - 1} 0 R /Count {len(CHAPTERS)} >>")    for p in range(pages):        chapter = CHAPTERS[p // per]        lines = []        if p % per == 0:            lines.append(("F1 20", chapter))        text = paragraph(rng, 40).split(" ")        row = []        for word in text:            row.append(word)            if len(" ".join(row)) > 62:                lines.append(("F1 12", " ".join(row)))                row = []        stream = ["BT", "72 720 Td"]        for font, line in lines[:34]:            size = font.split(" ")[1]            stream.append(f"/{font} Tf ({line}) Tj 0 -{int(size) + 6} Td")        stream += ["ET", "BT /F1 10 Tf 300 40 Td (" + str(p + 1) + ") Tj ET"]        data = zlib.compress("\n".join(stream).encode("latin-1"), 9)        number = first_page + p * 2        obj(number, f"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources << /Font << /F1 3 0 R >> >> /Contents {number + 1} 0 R >>")        obj(number + 1, f"<< /Length {len(data)} /Filter /FlateDecode >>\nstream\n".encode("latin-1") + data + b"\nendstream")    for i, name in enumerate(CHAPTERS):        number = first_item + i        links = ""        if i > 0:            links += f" /Prev {number - 1} 0 R"        if i < len(CHAPTERS) - 1:            links += f" /Next {number + 1} 0 R"        obj(number, f"<< /Title ({name}) /Parent 4 0 R{links} /Dest [{first_page + i * per * 2} 0 R /Fit] >>")    info = first_item + len(CHAPTERS)    obj(info, f"<< /Title ({TITLE}) /Author ({AUTHOR}) >>")    out = bytearray(b"%PDF-1.5\n%\xe2\xe3\xcf\xd3\n")    offsets = {}    for number in sorted(objects):        offsets[number] = len(out)        out += f"{number} 0 obj\n".encode("latin-1") + objects[number] + b"\nendobj\n"    xref = len(out)    count = max(objects) + 1    out += f"xref\n0 {count}\n".encode("latin-1") + b"0000000000 65535 f \n"    for number in range(1, count):        out += f"{offsets[number]:010} 00000 n \n".encode("latin-1")    out += f"trailer\n<< /Size {count} /Root 1 0 R /Info {info} 0 R >>\nstartxref\n{xref}\n%%EOF\n".encode("latin-1")    with open(path, "wb") as f:        f.write(out)if __name__ == "__main__":    epub(os.path.join(OUT, "the-lantern-orchard.epub"))    pdf(os.path.join(OUT, "the-lantern-orchard.pdf"))    print("wrote the-lantern-orchard.epub and the-lantern-orchard.pdf")