aboutsummaryrefslogtreecommitdiffhomepage
path: root/tools/build_logo_assets.py
blob: c6fc27ffa0ec2ca1c521e6cdb44feaf5f2f44335 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
#!/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 re
import shutil
import subprocess
import tempfile
import xml.etree.ElementTree as ET

from PIL import Image, ImageColor


ROOT = Path(__file__).resolve().parents[1]
LOGO_DIR = ROOT / "logos"
RASTER_DIR = LOGO_DIR / "raster"
FAVICON_DIR = LOGO_DIR / "favicon"
LIBRARY_VERSION = 2
SIZES = (16, 32, 48, 64, 128, 256, 512, 1024)
FAVICON_SIZES = (16, 32, 48)

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_svg(magick: str, source: Path, target: Path, size: int) -> 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",
        f"PNG32:{target}",
    ]
    subprocess.run(command, check=True)


def gradient_color(stops: list[tuple[float, tuple[int, int, int]]], position: float) -> tuple[int, int, int]:
    for index, (offset, color) in enumerate(stops[1:], start=1):
        if position <= offset:
            previous_offset, previous_color = stops[index - 1]
            span = offset - previous_offset
            amount = 0 if span == 0 else (position - previous_offset) / span
            return tuple(round(start + ((end - start) * amount)) for start, end in zip(previous_color, color))
    return stops[-1][1]


def render_metallic(magick: str, source: Path, target: Path, size: int, fmt: str) -> None:
    """Render the metallic gradients that ImageMagick's SVG delegate drops."""
    namespace = "{http://www.w3.org/2000/svg}"
    root = ET.parse(source).getroot()
    gradients = {
        gradient.attrib["id"]: [
            (
                float(stop.attrib.get("offset", "0").removesuffix("%"))
                / (100 if stop.attrib.get("offset", "0").endswith("%") else 1),
                ImageColor.getrgb(stop.attrib["stop-color"]),
            )
            for stop in gradient.findall(f"{namespace}stop")
        ]
        for gradient in root.findall(f".//{namespace}linearGradient")
    }
    canvas = Image.new("RGBA", (size, size), (0, 0, 0, 0))

    with tempfile.TemporaryDirectory(prefix="pw-logo-") as temporary_directory:
        temporary = Path(temporary_directory)
        for index, path in enumerate(root.findall(f"{namespace}path")):
            match = re.fullmatch(r"url\(#([^)]+)\)", path.attrib.get("fill", ""))
            if match is None or match.group(1) not in gradients:
                raise ValueError(f"Metallic path has no recognized gradient: {source.name}")

            mask_svg = temporary / f"mask-{index}.svg"
            mask_png = temporary / f"mask-{index}.png"
            mask_svg.write_text(
                '<svg xmlns="http://www.w3.org/2000/svg" viewBox="'
                + root.attrib["viewBox"]
                + '"><path fill="#fff" d="'
                + path.attrib["d"]
                + '"/></svg>',
                encoding="utf-8",
            )
            render_svg(magick, mask_svg, mask_png, size)

            mask = Image.open(mask_png).convert("RGBA").getchannel("A")
            solid_bounds = mask.point(lambda value: 255 if value >= 128 else 0).getbbox()
            if solid_bounds is None:
                raise ValueError(f"Metallic path rendered empty: {source.name}")
            top, bottom = solid_bounds[1], solid_bounds[3]
            height = max(bottom - top - 1, 1)
            rows = []
            for y in range(size):
                position = min(1.0, max(0.0, (y - top) / height))
                rows.append(gradient_color(gradients[match.group(1)], position))
            gradient = Image.new("RGB", (1, size))
            gradient.putdata(rows)
            layer = gradient.resize((size, size)).convert("RGBA")
            layer.putalpha(mask)
            canvas.alpha_composite(layer)

    target.parent.mkdir(parents=True, exist_ok=True)
    if fmt == "png":
        canvas.save(target, format="PNG")
    else:
        with tempfile.TemporaryDirectory(prefix="pw-logo-") as temporary_directory:
            png = Path(temporary_directory) / "metallic.png"
            canvas.save(png, format="PNG")
            subprocess.run(
                [magick, str(png), "-define", "webp:lossless=true", str(target)],
                check=True,
            )


def render(magick: str, source: Path, target: Path, size: int, fmt: str) -> None:
    target.parent.mkdir(parents=True, exist_ok=True)
    if source.stem == "packet-warriors-metallic":
        render_metallic(magick, source, target, size, fmt)
        return
    if fmt == "png":
        render_svg(magick, source, target, size)
        return
    subprocess.run(
        [
            magick,
            "-background",
            "none",
            "-density",
            "384",
            str(source),
            "-resize",
            f"{size}x{size}",
            "-gravity",
            "center",
            "-extent",
            f"{size}x{size}",
            "-strip",
            "-define",
            "webp:lossless=true",
            str(target),
        ],
        check=True,
    )


def build_favicon_package(magick: str) -> None:
    source = FAVICON_DIR / "packet-warriors-favicon.svg"
    pngs = []
    for size in FAVICON_SIZES:
        target = FAVICON_DIR / f"favicon-{size}x{size}.png"
        render_svg(magick, source, target, size)
        pngs.append(target)

    render_svg(
        magick,
        source,
        FAVICON_DIR / "apple-touch-icon-180x180.png",
        180,
    )
    subprocess.run(
        [magick, *(str(png) for png in pngs), "-strip", str(FAVICON_DIR / "favicon.ico")],
        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"):
                filename = f"{source.stem}-{size}x{size}.{fmt}"
                relative = Path("logos") / "raster" / fmt / str(size) / filename
                render(magick, source, ROOT / relative, size, fmt)
                raster[str(size)][fmt] = relative.as_posix()
        asset["raster"] = raster

    build_favicon_package(magick)

    payload = {
        "version": LIBRARY_VERSION,
        "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()