#!/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
import os
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 = '\n'
GENERATED = '\n'
ROOT = Path(__file__).resolve().parent.parent
BACKGROUND = "#F4F0FA"
# Adaptive icon plate: lit from the top left like the copper rim.
PLATE = (("0", "#3A2A6E"), (".55", "#231946"), ("1", "#140E2B"))
# The plate's light, in the 108dp adaptive canvas.
PLATE_CENTER, PLATE_RADIUS = (40, 32), 96
# A launcher shows the central 72dp of that canvas; the mark fills 64dp of it.
ADAPTIVE_VISIBLE, ADAPTIVE_MARK = 72, 64
def run(*args, data=None, env=None):
return subprocess.run(args, input=data, stdout=subprocess.PIPE, check=True, env=env).stdout
def render(svg, size, *, opaque=False, env=None):
png = run("rsvg-convert", "-w", str(size), data=svg.encode(), env=env)
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):
# The same plate and crop as an Android launcher icon, so the two
# phones show one icon: the visible 72dp window becomes the 256-unit
# canvas, and the mark keeps its 64dp share of it.
unit = 256 / ADAPTIVE_VISIBLE
inset = (108 - ADAPTIVE_VISIBLE) / 2
cx, cy = ((v - inset) * unit for v in PLATE_CENTER)
stops = "".join(f'' for o, c in PLATE)
scale = ADAPTIVE_MARK / ADAPTIVE_VISIBLE
return HEADER + GENERATED + f'''
'''
def banner(self):
return HEADER + GENERATED + f'''
'''
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)
if app in {"drive", "stream"} and any("clip-path" in node.attrib for node in art.mark.iter()):
# The master ships as the desktop icon, and QtSvg, which Qt shells and
# launchers draw it with, ignores clip-path: whatever it was cutting
# spills out. Cut the shape in its own path instead.
parser.error("images/logo.svg ships as the desktop icon; its mark cannot use clip-path")
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)
# Launchers mask the background into a circle or squircle. A light
# surface turned into a pale disc around the mark on dark home
# screens, so the plate is a deep violet that frames the copper rim
# and lets the mask read as part of the icon.
background = ET.Element("vector", {
ANDROID + "width": "108dp", ANDROID + "height": "108dp",
ANDROID + "viewportWidth": "108", ANDROID + "viewportHeight": "108",
})
plate = ET.SubElement(background, "path", {ANDROID + "pathData": "M0 0H108V108H0Z"})
fill = ET.SubElement(plate, AAPT + "attr", {"name": "android:fillColor"})
gradient = ET.SubElement(fill, "gradient", {
ANDROID + "type": "radial", ANDROID + "centerX": str(PLATE_CENTER[0]),
ANDROID + "centerY": str(PLATE_CENTER[1]), ANDROID + "gradientRadius": str(PLATE_RADIUS),
})
for offset, stop in PLATE:
ET.SubElement(gradient, "item", {ANDROID + "offset": offset, ANDROID + "color": color(stop)})
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)
# The mark inside the app: the Library's bar, About, an empty page.
# 64dp, its largest use; lint caps a vector at 200.
outputs["android/app/src/main/res/drawable/ic_stream_mark.xml"] = art.vector(64, .25)
outputs["crates/pstr-app/assets/icon-256.png"] = render(desktop.decode(), 256)
# F-Droid and IzzyOnDroid list the app with this icon.
outputs["fastlane/metadata/android/en-US/images/icon.png"] = render(desktop.decode(), 512)
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:-")
# The banner's name is set in the app's own Inter, and fontconfig sees
# only the bundled files, so no installed font can change the pixels.
with tempfile.TemporaryDirectory(prefix="proton-fonts-") as temp:
conf = Path(temp) / "fonts.conf"
conf.write_text(f"""
{ROOT / "crates/pstr-app/assets/fonts"}{temp}
""")
env = {**os.environ, "FONTCONFIG_FILE": str(conf)}
outputs["android/app/src/main/res/drawable-nodpi/tv_banner.png"] = render(art.banner(), 640, opaque=True, env=env)
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()