Cotton code
172 lines · 7.0 KB · PythonRaw
#!/usr/bin/env python3"""Lay Cotton Cinemas' fan tiles into its kit, as data.    python3 scripts/import-cinemas-tiles.py [<layers directory>]The black felt letterboard (Round 19, 6 Nov 2026, the owner's pick): one wordlesstile stock, `tile-blank.png` (474 x 696, its alpha outside the brass frame),and one cream plastic pictogram per key, each a centred 300 x 300 cut-out(`<key>.png`), painted with Codex and cut by the features lane(`cinemas19-letterboard-layers`, with `layout.json` and `notes.md`). No wordor numeral is on any of them: the phone types the name and the count live.Each picture goes into the Cinemas 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(`letterboard`), the shell's roles, and a pictogram for each view, act and Plusdoor by its id. A picture the tile named before and names no longer leavesthe folder. Then the Worker's kit module is written again (`pnpm -s --filter@cottondb/business kit`), which carries the tile pictures the object serves.So the next change is: drop the new PNG into the directory under its key, runthis, push, deploy the Worker. A phone signed in draws it on its next sync,with no new build; before sign-in it draws what its build carries.Where an act has no key of its own it takes the nearest (`NEAREST`, said inthe lane's notes): every tile the Cinemas 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/cinemas'DEFAULT = pathlib.Path('/Volumes/Cotton SSD/lanes/features/out/cinemas19-letterboard-layers')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 ('films', 'series', 'watched', 'all', 'a_to_z', 'on_phone')}# Plus's doors on the film deck (`film.json`'s create), by id.DOORS = {'files': 'add_files', 'folder': 'add_folder', 'find': 'find_film'}# Every act the Cinemas fan deals, by id: a film's, a series', a season's and# an episode's commands, the shell's own on a held card (Group is Add to# list, Bin is Remove) and on a list's deck (Set picture), and the tool's.ACTS = {    'play': 'play',    'play_from_start': 'play_from_start',    'mark_unwatched': 'mark_unwatched',    'find_details': 'find_details',    'keep_on_phone': 'keep',    'keep_series': 'keep_series',    'remove_download': 'remove_download',    'group': 'add_to_list',    'list_set_picture': 'set_picture',    'bin': 'remove',    'cinemas_keep_everything': 'keep_everything',    'cinemas_cellular': 'mobile_data',    'cinemas_budget': 'storage_budget',    'account_sign_in': 'sign_in',    'account_back_up': 'back_up',    'account_sign_out': 'sign_out',}# Acts with no key of their own, and the key each takes.NEAREST = {    'mark_watched': 'watched',  # Watched's tick    'when': 'watched',  # a film's When is the day it was watched    'keep_season': 'keep',  # a season kept as a film is    'list_remove_picture': 'remove',}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()))    tile = {        'stock': lay(STOCK[0], STOCK[1]),        'type': 'letterboard',        # 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),    }    # What is unnamed is left unwritten (`skip_serializing_if`), as the core    # writes it: a layout naming no type's words leaves the type's own.    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[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 after the card stock, where a reader looks for the look.    out = {}    for key, value in manifest.items():        if key == 'fan_tile':            continue        out[key] = value        if key == 'card_stock':            out['fan_tile'] = tile    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__':    main(sys.argv[1] if len(sys.argv) > 1 else DEFAULT)