#!/usr/bin/env python3"""Write each app's launch screen into its flavour's folder. python3 scripts/gen-launch-screens.py [--objects <directory>] [<flavour> ...]An app whose manifest names a ground (`flavour.json`'s `ground`, a`FaceGround` id; or `launch`, for an app that stands on the shell's paper andlaunches on its icon's ground all the same) launches on that ground as the app itself lays it, fullbleed, with its icon's object alone in the middle, cut out, no tile under it(13 Nov 2026). The splash after it draws the same things at the same places(`SplashOverlay`: `FaceGroundSurface` and `LaunchObject`), so the first framethe app draws is the launch screen again and nothing moves. A `UILaunchScreen`dictionary can only stretch one image, so the launch screen is a storyboard(`scripts/ios-spec-gate.ts` names it), written here with what it draws into`App/Flavours/<flavour>/`: LaunchScreen.storyboard the ground's colour; over it the ground laid, pinned to the screen's top left corner and never scaled; the lamp's glow, where the ground has one, at its place and strength; the object centred on the screen, at its own size Assets.xcassets/ LaunchGround.colorset the tile's mean, under it while it is drawn LaunchSurface.imageset the ground's painted tile (Loom's catalogue) repeated from its top left corner over 480 by 1050 points at three pixels a point, as `FaceGroundSurface` lays it: more than the largest phone's screen. A launch screen does not repeat a sliced image across (measured 13 Nov 2026: it stretched the tile's last column past 341 points), so the ground is laid here LaunchLamp.imageset the lamp's glow (Loom's catalogue), where the ground has a lamp LaunchObject.imageset the app's object cut out of its icon: the painted 1024 px cut-out (`<flavour>-object.png` in `--objects`, Codex, 13 Nov 2026), its soft contact shadow kept, 200 points across (the object itself about 160) at 2x and 3xThe ground's tile and lamp are read from `Face.swift` (`FaceGround.tile`,`FaceGround.lamp`). With `--objects` the cut-outs found there replace theflavours' `LaunchObject`; without it each flavour keeps the one it has. Aflavour with no cut-out launches on its bare ground, and this says so. Run itagain whenever a ground or a cut-out changes: the same inputs write the samefiles. With no flavours named it writes every flavour that names a ground.A FLAT app (`flavour.json`'s `flat`: `{"light": "#RRGGBB", "dark": "#RRGGBB"}`,Cotton Story, 17 Nov 2026) has no painted ground and follows the phone'sappearance: its launch screen is the flat colour, light or dark, and its wordmark centred (`<flavour>-object.png` and `<flavour>-object-dark.png` in`--objects`), with no surface and no lamp."""from __future__ import annotationsimport jsonimport reimport shutilimport sysfrom pathlib importPathimport numpy as npfrom PIL importImageROOT = Path(__file__).resolve().parent.parentFLAVOURS = ROOT / "apps/cotton/App/Flavours"# An app only Android builds keeps its flavour folder beside the Android build (apps/android/app/flavours/<slug>).ANDROID_FLAVOURS = ROOT / "apps/android/app/flavours"def folder_of(flavour: str) -> Path:"""The flavour's folder: the iPhone's, else the Android-only one.""" ios = FLAVOURS / flavourreturn ios if ios.is_dir() ornot (ANDROID_FLAVOURS / flavour).is_dir() else ANDROID_FLAVOURS / flavourFACE = ROOT / "apps/loom/Sources/CottonFaces/Face.swift"MEDIA = ROOT / "apps/loom/Sources/CottonPaper/Media.xcassets"OBJECT_POINTS = 200# the cut-out's square; the painted object spans about 80% of itSURFACE_POINTS = (480, 1050) # more than the largest phone's portrait screen (440 by 956)PIXELS_PER_POINT = 3# a ground's tile and lamp are 3x masters (`FaceGroundKnobs`)STORYBOARD = "LaunchScreen.storyboard"INFO = {"author": "xcode", "version": 1}# No picture here carries a colour profile, as none of Loom's does: the app# draws an untagged picture as sRGB. The launch screen's colour is not theirs# to set: on the iPhone simulator the system shows its launch snapshot of# some apps warmer than the app draws the same picture (its sRGB values read# as Display P3; 13 Nov 2026), alike whether the picture is untagged, tagged# sRGB or stored as Display P3, so a profile buys nothing and is refused.def switch(name: str) -> str: source = FACE.read_text() body = source[source.index(f"public var {name}:") :]return body[: body.index("\n }\n")]def tiles() -> dict[str, str]:return dict(re.findall(r'case \.(\w+): "([\w-]+)"', switch("tile")))def lamps() -> dict[str, tuple[str, tuple[float, float, float, float], float]]: found = {} pattern = ( r'case \.(\w+): FaceGroundLamp\(name: "([\w-]+)", rect: CGRect\(x: (-?[\d.]+), y: (-?[\d.]+), ' r"width: ([\d.]+), height: ([\d.]+)\), strength: ([\d.]+)\)" )for ground, name, x, y, w, h, strength in re.findall(pattern, switch("lamp")): found[ground] = (name, (float(x), float(y), float(w), float(h)), float(strength))return founddef overlaid() -> set[str]:return set(re.findall(r"case \.(\w+): FaceGroundOverlay\(", switch("overlay")))def picture(name: str) -> Path: folder = MEDIA / f"{name}.imageset"return next(p for p in sorted(folder.iterdir()) if p.suffix.lower() in (".jpg", ".jpeg", ".png"))def write_json(path: Path, value: object) -> None: path.parent.mkdir(parents=True, exist_ok=True) path.write_text(json.dumps(value, indent=2) + "\n")def fresh(folder: Path) -> Path:if folder.exists(): shutil.rmtree(folder) folder.mkdir(parents=True)return folderdef colour_set(catalogue: Path, rgb: tuple[float, float, float]) -> None: components = {"red": f"{rgb[0]:.3f}", "green": f"{rgb[1]:.3f}", "blue": f"{rgb[2]:.3f}", "alpha": "1.000"} write_json( catalogue / "LaunchGround.colorset" / "Contents.json", {"colors": [{"idiom": "universal", "color": {"color-space": "srgb", "components": components}}], "info": INFO}, )def flat_colour_set(catalogue: Path, light: tuple[float, float, float], dark: tuple[float, float, float]) -> None:def entry(rgb: tuple[float, float, float], appearance: str | None) -> dict: components = {"red": f"{rgb[0]:.3f}", "green": f"{rgb[1]:.3f}", "blue": f"{rgb[2]:.3f}", "alpha": "1.000"} row = {"idiom": "universal", "color": {"color-space": "srgb", "components": components}}if appearance: row["appearances"] = [{"appearance": "luminosity", "value": appearance}]return row write_json( catalogue / "LaunchGround.colorset" / "Contents.json", {"colors": [entry(light, None), entry(dark, "dark")], "info": INFO}, )def hex_rgb(value: str) -> tuple[float, float, float]: value = value.lstrip("#")return tuple(int(value[k : k + 2], 16) / 255for k in (0, 2, 4))def surface_set(catalogue: Path, source: Path) -> tuple[float, float]:"""The ground laid as `FaceGroundSurface` lays it: the tile repeated from the top left corner, one tile's pixel to the screen's third of a point.""" stale = catalogue / "LaunchTile.imageset"if stale.exists(): shutil.rmtree(stale) folder = fresh(catalogue / "LaunchSurface.imageset") tile = Image.open(source).convert("RGB") width, height = (side * PIXELS_PER_POINT for side in SURFACE_POINTS) laid = Image.new("RGB", (width, height))for y in range(0, height, tile.height):for x in range(0, width, tile.width): laid.paste(tile, (x, y)) laid.save(folder / "LaunchSurface.jpg", quality=90, optimize=True) image = {"filename": "LaunchSurface.jpg", "idiom": "universal", "scale": f"{PIXELS_PER_POINT}x"} write_json(folder / "Contents.json", {"images": [image], "info": INFO})return SURFACE_POINTSdef lamp_set(catalogue: Path, source: Path | None) -> None: folder = catalogue / "LaunchLamp.imageset"if source isNone:if folder.exists(): shutil.rmtree(folder)return fresh(folder)Image.open(source).convert("RGBA").save(folder / "LaunchLamp.png", optimize=True) write_json(folder / "Contents.json", {"images": [{"filename": "LaunchLamp.png", "idiom": "universal", "scale": "3x"}], "info": INFO})def object_set(catalogue: Path, master: Path, dark: Path | None = None) -> None: folder = fresh(catalogue / "LaunchObject.imageset") images = []for source, suffix, appearance in [(master, "", None)] + ([(dark, "-dark", "dark")] if dark else []): cut = Image.open(source).convert("RGBA")if cut.size[0] != cut.size[1]: sys.exit(f"{source}: a cut-out is square, this one is {cut.size}") corners = np.asarray(cut)[[0, 0, -1, -1], [0, -1, 0, -1], 3]if corners.max() != 0: sys.exit(f"{source}: a cut-out's corners are clear, this one's are not (a tile, not a cut-out)")for scale in (2, 3): name = f"LaunchObject{suffix}@{scale}x.png" cut.resize((OBJECT_POINTS * scale, OBJECT_POINTS * scale), Image.LANCZOS).save(folder / name, optimize=True) row = {"filename": name, "idiom": "universal", "scale": f"{scale}x"}if appearance: row["appearances"] = [{"appearance": "luminosity", "value": appearance}] images.append(row) write_json(folder / "Contents.json", {"images": images, "info": INFO})def number(value: float) -> str:return f"{value:.6g}"def storyboard(rgb: tuple[float, float, float], lamp: tuple[float, float, float, float, float] | None, surface: tuple[float, float] | None, has_object: bool) -> str:"""The launch screen: every picture in a view of exactly its own size, so it is drawn one to one and nothing scales it (the launch screen ignores an image view's content mode: measured 13 Nov 2026, a top-left picture in a screen-sized view was squeezed to the screen); the ground's pinned to the screen's top left corner (not the safe area) and clipped by the screen, the lamp's at its offset from that corner, the object's centred.""" views, constraints, images = [], [], []def picture(key: str, name: str, size: tuple[float, float], place: list[tuple[str, float]], alpha: float | None = None) -> None: w, h = size shade = ""if alpha isNoneelse f'alpha="{number(alpha)}" ' views.append( f'<imageView userInteractionEnabled="NO" {shade}contentMode="scaleToFill" image="{name}" ' f'translatesAutoresizingMaskIntoConstraints="NO" id="{key}-pi-c01">' f'<rect key="frame" x="0.0" y="0.0" width="{number(w)}" height="{number(h)}"/>' f'<constraints><constraint firstAttribute="width" constant="{number(w)}" id="{key}-cn-w01"/>' f'<constraint firstAttribute="height" constant="{number(h)}" id="{key}-cn-h01"/></constraints></imageView>' )for n, (attribute, constant) in enumerate(place): constraints.append( f'<constraint firstItem="{key}-pi-c01" firstAttribute="{attribute}" secondItem="Lgr-oo-t01" ' f'secondAttribute="{attribute}" constant="{number(constant)}" id="{key}-cn-{n:03d}"/>' ) images.append(f'<image name="{name}" width="{number(w)}" height="{number(h)}"/>')if surface isnotNone: picture("Lgt", "LaunchSurface", surface, [("leading", 0), ("top", 0)])if lamp isnotNone: x, y, w, h, strength = lamp picture("Lgl", "LaunchLamp", (w, h), [("leading", x), ("top", y)], strength)if has_object: picture("Lgo", "LaunchObject", (OBJECT_POINTS, OBJECT_POINTS), [("centerX", 0), ("centerY", 0)]) indent = "\n " rows = "\n "return f"""<?xml version="1.0" encoding="UTF-8"?><!-- Written by scripts/gen-launch-screens.py: run it again, never edit this. --><document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="23727" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" launchScreen="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES" initialViewController="Lgv-cc-001"> <device id="retina6_12" orientation="portrait" appearance="light"/> <dependencies> <plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="23721"/> <capability name="Named colors" minToolsVersion="9.0"/> <capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/> </dependencies> <scenes> <scene sceneID="Lgs-cn-001"> <objects> <viewController id="Lgv-cc-001" sceneMemberID="viewController"> <view key="view" clipsSubviews="YES" contentMode="scaleToFill" id="Lgr-oo-t01"> <rect key="frame" x="0.0" y="0.0" width="393" height="852"/> <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/> <subviews>{indent}{indent.join(views)} </subviews> <color key="backgroundColor" name="LaunchGround"/> <constraints>{indent}{indent.join(constraints)} </constraints> </view> </viewController> <placeholder placeholderIdentifier="IBFirstResponder" id="Lgf-rr-001" userLabel="First Responder" sceneMemberID="firstResponder"/> </objects> </scene> </scenes> <resources>{rows}{rows.join(images)} <namedColor name="LaunchGround"> <color red="{rgb[0]:.3f}" green="{rgb[1]:.3f}" blue="{rgb[2]:.3f}" alpha="1" colorSpace="custom" customColorSpace="sRGB"/> </namedColor> </resources></document>"""def generate(flavour: str, named: dict[str, str], lit: dict, drifting: set[str], objects: Path | None) -> None: folder = folder_of(flavour) manifest = json.loads((folder / "flavour.json").read_text())if"flat"in manifest: generate_flat(flavour, manifest["flat"], objects)return ground = manifest.get("launch", manifest.get("ground"))if ground isNone: sys.exit(f"{flavour}: its flavour.json names no ground to launch on (launch, or ground)")if ground notin named: sys.exit(f"{flavour}: ground {ground} has no painted tile in FaceGround.tile")if ground in drifting: sys.exit(f"{flavour}: ground {ground} drifts (FaceGround.overlay), which a launch screen cannot draw") catalogue = folder / "Assets.xcassets" tile = picture(named[ground]) pixels = np.asarray(Image.open(tile).convert("RGB")).reshape(-1, 3).astype(float) rgb = tuple(pixels.mean(0) / 255) colour_set(catalogue, rgb) surface = surface_set(catalogue, tile) lamp = Noneif ground in lit: name, (x, y, w, h), strength = lit[ground] lamp_set(catalogue, picture(name)) k = PIXELS_PER_POINT lamp = (x / k, y / k, w / k, h / k, strength)else: lamp_set(catalogue, None) master = objects / f"{flavour}-object.png"if objects elseNoneif master isnotNoneand master.is_file(): object_set(catalogue, master) kept = catalogue / "LaunchObject.imageset" / "LaunchObject@3x.png" has_object = kept.is_file()if has_object:withImage.open(kept) as cut:if np.asarray(cut.convert("RGBA"))[[0, 0, -1, -1], [0, -1, 0, -1], 3].max() != 0: sys.exit(f"{flavour}: its LaunchObject is not a cut-out (its corners are not clear): pass --objects with {flavour}-object.png")if cut.info.get("icc_profile"): sys.exit(f"{flavour}: its LaunchObject carries a colour profile: pass --objects with {flavour}-object.png") (folder / STORYBOARD).write_text(storyboard(rgb, lamp, surface, has_object)) hexed = "#" + "".join(f"{int(c * 255):02X}"for c in rgb) print(f"{flavour}: {ground} {hexed}{' lamp' if lamp else ''}{'' if has_object else ' — NO cut-out: launches on its bare ground'}")def generate_flat(flavour: str, flat: dict[str, str], objects: Path | None) -> None: folder = folder_of(flavour) catalogue = folder / "Assets.xcassets" light, dark = hex_rgb(flat["light"]), hex_rgb(flat["dark"]) flat_colour_set(catalogue, light, dark)for stale in ("LaunchSurface.imageset", "LaunchLamp.imageset", "LaunchTile.imageset"):if (catalogue / stale).exists(): shutil.rmtree(catalogue / stale) master = objects / f"{flavour}-object.png"if objects elseNoneif master isnotNoneand master.is_file(): night = objects / f"{flavour}-object-dark.png" object_set(catalogue, master, night if night.is_file() elseNone) has_object = (catalogue / "LaunchObject.imageset" / "LaunchObject@3x.png").is_file() (folder / STORYBOARD).write_text(storyboard(light, None, None, has_object)) print(f"{flavour}: flat {flat['light']} / {flat['dark']}{'' if has_object else ' — NO word mark'}")def main() -> None: args = sys.argv[1:] objects = Noneif"--objects"in args: k = args.index("--objects") objects = Path(args[k + 1])del args[k : k + 2]ifnot objects.is_dir(): sys.exit(f"{objects} is not a directory") named, lit, drifting = tiles(), lamps(), overlaid() flavours = args or sorted( p.parent.name for p in FLAVOURS.glob("*/flavour.json") if {"ground", "launch", "flat"} & json.loads(p.read_text()).keys() )for flavour in flavours: generate(flavour, named, lit, drifting, objects)if __name__ == "__main__": main()