Cotton code
171 lines · 7.1 KB · PythonRaw
#!/usr/bin/env python3"""Lay Cotton Money's fan tiles into its kit, as data.    python3 scripts/import-money-tiles.py <layers directory>The ruled ledger (Round 25, 8 Nov 2026, the owner's pick): one wordless tilestock, `tile-blank.png` (474 x 696, cream ruled ledger stock with one brasscorner, alpha outside its silhouette; the rules belong to the blank), and onenavy printed pictogram per key, each a centred 300 x 300 cut-out(`<key>.png`), painted with Codex (`apps25-tiles-layers/money`, with`layout.json`, `validation.json` and `notes.md`). No word or numeral is on anyof them: the phone types the name and the count live, in Courier.Each picture goes into the Money tool's kit folder as`pictures/<sha256>.png` and is named by the tool's `fan_tile` in its manifest(`crates/cotton-core/src/definitions/fan_tile.rs`): the stock, the type(Courier, the default, so left unwritten), the shell's roles, and a pictogramfor each view and act by its id. Money's tables have no Plus doors and nocommands, so the tile names no door (an empty map is left unwritten, as thecore leaves it) and its acts are the shell's own. A picture the tile namedbefore and names no longer leaves the folder. Then the Worker's kit module iswritten again (`pnpm -s --filter @cottondb/business kit`), which carries thetile pictures the object serves.`fan.png` is a proof composite and `*.prompt.txt` provenance: neither ships.Where an act has no key of its own it takes the nearest (`NEAREST`, each withits reason): every tile the Money fan deals has a pictogram."""import hashlibimport jsonimport pathlibimport shutilimport structimport subprocessimport sysfrom tile_words import words_ofHERE = pathlib.Path(__file__).resolve().parentROOT = HERE.parentTOOL = ROOT / 'crates/cotton-core/kits/personal/tools/money'STOCK = ('tile-blank', (474, 696))PICTOGRAM = (300, 300)# The shell's own tiles, by role.ROLES = {'list': 'list', 'new_list': 'new_list', 'more': 'more'}# The tool's views, by id.VIEWS = {view: view for view in ('past', 'future', 'banks', 'cards', 'statements', 'owed', 'with_person', 'by_person')}# Plus's doors: Money's tables have none (its records are the money engine's).DOORS = {}# Every act the Money fan deals, by id: its tables carry no commands, so these# are the shell's own on a held card and on a list's deck.ACTS = {    'when': 'when',    'group': 'group',    'repeat': 'repeat',    'status': 'status',    'face': 'face',    'bin': 'bin',    'list_set_picture': 'set_picture',    'list_remove_picture': 'remove_picture',}# Acts with no key of their own, and the key each takes.NEAREST = {    'list_rename': 'list',  # renaming a list is the list itself    'list_move_earlier': 'repeat',  # the turning arrows are reordering    'list_move_later': 'repeat',  # the turning arrows are reordering    'list_remove': 'bin',  # Money has no remove key: taking a list off is the bin    'list_member_earlier': 'repeat',  # a card moved along the list is a reorder    'list_member_later': 'repeat',  # a card moved along the list is a reorder    'list_member_remove': 'bin',  # Money has no remove key: a card off the list is the bin}def png_size(path):    data = path.read_bytes()    if data[:8] != b'\x89PNG\r\n\x1a\n' or data[12:16] != b'IHDR':        sys.exit(f'{path} is no PNG')    width, height, _, colour = struct.unpack('>IIBB', data[16:26])    if colour not in (4, 6):        sys.exit(f'{path} has no alpha: a tile layer is a cut-out')    return width, heightdef main(source):    source = pathlib.Path(source)    pictures = TOOL / 'pictures'    manifest_path = TOOL / 'manifest.json'    manifest = json.loads(manifest_path.read_text())    laid = {}    def lay(key, size):        path = source / f'{key}.png'        if not path.exists():            sys.exit(f'{source} holds no {key}.png')        if png_size(path) != size:            sys.exit(f'{path} is {png_size(path)}, not {size}')        data = path.read_bytes()        sha = hashlib.sha256(data).hexdigest()        target = pictures / f'{sha}.png'        if not target.exists():            shutil.copyfile(path, target)        laid[key] = sha        return {'photo': f'photo:{sha}'}    # Each map by its ids in order, as the core writes the manifest    # (`FanTile`'s maps are BTreeMaps): a package exported again is the same    # bytes as the kit's files (`tests/kit.rs`).    by = lambda *named: dict(sorted({id: lay(key, PICTOGRAM) for names in named for id, key in names.items()}.items()))    # Courier is `TileType`'s default, which the core leaves unwritten    # (`skip_serializing_if`): naming it would be a key no build names back.    tile = {        'stock': lay(STOCK[0], STOCK[1]),        # The words' ink and baselines as the painter set them (`layout.json`).        'words': words_of(source),        'pictures': by(ROLES),        'views': by(VIEWS),        'acts': by(ACTS, NEAREST),        'doors': by(DOORS),    }    # An empty map is left unwritten (`skip_serializing_if`), as the core    # writes it: Money names no door.    tile = {part: value for part, value in tile.items() if value}    # What the tile named before and names no longer leaves the kit; the    # tool's own picture stays.    before = manifest.get('fan_tile') or {}    named_before = set()    for part in ('pictures', 'views', 'acts', 'doors'):        named_before |= {photo['photo'] for photo in (before.get(part) or {}).values()}    if before.get('stock'):        named_before.add(before['stock']['photo'])    keep = {photo['photo'] for photo in [tile['stock'], *[p for part in ('pictures', 'views', 'acts', 'doors') for p in tile.get(part, {}).values()]]}    keep.add((manifest.get('picture') or {}).get('photo'))    for gone in sorted(named_before - keep):        path = pictures / f'{gone.removeprefix("photo:")}.png'        if path.exists():            path.unlink()            print(f'removed {path.name}')    # The tile stands where the core writes it (`Tool`'s field order): after    # the picture and any card stock, just before the tables.    out = {}    for key, value in manifest.items():        if key == 'fan_tile':            continue        if key == 'tables':            out['fan_tile'] = tile        out[key] = value    if 'fan_tile' not in out:        out['fan_tile'] = tile    manifest_path.write_text(json.dumps(out, indent=2, ensure_ascii=False) + '\n')    for key, sha in sorted(laid.items()):        print(f'{key}.png -> pictures/{sha}.png')    size = sum((pictures / f'{sha}.png').stat().st_size for sha in set(laid.values()))    print(f'{len(set(laid.values()))} pictures, {size // 1024} KB, named by {manifest_path.relative_to(ROOT)}')    # The Worker serves the tile pictures from its own kit module.    try:        subprocess.run(['pnpm', '-s', '--filter', '@cottondb/business', 'kit'], cwd=ROOT, check=True)    except (OSError, subprocess.CalledProcessError) as error:        sys.exit(f'the Worker kit module was not written ({error}): run `pnpm -s --filter @cottondb/business kit`')if __name__ == '__main__':    if len(sys.argv) != 2:        sys.exit('usage: python3 scripts/import-money-tiles.py <layers directory>')    main(sys.argv[1])