aboutsummaryrefslogtreecommitdiffhomepage
path: root/tools/build_logo_assets.py
diff options
context:
space:
mode:
Diffstat (limited to 'tools/build_logo_assets.py')
-rw-r--r--tools/build_logo_assets.py129
1 files changed, 129 insertions, 0 deletions
diff --git a/tools/build_logo_assets.py b/tools/build_logo_assets.py
new file mode 100644
index 0000000..1f1abfe
--- /dev/null
+++ b/tools/build_logo_assets.py
@@ -0,0 +1,129 @@
+#!/usr/bin/env python3
+"""Build square PNG and WebP exports for every approved logo SVG."""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+import shutil
+import subprocess
+
+
+ROOT = Path(__file__).resolve().parents[1]
+LOGO_DIR = ROOT / "logos"
+RASTER_DIR = LOGO_DIR / "raster"
+SIZES = (16, 32, 48, 64, 128, 256, 512, 1024)
+
+PRODUCTS = (
+ ("packet-warriors", "Packet Warriors"),
+ ("firefly", "Firefly"),
+ ("xlx-observatory", "XLX Observatory"),
+ ("fwdfix", "FwdFix"),
+ ("gps-clock-dash", "GPS Clock Dash"),
+)
+
+VARIANTS = {
+ "flat-dark": "Flat / dark",
+ "flat-light": "Flat / light",
+ "mono-dark": "Monochrome / dark",
+ "mono-light": "Monochrome / light",
+ "metallic": "Metallic / optional",
+ "icon": "Favicon / app tile",
+}
+
+
+def asset_metadata(source: Path) -> dict[str, object]:
+ for slug, product in PRODUCTS:
+ prefix = f"{slug}-"
+ if source.stem.startswith(prefix):
+ variant = source.stem.removeprefix(prefix)
+ if variant not in VARIANTS:
+ break
+ return {
+ "slug": source.stem,
+ "product": product,
+ "productSlug": slug,
+ "variant": variant,
+ "variantLabel": VARIANTS[variant],
+ "svg": f"logos/{source.name}",
+ "preview": "light" if variant.endswith("light") else "dark",
+ }
+ raise ValueError(f"Unrecognized approved logo filename: {source.name}")
+
+
+def render(magick: str, source: Path, target: Path, size: int, fmt: str) -> None:
+ target.parent.mkdir(parents=True, exist_ok=True)
+ command = [
+ magick,
+ "-background",
+ "none",
+ "-density",
+ "384",
+ str(source),
+ "-resize",
+ f"{size}x{size}",
+ "-gravity",
+ "center",
+ "-extent",
+ f"{size}x{size}",
+ "-strip",
+ ]
+ if fmt == "png":
+ command.append(f"PNG32:{target}")
+ else:
+ command.extend(("-define", "webp:lossless=true", str(target)))
+ subprocess.run(command, check=True)
+
+
+def main() -> None:
+ magick = shutil.which("magick")
+ if magick is None:
+ raise SystemExit("ImageMagick 7 (`magick`) is required to build logo exports.")
+
+ source_assets = [(source, asset_metadata(source)) for source in LOGO_DIR.glob("*.svg")]
+ product_order = {slug: index for index, (slug, _) in enumerate(PRODUCTS)}
+ variant_order = {variant: index for index, variant in enumerate(VARIANTS)}
+ source_assets.sort(
+ key=lambda item: (
+ product_order[str(item[1]["productSlug"])],
+ variant_order[str(item[1]["variant"])],
+ )
+ )
+ sources = [source for source, _ in source_assets]
+ assets = [asset for _, asset in source_assets]
+
+ # These two format trees contain generated files only. Recreate them so
+ # removed or renamed source assets cannot leave stale downloads behind.
+ for fmt in ("png", "webp"):
+ output_dir = RASTER_DIR / fmt
+ if output_dir.exists():
+ shutil.rmtree(output_dir)
+
+ for source, asset in zip(sources, assets, strict=True):
+ raster: dict[str, dict[str, str]] = {}
+ for size in SIZES:
+ raster[str(size)] = {}
+ for fmt in ("png", "webp"):
+ relative = Path("logos") / "raster" / fmt / str(size) / f"{source.stem}.{fmt}"
+ render(magick, source, ROOT / relative, size, fmt)
+ raster[str(size)][fmt] = relative.as_posix()
+ asset["raster"] = raster
+
+ payload = {
+ "version": 1,
+ "canvas": "square-transparent",
+ "sizes": list(SIZES),
+ "assets": assets,
+ }
+ manifest = json.dumps(payload, indent=2) + "\n"
+ RASTER_DIR.mkdir(parents=True, exist_ok=True)
+ (RASTER_DIR / "manifest.json").write_text(manifest, encoding="utf-8")
+ (LOGO_DIR / "logo-library.js").write_text(
+ "window.PW_LOGO_LIBRARY = " + json.dumps(payload, separators=(",", ":")) + ";\n",
+ encoding="utf-8",
+ )
+ print(f"Built {len(assets)} logos in {len(SIZES)} sizes as PNG and WebP.")
+
+
+if __name__ == "__main__":
+ main()