Files
proton-drive-linux/scripts/render-branding.py
T
2026-11-18 01:42:13 +01:00

274 lines
12 KiB
Python
Executable File

#!/usr/bin/env python3
"""Render the vector branding into desktop, Android, iOS and Windows assets.
Kept identical across the suite; each checkout renders independently.
"""
import argparse
from pathlib import Path
import re
import shutil
import subprocess
import tempfile
import xml.etree.ElementTree as ET
SVG = "{http://www.w3.org/2000/svg}"
ANDROID = "{http://schemas.android.com/apk/res/android}"
AAPT = "{http://schemas.android.com/aapt}"
ET.register_namespace("", SVG[1:-1])
ET.register_namespace("android", ANDROID[1:-1])
ET.register_namespace("aapt", AAPT[1:-1])
HEADER = '<?xml version="1.0" encoding="utf-8"?>\n'
GENERATED = '<!-- Generated by scripts/render-branding.py; edit images/logo.svg. -->\n'
ROOT = Path(__file__).resolve().parent.parent
BACKGROUND = "#F4F0FA"
def run(*args, data=None):
return subprocess.run(args, input=data, stdout=subprocess.PIPE, check=True).stdout
def render(svg, size, *, opaque=False):
png = run("rsvg-convert", "-w", str(size), data=svg.encode())
options = ["-background", BACKGROUND, "-alpha", "remove", "-alpha", "off"] if opaque else []
return run("magick", "-", *options, "-strip", "PNG:-", data=png)
def shape_path(node):
"""Use the same paths on Android, including rounded rectangles and circles."""
tag = node.tag.removeprefix(SVG)
a = node.attrib
if tag == "path":
return a["d"]
if tag == "circle":
x, y, r = (float(a[k]) for k in ("cx", "cy", "r"))
return f"M{x-r:g} {y:g}a{r:g} {r:g} 0 1 0 {2*r:g} 0a{r:g} {r:g} 0 1 0 {-2*r:g} 0Z"
if tag == "rect":
x, y = float(a.get("x", 0)), float(a.get("y", 0))
w, h = float(a["width"]), float(a["height"])
rx = min(float(a.get("rx", a.get("ry", 0))), w / 2)
ry = min(float(a.get("ry", a.get("rx", 0))), h / 2)
if not rx or not ry:
return f"M{x:g} {y:g}h{w:g}v{h:g}h{-w:g}Z"
return (f"M{x+rx:g} {y:g}H{x+w-rx:g}a{rx:g} {ry:g} 0 0 1 {rx:g} {ry:g}"
f"V{y+h-ry:g}a{rx:g} {ry:g} 0 0 1 {-rx:g} {ry:g}"
f"H{x+rx:g}a{rx:g} {ry:g} 0 0 1 {-rx:g} {-ry:g}"
f"V{y+ry:g}a{rx:g} {ry:g} 0 0 1 {rx:g} {-ry:g}Z")
raise ValueError(f"Unsupported SVG shape: {tag}")
def color(value):
if value == "none":
return "#00000000"
if re.fullmatch(r"#[0-9a-fA-F]{6}", value):
return "#FF" + value[1:]
raise ValueError(f"Unsupported SVG color: {value}")
def xml(element):
ET.indent(element, space=" ")
return HEADER + GENERATED + ET.tostring(element, encoding="unicode") + "\n"
class Artwork:
def __init__(self, master):
if master.attrib.get("viewBox") != "0 0 256 256":
raise ValueError("The master must use the 256-unit vector grid")
self.defs = master.find(f"{SVG}defs")
self.mark = master.find(f"{SVG}g[@id='mark']")
if self.defs is None or self.mark is None or not list(self.mark):
raise ValueError("The master needs defs and a nonempty mark group")
self.gradients = {g.attrib["id"]: g for g in self.defs.findall(f"{SVG}linearGradient")}
self.clips = {g.attrib["id"]: g for g in self.defs.findall(f"{SVG}clipPath")}
self.svg_defs = ET.tostring(self.defs, encoding="unicode")
self.svg_mark = ET.tostring(self.mark, encoding="unicode")
def paint(self, node, name, value):
if not value.startswith("url(#"):
node.set(ANDROID + name, color(value))
return
gradient = self.gradients[value[5:-1]]
if gradient.attrib.get("gradientUnits") != "userSpaceOnUse":
raise ValueError("Android gradients must use userSpaceOnUse")
attr = ET.SubElement(node, AAPT + "attr", {"name": "android:" + name})
out = ET.SubElement(attr, "gradient", {
ANDROID + "type": "linear",
**{ANDROID + dst: gradient.attrib[src] for src, dst in
(("x1", "startX"), ("y1", "startY"), ("x2", "endX"), ("y2", "endY"))},
})
for stop in gradient:
ET.SubElement(out, "item", {
ANDROID + "offset": stop.attrib.get("offset", "0"),
ANDROID + "color": color(stop.attrib["stop-color"]),
})
def android_node(self, source, parent, monochrome):
tag = source.tag.removeprefix(SVG)
a = source.attrib
if tag not in {"g", "path", "rect", "circle"}:
raise ValueError(f"Unsupported artwork element: {tag}")
supported = {"id", "transform", "clip-path"}
if tag != "g":
supported |= {"d", "x", "y", "width", "height", "rx", "ry", "cx", "cy", "r",
"fill", "fill-rule", "fill-opacity", "opacity", "stroke", "stroke-width",
"stroke-opacity", "stroke-linecap", "stroke-linejoin"}
if set(a) - supported:
raise ValueError(f"Unsupported {tag} attributes: {set(a) - supported}")
if "transform" in a:
match = re.fullmatch(r"translate\(\s*([-\d.]+)[ ,]+([-\d.]+)\s*\)", a["transform"])
if not match:
raise ValueError("Only explicit x/y translation is supported")
parent = ET.SubElement(parent, "group", {
ANDROID + "translateX": match[1], ANDROID + "translateY": match[2],
})
if "clip-path" in a:
clip = self.clips[a["clip-path"][5:-1]]
parent = ET.SubElement(parent, "group")
ET.SubElement(parent, "clip-path", {
ANDROID + "pathData": " ".join(shape_path(s) for s in clip),
})
if tag == "g":
for child in source:
self.android_node(child, parent, monochrome)
return
fill = a.get("fill", "#000000")
if monochrome and fill == "none":
return # Bevel highlights do not belong in the themed silhouette.
node = ET.SubElement(parent, "path", {
ANDROID + "pathData": shape_path(source),
ANDROID + "fillType": "evenOdd" if a.get("fill-rule") == "evenodd" else "nonZero",
})
self.paint(node, "fillColor", "#FFFFFF" if monochrome else fill)
if monochrome:
return
opacity = float(a.get("opacity", 1))
node.set(ANDROID + "fillAlpha", f'{opacity * float(a.get("fill-opacity", 1)):g}')
if "stroke" in a:
self.paint(node, "strokeColor", a["stroke"])
node.set(ANDROID + "strokeWidth", a.get("stroke-width", "1"))
node.set(ANDROID + "strokeAlpha", f'{opacity * float(a.get("stroke-opacity", 1)):g}')
for src, dst in (("stroke-linecap", "strokeLineCap"), ("stroke-linejoin", "strokeLineJoin")):
if src in a:
node.set(ANDROID + dst, a[src])
def vector(self, size=108, scale=.25, *, monochrome=False):
# The 256-unit canvas maps to 64dp; all painted corners stay inside
# the adaptive icon's central safe circle, including the copper rim.
root = ET.Element("vector", {
ANDROID + "width": f"{size}dp", ANDROID + "height": f"{size}dp",
ANDROID + "viewportWidth": str(size), ANDROID + "viewportHeight": str(size),
})
shift = size / 2 - 128 * scale
group = ET.SubElement(root, "group", {
ANDROID + "scaleX": str(scale), ANDROID + "scaleY": str(scale),
ANDROID + "translateX": str(shift), ANDROID + "translateY": str(shift),
})
self.android_node(self.mark, group, monochrome)
return xml(root).encode()
def ios(self):
return HEADER + GENERATED + f'''<svg xmlns="http://www.w3.org/2000/svg" width="1024" height="1024" viewBox="0 0 256 256">
{self.svg_defs}
<rect width="256" height="256" fill="{BACKGROUND}"/>
{self.svg_mark}
</svg>
'''
def banner(self):
return HEADER + GENERATED + f'''<svg xmlns="http://www.w3.org/2000/svg" width="640" height="360" viewBox="0 0 320 180">
{self.svg_defs}
<rect width="320" height="180" fill="{BACKGROUND}"/>
<g transform="translate(8 24) scale(.5)">{self.svg_mark}</g>
<g fill="#35245D" font-family="DejaVu Sans">
<text x="140" y="82" font-size="22">Proton</text>
<text x="138" y="115" font-size="30" font-weight="bold">Stream</text>
</g>
</svg>
'''
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--check", action="store_true", help="Verify outputs without writing files")
args = parser.parse_args()
for command in ("rsvg-convert", "magick"):
if not shutil.which(command):
parser.error(f"{command} is required")
source = ROOT / "images/logo.svg"
master = ET.parse(source).getroot()
app = master.attrib["data-app"]
if app not in {"drive", "stream", "gallery"}:
parser.error("Unknown data-app in images/logo.svg")
art = Artwork(master)
desktop = source.read_bytes()
outputs = {}
if app in {"drive", "stream"}:
slug = "proton-drive-linux" if app == "drive" else "proton-stream"
outputs[f"packaging/io.narl.{slug}.svg"] = desktop
if app == "drive":
cover = ET.parse(ROOT / "images/cover.svg").getroot()
slot = cover.find(f"{SVG}g[@id='app-logo']")
if slot is None:
raise ValueError("The cover needs an app-logo group")
for child in list(slot):
slot.remove(child)
slot.append(ET.fromstring(art.svg_defs))
slot.append(ET.fromstring(art.svg_mark))
cover_svg = xml(cover)
outputs["images/cover.svg"] = cover_svg.encode()
outputs["images/cover.png"] = render(cover_svg, 1920)
if app in {"stream", "gallery"}:
res = "android/app/src/main/res/drawable/"
outputs[res + "ic_launcher_foreground.xml"] = art.vector()
outputs[res + "ic_launcher_monochrome.xml"] = art.vector(monochrome=True)
# A full-bleed neutral surface keeps the violet object legible under
# every launcher mask. The foreground retains its own copper depth.
background = ET.Element("vector", {
ANDROID + "width": "108dp", ANDROID + "height": "108dp",
ANDROID + "viewportWidth": "108", ANDROID + "viewportHeight": "108",
})
ET.SubElement(background, "path", {
ANDROID + "fillColor": color(BACKGROUND), ANDROID + "pathData": "M0 0H108V108H0Z",
})
outputs[res + "ic_launcher_background.xml"] = xml(background).encode()
if app == "gallery":
outputs["images/icon-512.png"] = render(desktop.decode(), 512)
outputs["android/app/src/main/res/drawable/ic_gallery.xml"] = art.vector(256, 1)
if app == "stream":
outputs["android/app/src/main/res/drawable/ic_notification_stream.xml"] = art.vector(24, 24/256, monochrome=True)
outputs["crates/pstr-app/assets/icon-256.png"] = render(desktop.decode(), 256)
ios = art.ios()
outputs["ios/ProtonStream/Resources/AppIcon.svg"] = ios.encode()
outputs["ios/ProtonStream/Resources/Assets.xcassets/AppIcon.appiconset/AppIcon-1024.png"] = render(ios, 1024, opaque=True)
with tempfile.TemporaryDirectory(prefix="proton-icons-") as temp:
files = []
for size in (16, 24, 32, 48, 64, 128, 256):
path = Path(temp) / f"{size}.png"
path.write_bytes(render(desktop.decode(), size))
files.append(str(path))
outputs["packaging/windows/proton-stream.ico"] = run("magick", *files, "-strip", "ICO:-")
if not shutil.which("fc-match"):
parser.error("fontconfig is required to render the Android TV banner")
if "DejaVu Sans" not in run("fc-match", "-f", "%{family}", "DejaVu Sans").decode():
parser.error("DejaVu Sans is required to render the Android TV banner")
outputs["android/app/src/main/res/drawable-nodpi/tv_banner.png"] = render(art.banner(), 640, opaque=True)
stale = []
for relative, data in outputs.items():
target = ROOT / relative
if target.exists() and target.read_bytes() == data:
continue
if args.check:
stale.append(relative)
else:
target.parent.mkdir(parents=True, exist_ok=True)
target.write_bytes(data)
print(f"wrote {relative}")
if stale:
parser.exit(1, "Branding assets need regeneration:\n" + "\n".join(stale) + "\n")
print(f"{'Verified' if args.check else 'Rendered'} {len(outputs)} assets from images/logo.svg")
if __name__ == "__main__":
main()