Cotton code
187 lines · 7.6 KB · PythonRaw
#!/usr/bin/env python3"""Lay Cotton Music's fan tiles into its kit, as data.    python3 scripts/import-music-tiles.py <layers directory>The hi-fi faceplate (Round 25, treatment A, 8 Nov 2026): one wordless tilestock, `tile-blank.png` (474 x 696, brushed hi-fi aluminium with an empty palelegend field, alpha outside its silhouette), and one isolated backlit creamsymbol per key, each a centred 300 x 300 cut-out (`<key>.png`), painted withCodex (`apps25-tiles-layers/music`, with `layout.json`, `validation.json` and`notes.md`). No word or numeral is on any of them: the phone types the nameand the count live, on the letterboard.Each picture goes into the Music 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`, written, as Cinemas does), the shell's roles, and a pictogramfor each view, act and Plus door by its id. Acts are one map by id: thetool's own acts, its tables' commands (song, music_album, artist) and theshell's. A picture the tile named before and names no longer leaves thefolder. Then the Worker's kit module is written again (`pnpm -s --filter@cottondb/business kit`), which carries the tile pictures the object serves.`fan.png` is a proof composite, `sources.png` a reference sheet and`*.prompt.txt` provenance: none ships.Where an act has no key of its own it takes the nearest (`NEAREST`, each withits reason): every tile the Music 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/music'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 ('listening', 'albums', 'artists', 'songs', 'favourites', 'recently_added', 'on_phone')}# Plus's doors on the song, album and artist decks (each table's create), by id.DOORS = {'files': 'files', 'folder': 'folder'}# Every act the Music fan deals, by id: the tool's own acts, a song's, an# album's and an artist's commands, the shell's own on a held card and on a# list's deck.ACTS = {    'music_keep_everything': 'music_keep_everything',    'account_sign_in': 'account_sign_in',    'account_back_up': 'account_back_up',    'account_sign_out': 'account_sign_out',    'export_library': 'export_library',    'play': 'play',    'shuffle': 'shuffle',    'play_next': 'play_next',    'add_to_queue': 'add_to_queue',    'favourite': 'favourite',    'unfavourite': 'unfavourite',    'find_lyrics': 'find_lyrics',    'find_details': 'find_details',    'keep_on_phone': 'keep_on_phone',    'remove_download': 'remove_download',    '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 opposed arrows are reordering    'list_move_later': 'repeat',  # the opposed arrows are reordering    'list_remove': 'bin',  # Music 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',  # Music 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()))    # The letterboard is not `TileType`'s default (Courier), so it is written.    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),    }    # An empty map is left unwritten (`skip_serializing_if`), as the core    # writes it.    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-music-tiles.py <layers directory>')    main(sys.argv[1])