Cotton code
64 lines · 2.4 KB · PythonRaw
#!/usr/bin/env python3"""Write Home's tool objects into `apps/loom/Sources/CottonPaper/Media.xcassets`.    python3 scripts/gen-tools/export_tool_objects.py <dir of tool-<key>.png>The pipeline, end to end: a generated sheet of objects on a flat magentaground is cut into one transparent 600 px square per tool by `cut_sheet.py`(Pillow + numpy); this script turns that folder into one universal 2x imagesetper object (300pt intrinsic — Home draws them far smaller, so the phone's 3xscreen still has pixels to spare). No image work happens here, only checks:every file must be a 600x600 PNG with an alpha channel, or the export stops.The set of keys is whatever the folder holds. Which tool draws which object isthe app's decision (`Paper/ToolObjects.swift`), and `ToolObjectsTests`holds that table total over Home's directory and every named object to animageset this script wrote. Standard library only."""import jsonimport pathlibimport shutilimport structimport sysROOT = pathlib.Path(__file__).resolve().parents[2]CATALOGUE = ROOT / "apps/loom/Sources/CottonPaper/Media.xcassets"SIDE = 600# PNG colour types that carry alpha: greyscale+alpha (4) and RGBA (6).ALPHA_TYPES = {4, 6}def png_header(path):    with open(path, "rb") as f:        head = f.read(26)    if head[:8] != b"\x89PNG\r\n\x1a\n" or head[12:16] != b"IHDR":        raise SystemExit(f"{path.name}: not a PNG")    width, height = struct.unpack(">II", head[16:24])    return width, height, head[25]def main():    if len(sys.argv) != 2:        raise SystemExit(__doc__)    source = pathlib.Path(sys.argv[1]).expanduser()    files = sorted(source.glob("tool-*.png"))    if not files:        raise SystemExit(f"no tool-*.png in {source}")    for path in files:        width, height, colour = png_header(path)        if (width, height) != (SIDE, SIDE) or colour not in ALPHA_TYPES:            raise SystemExit(f"{path.name}: {width}x{height}, colour type {colour} — want {SIDE}x{SIDE} with alpha")        name = path.stem        dest = CATALOGUE / f"{name}.imageset"        dest.mkdir(parents=True, exist_ok=True)        shutil.copyfile(path, dest / path.name)        contents = {            "images": [{"filename": path.name, "idiom": "universal", "scale": "2x"}],            "info": {"author": "xcode", "version": 1},        }        (dest / "Contents.json").write_text(json.dumps(contents, indent=2) + "\n")        print("wrote", name)if __name__ == "__main__":    main()