first commit
初次提交
This commit is contained in:
@@ -0,0 +1,177 @@
|
||||
#!/usr/bin/env python3
|
||||
"""从 assets/svgs 生成 gallery.js。
|
||||
|
||||
用法(新增或删除 SVG 后运行一次):
|
||||
python tools/build-gallery.py
|
||||
|
||||
每个图形都会被归一化到页面使用的 1500×1200 坐标画布:保持宽高比、居中。
|
||||
`clipPath` 不支持 <g>,因此这里会把组展平,并把归一化变换写到每个形状上。
|
||||
仅支持矢量形状(path / circle / rect / ellipse / line / polyline / polygon);
|
||||
文字、位图、foreignObject 会被忽略。
|
||||
"""
|
||||
from pathlib import Path
|
||||
import json
|
||||
import sys
|
||||
import xml.etree.ElementTree as ET
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
SRC_DIR = ROOT / "assets" / "svgs"
|
||||
OUT = ROOT / "gallery.js"
|
||||
CANVAS_W, CANVAS_H = 1500, 1200
|
||||
NS = "{http://www.w3.org/2000/svg}"
|
||||
|
||||
SHAPE_ATTRS = {
|
||||
"path": ("d", "fill-rule", "clip-rule"),
|
||||
"circle": ("cx", "cy", "r"),
|
||||
"rect": ("x", "y", "width", "height", "rx", "ry"),
|
||||
"ellipse": ("cx", "cy", "rx", "ry"),
|
||||
"line": ("x1", "y1", "x2", "y2"),
|
||||
"polyline": ("points",),
|
||||
"polygon": ("points",),
|
||||
}
|
||||
CONTAINERS = {"g", "a", "switch"}
|
||||
SKIP = {
|
||||
"defs", "style", "metadata", "title", "desc", "clippath", "mask", "filter",
|
||||
"lineargradient", "radialgradient", "pattern", "symbol", "marker", "image",
|
||||
"text", "tspan", "textpath", "foreignobject", "script",
|
||||
}
|
||||
|
||||
|
||||
def fmt(n):
|
||||
if abs(n) < 1e-9:
|
||||
return "0"
|
||||
return f"{n:.6f}".rstrip("0").rstrip(".")
|
||||
|
||||
|
||||
def read_view_box(root):
|
||||
vb = root.get("viewBox")
|
||||
if vb:
|
||||
parts = [p for p in vb.replace(",", " ").split() if p]
|
||||
if len(parts) == 4:
|
||||
x, y, w, h = (float(p) for p in parts)
|
||||
if w > 0 and h > 0:
|
||||
return x, y, w, h
|
||||
w = float(str(root.get("width", "")).rstrip("px") or 0)
|
||||
h = float(str(root.get("height", "")).rstrip("px") or 0)
|
||||
if w > 0 and h > 0:
|
||||
return 0.0, 0.0, w, h
|
||||
raise ValueError("缺少有效的 viewBox / width / height")
|
||||
|
||||
|
||||
def normalize_transform(x, y, w, h):
|
||||
scale = min(CANVAS_W / w, CANVAS_H / h)
|
||||
tx = (CANVAS_W - w * scale) / 2
|
||||
ty = (CANVAS_H - h * scale) / 2
|
||||
parts = []
|
||||
if abs(tx) > 1e-9 or abs(ty) > 1e-9:
|
||||
parts.append(f"translate({fmt(tx)} {fmt(ty)})")
|
||||
if abs(scale - 1) > 1e-9:
|
||||
parts.append(f"scale({fmt(scale)})")
|
||||
if abs(x) > 1e-9 or abs(y) > 1e-9:
|
||||
parts.append(f"translate({fmt(-x)} {fmt(-y)})")
|
||||
return " ".join(parts)
|
||||
|
||||
|
||||
def esc(value):
|
||||
return (str(value).replace("&", "&").replace("<", "<")
|
||||
.replace(">", ">").replace('"', """))
|
||||
|
||||
|
||||
def collect_ids(root):
|
||||
ids = {}
|
||||
for el in root.iter():
|
||||
eid = el.get("id")
|
||||
if eid:
|
||||
ids[eid] = el
|
||||
return ids
|
||||
|
||||
|
||||
def walk(node, inherited, out, ids, stack):
|
||||
tag = node.tag.replace(NS, "").lower()
|
||||
own = (node.get("transform") or "").strip()
|
||||
|
||||
if tag == "use":
|
||||
href = node.get("href") or node.get("{http://www.w3.org/1999/xlink}href") or ""
|
||||
if not href.startswith("#"):
|
||||
return
|
||||
ref = ids.get(href[1:])
|
||||
if ref is None or id(ref) in stack:
|
||||
return
|
||||
x = float(node.get("x") or 0)
|
||||
y = float(node.get("y") or 0)
|
||||
chain = " ".join(p for p in (inherited, own) if p)
|
||||
if x or y:
|
||||
chain = " ".join(p for p in (chain, f"translate({fmt(x)} {fmt(y)})") if p)
|
||||
walk(ref, chain, out, ids, stack | {id(ref)})
|
||||
return
|
||||
|
||||
if tag in SKIP:
|
||||
return
|
||||
chain = " ".join(p for p in (inherited, own) if p)
|
||||
|
||||
if tag in CONTAINERS:
|
||||
for child in node:
|
||||
walk(child, chain, out, ids, stack)
|
||||
return
|
||||
|
||||
if tag not in SHAPE_ATTRS:
|
||||
return
|
||||
|
||||
attrs = []
|
||||
for name in SHAPE_ATTRS[tag]:
|
||||
val = node.get(name)
|
||||
if val not in (None, ""):
|
||||
attrs.append(f'{name}="{esc(val)}"')
|
||||
if not attrs:
|
||||
return
|
||||
if chain:
|
||||
attrs.append(f'transform="{esc(chain)}"')
|
||||
out.append(f"<{tag} {' '.join(attrs)}/>")
|
||||
|
||||
|
||||
def build_entry(path):
|
||||
root = ET.parse(path).getroot()
|
||||
vx, vy, vw, vh = read_view_box(root)
|
||||
shapes = []
|
||||
norm = normalize_transform(vx, vy, vw, vh)
|
||||
ids = collect_ids(root)
|
||||
for child in root:
|
||||
walk(child, norm, shapes, ids, set())
|
||||
if not shapes:
|
||||
raise ValueError("没有可用的矢量形状")
|
||||
return {
|
||||
"name": path.stem,
|
||||
"viewBox": f"{fmt(vx)} {fmt(vy)} {fmt(vw)} {fmt(vh)}",
|
||||
"markup": "".join(shapes),
|
||||
}
|
||||
|
||||
|
||||
def main():
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding="utf-8")
|
||||
except AttributeError:
|
||||
pass
|
||||
if not SRC_DIR.is_dir():
|
||||
sys.exit(f"目录不存在: {SRC_DIR}")
|
||||
files = sorted(SRC_DIR.glob("*.svg"), key=lambda p: p.name.lower())
|
||||
entries = []
|
||||
for path in files:
|
||||
try:
|
||||
entries.append(build_entry(path))
|
||||
except Exception as exc: # noqa: BLE001 - report and continue
|
||||
print(f"[skip] {path.name}: {exc}")
|
||||
|
||||
body = json.dumps(entries, ensure_ascii=False, indent=2)
|
||||
OUT.write_text(
|
||||
"/* 由 tools/build-gallery.py 生成,请勿手工编辑。\n"
|
||||
" 新增/删除 assets/svgs 中的 SVG 后运行: python tools/build-gallery.py */\n"
|
||||
"window.WALLPAPER_GALLERY = " + body + ";\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
print(f"已写入 {OUT.name}: {len(entries)} 个图形")
|
||||
for entry in entries:
|
||||
print(f" - {entry['name']} ({entry['viewBox']})")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user