Files
Yuriy PanovandClaude Opus 5.5 4c978efa80 Split the shared code into a core module
The Yandex Music client, the player, the app state and the stores move from the
TV app to :core (it.panov.musyx.*), so a phone app can build on them. The TV app
becomes :tv with the same application id. CoverHues, SessionPlayer and the
strings the state layer shows move with them; LRCLIB's user agent is set by
each app.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 10:07:21 +06:00

135 lines
5.6 KiB
Python

#!/usr/bin/env python3
"""Converts the Lucide SVGs in assets/icons to Android vector drawables (res/drawable/ic_<name>.xml).
Lucide draws everything in `currentColor`. The drawables keep that idea: every stroke and fill
is plain white, which Compose's `Icon(tint = ...)` replaces with a theme token, so no design
colour is baked in. Path data is re-tokenised so arc flags and packed numbers are unambiguous.
Usage: python3 tool/svg_to_vector.py [assets/icons] [tv/src/main/res/drawable]
"""
import re
import sys
import xml.etree.ElementTree as ET
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
SVG = "{http://www.w3.org/2000/svg}"
INK = "@android:color/white"
ARGS = {"m": 2, "l": 2, "h": 1, "v": 1, "c": 6, "s": 4, "q": 4, "t": 2, "a": 7, "z": 0}
NUMBER = re.compile(r"[-+]?(?:\d+\.?\d*|\.\d+)(?:[eE][-+]?\d+)?")
def fmt(v):
s = f"{float(v):.3f}".rstrip("0").rstrip(".")
return "0" if s == "-0" else s
def normalise(d):
"""Re-emits SVG path data with every command and argument separated by spaces."""
out, i, cmd, args = [], 0, None, []
while i < len(d):
ch = d[i]
if ch.isspace() or ch == ",":
i += 1
elif ch.isalpha():
cmd = ch
out.append(ch)
args = []
i += 1
else:
if cmd is None:
raise ValueError(f"number before command in {d!r}")
n = ARGS[cmd.lower()]
# Arc flags are single digits and may be packed against the next number.
if cmd.lower() == "a" and len(args) % 7 in (3, 4):
tok = ch
else:
m = NUMBER.match(d, i)
if not m:
raise ValueError(f"bad path data at {d[i:]!r}")
tok = m.group()
args.append(tok)
out.append(fmt(tok))
i += len(tok)
if n and len(args) % n == 0 and cmd in "Mm":
# Extra pairs after a moveto are implicit linetos.
cmd = "L" if cmd == "M" else "l"
return " ".join(out)
def shape_to_path(el):
tag = el.tag.removeprefix(SVG)
a = {k: float(v) for k, v in el.attrib.items() if k in ("cx", "cy", "r", "x", "y", "width", "height", "rx", "ry", "x1", "y1", "x2", "y2")}
if tag == "path":
return normalise(el.attrib["d"])
if tag == "circle":
cx, cy, r = a["cx"], a["cy"], a["r"]
return f"M {fmt(cx - r)} {fmt(cy)} a {fmt(r)} {fmt(r)} 0 1 0 {fmt(2 * r)} 0 a {fmt(r)} {fmt(r)} 0 1 0 {fmt(-2 * r)} 0 Z"
if tag == "line":
return f"M {fmt(a['x1'])} {fmt(a['y1'])} L {fmt(a['x2'])} {fmt(a['y2'])}"
if tag in ("polyline", "polygon"):
nums = NUMBER.findall(el.attrib["points"])
pts = [f"{fmt(nums[k])} {fmt(nums[k + 1])}" for k in range(0, len(nums), 2)]
return "M " + " L ".join(pts) + (" Z" if tag == "polygon" else "")
if tag == "rect":
x, y, w, h = a.get("x", 0), a.get("y", 0), a["width"], a["height"]
rx = a.get("rx", a.get("ry", 0))
ry = a.get("ry", rx)
if not rx:
return f"M {fmt(x)} {fmt(y)} h {fmt(w)} v {fmt(h)} h {fmt(-w)} Z"
return (
f"M {fmt(x + rx)} {fmt(y)} h {fmt(w - 2 * rx)} a {fmt(rx)} {fmt(ry)} 0 0 1 {fmt(rx)} {fmt(ry)} "
f"v {fmt(h - 2 * ry)} a {fmt(rx)} {fmt(ry)} 0 0 1 {fmt(-rx)} {fmt(ry)} "
f"h {fmt(-(w - 2 * rx))} a {fmt(rx)} {fmt(ry)} 0 0 1 {fmt(-rx)} {fmt(-ry)} "
f"v {fmt(-(h - 2 * ry))} a {fmt(rx)} {fmt(ry)} 0 0 1 {fmt(rx)} {fmt(-ry)} Z"
)
raise ValueError(f"unsupported element <{tag}>")
def convert(svg_path):
root = ET.parse(svg_path).getroot()
vb = root.attrib["viewBox"].split()
inherited = {k: root.attrib.get(k) for k in ("fill", "stroke", "stroke-width", "stroke-linecap", "stroke-linejoin")}
lines = [
'<?xml version="1.0" encoding="utf-8"?>',
f"<!-- Lucide {svg_path.stem} (ISC, assets/icons/LICENSE.txt). Generated by tool/svg_to_vector.py; tint it in code. -->",
'<vector xmlns:android="http://schemas.android.com/apk/res/android"',
f' android:width="{fmt(vb[2])}dp"',
f' android:height="{fmt(vb[3])}dp"',
f' android:viewportWidth="{fmt(vb[2])}"',
f' android:viewportHeight="{fmt(vb[3])}">',
]
for el in root.iter():
if el is root:
continue
attrs = {**inherited, **{k: v for k, v in el.attrib.items() if k in inherited}}
lines.append(" <path")
lines.append(f' android:pathData="{shape_to_path(el)}"')
if attrs["fill"] not in (None, "none"):
lines.append(f' android:fillColor="{INK}"')
if attrs["stroke"] not in (None, "none"):
lines.append(f' android:strokeColor="{INK}"')
lines.append(f' android:strokeWidth="{fmt(attrs["stroke-width"] or 1)}"')
if attrs["stroke-linecap"]:
lines.append(f' android:strokeLineCap="{attrs["stroke-linecap"]}"')
if attrs["stroke-linejoin"]:
lines.append(f' android:strokeLineJoin="{attrs["stroke-linejoin"]}"')
lines[-1] += " />"
lines.append("</vector>")
return "\n".join(lines) + "\n"
def main(src, dst):
src, dst = Path(src), Path(dst)
dst.mkdir(parents=True, exist_ok=True)
for svg in sorted(src.glob("*.svg")):
name = "ic_" + svg.stem.replace("-", "_")
(dst / f"{name}.xml").write_text(convert(svg))
if __name__ == "__main__":
main(
sys.argv[1] if len(sys.argv) > 1 else ROOT / "assets/icons",
sys.argv[2] if len(sys.argv) > 2 else ROOT / "tv/src/main/res/drawable",
)