Fichiers
Aleop c3608b3938 Loksi 2026.10.0 (Android 3) : source correspondante
Export du dépôt interne d'Aleop, révision 5fbb921.
2026-10-09 22:14:30 +02:00

386 lignes
21 KiB
Python

#!/usr/bin/env python3
"""Ressources vectorielles Loksi pour Android, GPL-3.0-only.
Tout part des fichiers de la charte adoptée le 28/09/2026 :
- brand/loksi-icon.svg, l'icône sculptée ;
- brand/sources/loksi-logo-{clair,sombre}.svg, icône et mot déjà en tracés ;
- brand/sources/loksi-icon-mono.svg, pour la couche monochrome.
Les SVG sont convertis en VectorDrawable par un convertisseur limité à ce que la
charte emploie : groupes translate et scale, rect arrondi, path, circle, dégradés
linéaires et radiaux. Tout autre élément ou attribut le fait échouer : c'est le
canari de structure. Les filtres (ombres floues) n'existent pas en VectorDrawable,
ils sont retirés et comptés. La géométrie des ombres dures (socle décalé, copie
foncée du symbole) reste. L'icône du lanceur, qui garde ses ombres, est en PNG par
densité, rendue par Chromium (render.mjs).
"""
import re
import xml.etree.ElementTree as ET
from pathlib import Path
NAVY = "#003087"
SVG = "{http://www.w3.org/2000/svg}"
HEADER = ('xmlns:android="http://schemas.android.com/apk/res/android"\n'
' xmlns:aapt="http://schemas.android.com/aapt"')
TRANSFORM = re.compile(r"(?:translate\(([-\d.]+)[ ,]+([-\d.]+)\))?\s*(?:scale\(([-\d.]+)(?:[ ,]+([-\d.]+))?\))?")
# Rotation autour d'un point, seule forme employée par les illustrations de la charte.
ROTATE = re.compile(r"rotate\(([-\d.]+)[ ,]+([-\d.]+)[ ,]+([-\d.]+)\)")
# Attributs admis par élément. Un attribut inconnu est un changement de la charte.
ALLOWED = {
"svg": {"viewBox", "role", "aria-label", "width", "height"},
"g": {"transform", "fill", "filter"},
"rect": {"x", "y", "width", "height", "rx", "fill", "stroke", "stroke-width", "filter", "mask"},
"path": {"d", "fill", "fill-opacity", "fill-rule", "stroke", "stroke-width", "stroke-opacity", "stroke-linecap",
"stroke-linejoin", "transform"},
"circle": {"cx", "cy", "r", "fill"},
}
def number(value):
value = float(value)
return f"{0.0 if abs(value) < 5e-5 else value:.4f}".rstrip("0").rstrip(".")
def argb(color, opacity=1.0):
color = color.strip().upper()
if not re.fullmatch(r"#[0-9A-F]{3}|#[0-9A-F]{6}", color):
raise RuntimeError(f"Couleur SVG non prise en charge : {color}")
if len(color) == 4:
color = "#" + "".join(c * 2 for c in color[1:])
return "#%02X%s" % (round(float(opacity) * 255), color[1:])
def percent(value, default):
value = default if value is None else value
return float(value[:-1]) / 100 if value.endswith("%") else float(value)
def path_bounds(d):
from fontTools.pens.boundsPen import BoundsPen
from fontTools.svgLib.path import parse_path
pen = BoundsPen(None)
parse_path(d, pen)
return pen.bounds
class Converter:
def __init__(self, svg_text, white=False):
self.root = ET.fromstring(svg_text)
self.white = white
self.dropped_filters = 0
self.gradients = {}
for tag in ("linearGradient", "radialGradient"):
for node in self.root.iter(SVG + tag):
stops = [(float(s.get("offset", "0")), argb(s.get("stop-color"), s.get("stop-opacity", "1")))
for s in node.findall(SVG + "stop")]
self.gradients[node.get("id")] = (tag, node.attrib, stops)
def paint(self, attribute, value, bounds):
"""Couleur ou dégradé VectorDrawable pour fillColor ou strokeColor."""
if value.startswith("url(#"):
if self.white:
return f'android:{attribute}="#FFFFFFFF"', ""
tag, attrib, stops = self.gradients[value[5:-1]]
x0, y0, x1, y1 = bounds
w, h = x1 - x0, y1 - y0
if attrib.get("gradientUnits") == "userSpaceOnUse":
# Coordonnées absolues dans le repère de la forme, comme en VectorDrawable.
if tag != "linearGradient":
raise RuntimeError("Dégradé radial en userSpaceOnUse non pris en charge")
geometry = " ".join(f'android:{a}="{number(attrib[k])}"' for a, k in
(("startX", "x1"), ("startY", "y1"), ("endX", "x2"), ("endY", "y2")))
items = "".join(f'\n <item android:offset="{number(o)}" android:color="{c}"/>'
for o, c in stops)
return "", (f'\n <aapt:attr name="android:{attribute}">\n'
f' <gradient android:type="linear" {geometry}>{items}\n </gradient>\n'
f' </aapt:attr>')
elif attrib.get("gradientUnits") not in (None, "objectBoundingBox"):
raise RuntimeError(f"gradientUnits non pris en charge : {attrib.get('gradientUnits')}")
if tag == "linearGradient":
geometry = (f'android:type="linear" android:startX="{number(x0 + w * percent(attrib.get("x1"), "0%"))}" '
f'android:startY="{number(y0 + h * percent(attrib.get("y1"), "0%"))}" '
f'android:endX="{number(x0 + w * percent(attrib.get("x2"), "100%"))}" '
f'android:endY="{number(y0 + h * percent(attrib.get("y2"), "0%"))}"')
else:
if "fx" in attrib or "fy" in attrib or abs(w - h) > 0.01:
raise RuntimeError("Dégradé radial non pris en charge (foyer ou boîte non carrée)")
geometry = (f'android:type="radial" android:centerX="{number(x0 + w * percent(attrib.get("cx"), "50%"))}" '
f'android:centerY="{number(y0 + h * percent(attrib.get("cy"), "50%"))}" '
f'android:gradientRadius="{number(w * percent(attrib.get("r"), "50%"))}"')
items = "".join(f'\n <item android:offset="{number(o)}" android:color="{c}"/>' for o, c in stops)
return "", (f'\n <aapt:attr name="android:{attribute}">\n'
f' <gradient {geometry}>{items}\n </gradient>\n </aapt:attr>')
return f'android:{attribute}="{"#FFFFFFFF" if self.white else argb(value)}"', ""
def group(self, transform, children):
if not transform:
return children
rotation = ROTATE.fullmatch(transform.strip())
if rotation:
angle, px, py = rotation.groups()
return ([f'<group android:rotation="{number(angle)}" android:pivotX="{number(px)}" android:pivotY="{number(py)}">']
+ [" " + line for line in children] + ["</group>"])
match = TRANSFORM.fullmatch(transform.strip())
if not match:
raise RuntimeError(f"Transformation SVG non prise en charge : {transform}")
tx, ty, sx, sy = match.groups()
attributes = []
if tx is not None:
attributes += [f'android:translateX="{number(tx)}"', f'android:translateY="{number(ty)}"']
if sx is not None:
attributes += [f'android:scaleX="{number(sx)}"', f'android:scaleY="{number(sy if sy is not None else sx)}"']
return [f'<group {" ".join(attributes)}>'] + [" " + line for line in children] + ["</group>"]
def shape(self, d, bounds, attrib, fill):
attributes, inner = [], ""
if fill != "none":
a, i = self.paint("fillColor", fill, bounds)
attributes.append(a)
inner += i
if "fill-opacity" in attrib:
attributes.append(f'android:fillAlpha="{number(attrib["fill-opacity"])}"')
if "fill-rule" in attrib:
if attrib["fill-rule"] != "evenodd":
raise RuntimeError(f"fill-rule non pris en charge : {attrib['fill-rule']}")
attributes.append('android:fillType="evenOdd"')
stroke = attrib.get("stroke")
if stroke and stroke != "none":
a, i = self.paint("strokeColor", stroke, bounds)
attributes.append(a)
inner += i
attributes.append(f'android:strokeWidth="{number(attrib.get("stroke-width", "1"))}"')
if "stroke-opacity" in attrib:
attributes.append(f'android:strokeAlpha="{number(attrib["stroke-opacity"])}"')
if "stroke-linecap" in attrib:
attributes.append(f'android:strokeLineCap="{attrib["stroke-linecap"]}"')
if "stroke-linejoin" in attrib:
attributes.append(f'android:strokeLineJoin="{attrib["stroke-linejoin"]}"')
attributes = " ".join(a for a in attributes if a)
if inner:
return [f'<path android:pathData="{d}" {attributes}>{inner}\n </path>']
return [f'<path android:pathData="{d}" {attributes}/>']
def walk(self, node, fill):
tag = node.tag.replace(SVG, "")
if tag == "defs":
return []
if tag not in ALLOWED:
raise RuntimeError(f"Élément SVG non pris en charge : {tag}")
unknown = set(node.attrib) - ALLOWED[tag]
if unknown or "mask" in node.attrib:
raise RuntimeError(f"Attributs SVG non pris en charge sur {tag} : {sorted(unknown) or ['mask']}")
if "filter" in node.attrib:
self.dropped_filters += 1
fill = node.get("fill", fill)
if tag in ("svg", "g"):
children = [line for child in node for line in self.walk(child, fill)]
return self.group(node.get("transform"), children)
if tag == "rect":
x, y = float(node.get("x", 0)), float(node.get("y", 0))
w, h, r = float(node.get("width")), float(node.get("height")), float(node.get("rx", 0))
d = (f"M{number(x + r)},{number(y)}H{number(x + w - r)}A{number(r)},{number(r)} 0 0 1 {number(x + w)},{number(y + r)}"
f"V{number(y + h - r)}A{number(r)},{number(r)} 0 0 1 {number(x + w - r)},{number(y + h)}"
f"H{number(x + r)}A{number(r)},{number(r)} 0 0 1 {number(x)},{number(y + h - r)}"
f"V{number(y + r)}A{number(r)},{number(r)} 0 0 1 {number(x + r)},{number(y)}Z")
return self.shape(d, (x, y, x + w, y + h), node.attrib, fill)
if tag == "circle":
cx, cy, r = (float(node.get(k)) for k in ("cx", "cy", "r"))
d = (f"M{number(cx - r)},{number(cy)}A{number(r)},{number(r)} 0 1 0 {number(cx + r)},{number(cy)}"
f"A{number(r)},{number(r)} 0 1 0 {number(cx - r)},{number(cy)}Z")
return self.shape(d, (cx - r, cy - r, cx + r, cy + r), node.attrib, fill)
d = node.get("d")
return self.group(node.get("transform"), self.shape(d, path_bounds(d), node.attrib, fill))
def vector(self, width_dp, height_dp, viewbox=None, subtree=None):
"""VectorDrawable du SVG entier, ou du seul sous-arbre dont le transform est donné,
ancêtres compris. viewbox (x, y, largeur, hauteur) remplace celui du SVG."""
if viewbox is None:
viewbox = tuple(float(v) for v in self.root.get("viewBox").split())
if subtree is not None:
parents = {child: parent for parent in self.root.iter() for child in parent}
found = [n for n in self.root.iter() if n.get("transform") == subtree]
if len(found) != 1:
raise RuntimeError(f"Sous-arbre « {subtree} » : {len(found)} trouvés, 1 attendu")
keep, node = found[0], found[0]
while node is not self.root:
node = parents[node]
for sibling in list(node):
if sibling is not keep and sibling.tag != SVG + "defs":
node.remove(sibling)
keep = node
body = self.walk(self.root, "#000")
if not body:
raise RuntimeError("SVG vide après conversion")
x, y, w, h = viewbox
lines = "\n ".join(body)
return (f'<vector {HEADER}\n android:width="{number(width_dp)}dp"\n android:height="{number(height_dp)}dp"\n'
f' android:viewportWidth="{number(w)}"\n android:viewportHeight="{number(h)}">\n'
f' <group android:translateX="{number(-x)}" android:translateY="{number(-y)}">\n'
f' {lines}\n </group>\n</vector>\n')
# Carré de l'icône dans le repère de brand/loksi-icon.svg : translate(7 2) scale(.86).
SQUARE = (7.0, 2.0, 86.0)
SYMBOL = "translate(3 0) scale(.94)"
def adaptive(square):
"""Repère 108 dp d'une icône adaptative : le carré occupe les 72 dp visibles du centre."""
x, y, side = square
return (x - side / 4, y - side / 4, side * 1.5, side * 1.5)
def monochrome(mono_text):
"""Couche monochrome : le symbole seul, pris dans le masque de loksi-icon-mono.svg,
en blanc plein. Le système pose son fond et teinte la couche."""
root = ET.fromstring(mono_text)
masks = root.findall(f".//{SVG}mask")
if len(masks) != 1:
raise RuntimeError("loksi-icon-mono.svg : un masque attendu")
groups = masks[0].findall(SVG + "g")
if len(groups) != 1 or len(list(groups[0])) != 3:
raise RuntimeError("loksi-icon-mono.svg : le masque doit porter un groupe de 3 tracés")
ET.register_namespace("", SVG[1:-1])
symbol = ET.tostring(groups[0], encoding="unicode")
svg = f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100">{symbol}</svg>'
return Converter(svg, white=True).vector(108, 108, viewbox=adaptive((0.0, 0.0, 100.0)))
def write_all(src, brand):
"""Écrit les ressources vectorielles. Chaque cible existe déjà en amont, sauf le logo sombre."""
brand = Path(brand)
icon = (brand / "loksi-icon.svg").read_text()
written, dropped = [], 0
def put(relative, content, must_exist=True):
path = src / relative
if must_exist and not path.is_file():
raise RuntimeError(f"Ressource amont absente : {relative}")
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(content)
written.append(relative)
def convert(svg_text, *args, **kwargs):
nonlocal dropped
converter = Converter(svg_text)
result = converter.vector(*args, **kwargs)
dropped += converter.dropped_filters
return result
mono = monochrome((brand / "sources/loksi-icon-mono.svg").read_text())
for variant in ("main", "beta", "release"):
# Premier plan du lanceur : PNG par densité (render.mjs), enveloppé ici.
put(f"app/src/{variant}/res/drawable/ic_launcher_foreground.xml",
'<?xml version="1.0" encoding="utf-8"?>\n'
'<!-- Loksi : symbole sculpté, PNG par densité rendu par mobile/android/render.mjs. -->\n'
'<bitmap xmlns:android="http://schemas.android.com/apk/res/android"\n'
' android:src="@drawable/loksi_launcher_foreground" />\n')
put(f"app/src/{variant}/res/drawable/ic_launcher_monochrome.xml", mono)
# Écran de démarrage : le symbole seul sur le fond navy, repère de l'icône adaptative.
put("ui/src/main/res/drawable/logo_shield_icon.xml",
convert(icon, 108, 108, viewbox=adaptive(SQUARE), subtree=SYMBOL))
# Remplissage automatique et échange d'identifiants : le carré, sans marge d'ombre.
put("ui/src/main/res/drawable/logo_bitwarden_icon.xml",
convert(icon, 64, 64, viewbox=(SQUARE[0], SQUARE[1], SQUARE[2], SQUARE[2])))
# Logo complet : 44 dp de haut comme sur iOS, cadre de la charte (marges d'ombre comprises).
for variant, relative, must_exist in (("clair", "drawable", True), ("sombre", "drawable-night", False)):
svg_text = (brand / f"sources/loksi-logo-{variant}.svg").read_text()
_, _, w, h = (float(v) for v in re.search(r'viewBox="([^"]+)"', svg_text).group(1).split())
put(f"ui/src/main/res/{relative}/logo_bitwarden.xml", convert(svg_text, round(44 * w / h), 44), must_exist)
background = src / "app/src/main/res/values/ic_launcher_background.xml"
value = background.read_text()
if value.count("#FF175DDC") != 1:
raise RuntimeError("Couleur de fond d'icône amont modifiée")
background.write_text(value.replace("#FF175DDC", "#FF" + NAVY[1:]))
written.append("app/src/main/res/values/ic_launcher_background.xml")
# Canari : icône et deux logos portent chacun deux filtres (socle et symbole) ; le
# symbole seul en porte un. Un autre compte veut dire que la charte a changé.
if dropped != 7:
raise RuntimeError(f"Filtres retirés : {dropped}, 7 attendus")
return written
# Illustrations de la charte (brand/illustrations-mobiles/, style validé par Romain le
# 29/09/2026). Chaque ill_* amont est remplacé sous le même nom par le maître clair, et un
# ill_* du même nom dans drawable-night reçoit le maître sombre : l'amont n'a qu'une
# variante, recolorée par des chemins nommés, les maîtres Loksi ont leurs couleurs en dur.
# La correspondance vient de brand/illustrations-mobiles/correspondance.mjs, colonne Android.
# Hors jeu : Premium (ill_celebration) et ill_vault, que le code amont n'affiche pas.
OUT_OF_SET = {"ill_celebration", "ill_vault"}
def android_set(brand):
"""{drawable amont: maître Loksi}, lu dans la colonne Android de correspondance.mjs."""
text = (Path(brand) / "illustrations-mobiles/correspondance.mjs").read_text()
quoted = r"'((?:[^'\\]|\\.)*)'"
rows = re.findall(r"\[\s*" + r",\s*".join([quoted] * 5) + r"\s*\]", text)
if len(rows) < 20:
raise RuntimeError(f"correspondance.mjs illisible : {len(rows)} lignes")
mapping = {}
for name, _, _, android, _ in rows:
for drawable in re.findall(r"ill_\w+", android):
if drawable in mapping:
raise RuntimeError(f"{drawable} attribué deux fois dans correspondance.mjs")
mapping[drawable] = name
return mapping
def write_illustrations(src, brand):
brand = Path(brand)
res = src / "ui/src/main/res"
upstream = {p.stem for p in (res / "drawable").glob("ill_*.xml")}
mapping = android_set(brand)
# Toute illustration amont est remplacée ou écartée exprès ; toute cible existe en amont.
if set(mapping) | OUT_OF_SET != upstream or set(mapping) & OUT_OF_SET:
raise RuntimeError(f"Illustrations amont non couvertes : {sorted(upstream - set(mapping) - OUT_OF_SET)}, "
f"absentes de l'amont : {sorted(set(mapping) - upstream)}")
written, evenodd = [], 0
for drawable, name in sorted(mapping.items()):
size = float(re.search(r'android:width="([\d.]+)dp"', (res / f"drawable/{drawable}.xml").read_text()).group(1))
for variant, folder in (("clair", "drawable"), ("sombre", "drawable-night")):
svg_text = (brand / f"illustrations-mobiles/sources/{name}-{variant}.svg").read_text()
converter = Converter(svg_text)
vector = converter.vector(size, size)
if converter.dropped_filters:
raise RuntimeError(f"{name}-{variant}.svg : filtre dans un maître d'illustration")
if vector.count('android:fillType="evenOdd"') != svg_text.count('fill-rule="evenodd"'):
raise RuntimeError(f"{name}-{variant}.svg : évidement perdu à la conversion")
evenodd += svg_text.count('fill-rule="evenodd"')
(res / folder).mkdir(exist_ok=True)
(res / folder / f"{drawable}.xml").write_text(vector)
written.append(f"{folder}/{drawable}.xml")
return written, evenodd
# Barre d'onglets : pictogrammes de la charte (brand/illustrations-mobiles/onglets/). Actif :
# formes pleines aux couleurs de la charte, clair dans drawable, sombre dans drawable-night,
# affichées sans teinte par l'amont (icônes multitons). Inactif : au trait, teinté par le
# thème (icon.primary), la variante claire suffit.
TABS = {"vault": "ic_vault", "generator": "ic_generator", "send": "ic_send", "settings": "ic_settings"}
def write_tab_icons(src, brand):
res = src / "ui/src/main/res"
sources = Path(brand) / "illustrations-mobiles/onglets"
written, evenodd = [], 0
for tab, drawable in TABS.items():
for state, name, variants in (("idle", drawable, (("light", "drawable"),)),
("active", drawable + "_filled", (("light", "drawable"), ("dark", "drawable-night")))):
if not (res / f"drawable/{name}.xml").is_file():
raise RuntimeError(f"Pictogramme amont absent : {name}")
for theme, folder in variants:
svg_text = (sources / f"{tab}-{state}-{theme}.svg").read_text()
vector = Converter(svg_text).vector(24, 24)
if vector.count('android:fillType="evenOdd"') != svg_text.count('fill-rule="evenodd"'):
raise RuntimeError(f"{tab}-{state}-{theme}.svg : évidement perdu à la conversion")
evenodd += svg_text.count('fill-rule="evenodd"')
(res / folder / f"{name}.xml").write_text(vector)
written.append(f"{folder}/{name}.xml")
if len(written) != 12:
raise RuntimeError(f"12 pictogrammes attendus, {len(written)}")
# Canari : la roue et le coffre ont des évidements (fill-rule evenodd). Sans aucun,
# le contrôle de conversion ci-dessus ne prouve rien.
if not evenodd:
raise RuntimeError("Canari muet : aucun évidement dans les pictogrammes")
return written, evenodd