korterm/scripts/update-tabler-icons.py
Ivan Cherniy 2607becaa7 Fix icons on GTK 4.22: turn strokes into outlines; version 0.3.27
GTK 4.22 recolours symbolic SVGs by filling them and ignores strokes, so the
Tabler icons drew as solid squares or empty shapes. update-tabler-icons.py now
converts strokes to filled paths with Inkscape and drops the background rect.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-19 00:42:06 +03:00

332 lines
12 KiB
Python

#!/usr/bin/env python3
"""Build KorTerm's embedded Tabler GResource from a pinned npm package.
Usage: scripts/update-tabler-icons.py /path/to/extracted/package
The package directory must contain package.json, icons.json, LICENSE, and
icons/outline/*.svg. Normal Cargo builds never access the network and consume
only the generated korterm-icons.gresource file.
Needs glib-compile-resources and Inkscape (1.x). Inkscape turns every stroke into a filled
outline: GTK 4.22 recolours symbolic SVGs by filling them and ignores strokes, so the upstream
stroke-only icons would draw as empty shapes or as solid squares.
"""
from __future__ import annotations
import hashlib
import json
import re
import shutil
import subprocess
import sys
import tempfile
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
RESOURCES = ROOT / "crates" / "korterm-ui" / "resources"
TABLER = RESOURCES / "tabler"
BUNDLE = RESOURCES / "korterm-icons.gresource"
RESOURCE_PREFIX = "/me/r4ven/KorTerm/icons/scalable/actions"
CATALOG_PREFIX = "/me/r4ven/KorTerm/tabler"
ICON_PREFIX = "korterm-tabler-"
EXPECTED_PACKAGE = "@tabler/icons"
EXPECTED_VERSION = "3.50.0"
EXPECTED_SOURCE_SHA256 = "7d2aca04edf89a2360cbb88ff59c21cf5941eec8f800f817056198e8b29483dc"
# Categories relevant to labelling SSH hosts and quick commands. Chosen over
# the full upstream set (e.g. Brand, Animals, Food, Zodiac) to keep the
# bundled catalog to a few hundred suitable icons instead of several thousand.
WANTED_CATEGORIES = {
"System",
"Devices",
"Development",
"Database",
"Computers",
"Communication",
"Document",
"Text",
"Symbols",
"Charts",
"Version control",
}
# Icons used by KorTerm's own chrome and menus. They are always embedded even when their upstream
# category is outside the entity-oriented picker filter, or when they are variants of a base icon.
UI_ICONS = {
"alert-triangle",
"app-window",
"arrow-down",
"arrow-left",
"arrow-right",
"arrow-up",
"browser-plus",
"chevron-down",
"chevron-left",
"chevron-right",
"chevron-up",
"circle-off",
"clipboard",
"columns-2",
"copy",
"dots-vertical",
"edit",
"file-text",
"folder",
"folder-open",
"folder-plus",
"folder-share",
"icons",
"info-circle",
"key",
"keyboard",
"layout-rows",
"list",
"menu-2",
"player-play",
"player-record",
"plus",
"refresh",
"search",
"select-all",
"server",
"settings",
"skull",
"square-plus",
"terminal-2",
"trash",
"x",
}
# GTK asks for these names inside standard controls such as DropDown and SpinButton. Providing
# application resource aliases gives them the same Tabler outline without replacing the widgets.
GTK_ALIASES = {
"pan-down-symbolic": "chevron-down",
"pan-end-symbolic": "chevron-right",
"pan-end-symbolic-rtl": "chevron-left",
"pan-up-symbolic": "chevron-up",
}
BACKGROUND = re.compile(r"^[ \t]*<path[^>]*d=\"M0 0h24v24H0z\"[^>]*/>[ \t]*\n", re.MULTILINE)
ROOT_PAINT = re.compile(r'\s(?:fill|stroke|stroke-width|stroke-linecap|stroke-linejoin|class)="[^"]*"')
INKSCAPE_BATCH = 40
def outline_batch(jobs: list[tuple[Path, Path]]) -> None:
"""Turn the strokes of several SVGs into filled paths in one Inkscape process.
Inkscape is a single-instance application, so parallel processes lose their work.
"""
actions = ";".join(
f"file-open:{source};select-all:all;object-stroke-to-path;"
f"export-filename:{target};export-plain-svg;export-do;file-close"
for source, target in jobs
)
subprocess.run(
["inkscape", f"--actions={actions}"],
check=False,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
def outline_svgs(sources: list[Path], target_dir: Path) -> None:
"""Write a stroke-free copy of every source SVG into target_dir."""
if shutil.which("inkscape") is None:
fail("Inkscape is required to turn icon strokes into outlines")
target_dir.mkdir(parents=True, exist_ok=True)
with tempfile.TemporaryDirectory(prefix="korterm-bare-") as bare:
jobs = []
for source in sources:
# The 24x24 background rectangle would be filled as a solid square.
text = BACKGROUND.sub("", source.read_text(encoding="utf-8"))
staged = Path(bare) / source.name
staged.write_text(text, encoding="utf-8")
jobs.append((staged, target_dir / source.name))
for start in range(0, len(jobs), INKSCAPE_BATCH):
batch = jobs[start : start + INKSCAPE_BATCH]
outline_batch(batch)
# Retry what a batch dropped, one file per process.
for job in batch:
if not (job[1].is_file() and job[1].stat().st_size > 0):
outline_batch([job])
for _, target in jobs:
if not (target.is_file() and target.stat().st_size > 0):
fail(f"Inkscape could not convert {target.name}")
text = target.read_text(encoding="utf-8")
# The root stroke attributes would be inherited by the new filled paths.
text = re.sub(r"<svg\b[^>]*>", lambda m: ROOT_PAINT.sub("", m.group(0)), text, count=1)
if "stroke" in text or "<path" not in text:
fail(f"{target.name} still has strokes or has no path after conversion")
target.write_text(text, encoding="utf-8")
def fail(message: str) -> None:
raise SystemExit(f"update-tabler-icons: {message}")
def clean(value: str) -> str:
return " ".join(value.replace("\t", " ").replace("\n", " ").split())
def source_digest(source: Path) -> str:
"""Hash every upstream input used to build the bundle, including stable relative paths."""
files = [
source / "package.json",
source / "icons.json",
source / "LICENSE",
*(source / "icons" / "outline").glob("*.svg"),
]
digest = hashlib.sha256()
for path in sorted(files, key=lambda item: item.relative_to(source).as_posix()):
digest.update(path.relative_to(source).as_posix().encode("utf-8"))
digest.update(b"\0")
digest.update(path.read_bytes())
digest.update(b"\0")
return digest.hexdigest()
def is_variant(name: str, all_names: set[str]) -> bool:
"""True if `name` is a decorated form of another icon (e.g. `bell-off`
of `bell`, `adjustments-cog` of `adjustments`). Keeps only the plain,
base concept per icon family instead of every styled suffix."""
parts = name.split("-")
return any("-".join(parts[:i]) in all_names for i in range(len(parts) - 1, 0, -1))
def main() -> None:
if len(sys.argv) != 2:
fail("expected one argument: an extracted @tabler/icons package directory")
source = Path(sys.argv[1]).resolve()
package_path = source / "package.json"
metadata_path = source / "icons.json"
license_path = source / "LICENSE"
source_icons = source / "icons" / "outline"
for path in (package_path, metadata_path, license_path, source_icons):
if not path.exists():
fail(f"missing {path}")
package = json.loads(package_path.read_text(encoding="utf-8"))
metadata = json.loads(metadata_path.read_text(encoding="utf-8"))
if not isinstance(metadata, dict):
fail("icons.json is not an object")
if package.get("name") != EXPECTED_PACKAGE or package.get("version") != EXPECTED_VERSION:
fail(
f"expected {EXPECTED_PACKAGE} {EXPECTED_VERSION}, got "
f"{package.get('name')} {package.get('version')}"
)
digest = source_digest(source)
if digest != EXPECTED_SOURCE_SHA256:
fail(
"the pinned package contents differ from the reviewed source "
f"(expected {EXPECTED_SOURCE_SHA256}, got {digest})"
)
icons = sorted(source_icons.glob("*.svg"), key=lambda path: path.stem)
names = [path.stem for path in icons]
if not icons or len(names) != len(set(names)):
fail("the outline icon set is empty or has duplicate names")
if set(names) != set(metadata):
fail("outline SVGs and icons.json entries differ")
all_names = set(names)
total_available = len(icons)
icons = [
path
for path in icons
if path.stem in UI_ICONS
or (
metadata[path.stem].get("category") in WANTED_CATEGORIES
and not is_variant(path.stem, all_names)
)
]
if not icons:
fail("category and variant filtering left no icons")
version = str(package.get("version", "unknown"))
provenance = (
f"@tabler/icons {version}\n"
f"Source: https://registry.npmjs.org/@tabler/icons/-/icons-{version}.tgz\n"
)
with tempfile.TemporaryDirectory(prefix="korterm-tabler-") as temporary:
stage = Path(temporary)
outline = stage / "tabler" / "outline"
outline.mkdir(parents=True)
raw = stage / "raw"
raw.mkdir()
catalog = []
resource_files = []
for source_icon in icons:
name = source_icon.stem
if not name or any(part in name for part in ("/", "\\", "..", "\t", "\n")):
fail(f"unsafe icon name {name!r}")
svg = source_icon.read_text(encoding="utf-8")
if 'stroke="currentColor"' not in svg or "<script" in svg.lower():
fail(f"icon {name!r} is not a safe current-color outline SVG")
(raw / source_icon.name).write_text(svg, encoding="utf-8")
record = metadata[name]
category = clean(str(record.get("category", "")))
tags = [clean(str(tag)) for tag in record.get("tags", [])]
search = clean(" ".join([name.replace("-", " "), category, *tags])).lower()
catalog.append(f"{name}\t{search}\n")
resource_files.append(
f' <file alias="{ICON_PREFIX}{name}-symbolic.svg" compressed="true">'
f"tabler/outline/{name}.svg</file>\n"
)
outline_svgs(sorted(raw.glob("*.svg")), outline)
for alias, name in GTK_ALIASES.items():
if name not in {path.stem for path in icons}:
fail(f"GTK alias {alias!r} refers to an icon that is not embedded: {name!r}")
resource_files.append(
f' <file alias="{alias}.svg" compressed="true">'
f"tabler/outline/{name}.svg</file>\n"
)
staged_tabler = stage / "tabler"
(staged_tabler / "icons.tsv").write_text("".join(catalog), encoding="utf-8")
shutil.copyfile(license_path, staged_tabler / "LICENSE")
(staged_tabler / "VERSION").write_text(provenance, encoding="utf-8")
manifest = (
'<?xml version="1.0" encoding="UTF-8"?>\n'
"<gresources>\n"
f' <gresource prefix="{RESOURCE_PREFIX}">\n'
+ "".join(resource_files)
+ " </gresource>\n"
f' <gresource prefix="{CATALOG_PREFIX}">\n'
' <file alias="icons.tsv" compressed="true">tabler/icons.tsv</file>\n'
' <file alias="LICENSE">tabler/LICENSE</file>\n'
' <file alias="VERSION">tabler/VERSION</file>\n'
" </gresource>\n"
"</gresources>\n"
)
manifest_path = stage / "icons.gresource.xml"
manifest_path.write_text(manifest, encoding="utf-8")
staged_bundle = stage / "korterm-icons.gresource"
subprocess.run(
[
"glib-compile-resources",
f"--sourcedir={stage}",
f"--target={staged_bundle}",
str(manifest_path),
],
check=True,
)
# Publish generated files only after the complete bundle was built successfully.
RESOURCES.mkdir(parents=True, exist_ok=True)
TABLER.mkdir(parents=True, exist_ok=True)
shutil.copyfile(staged_bundle, BUNDLE)
shutil.copyfile(staged_tabler / "LICENSE", TABLER / "LICENSE")
shutil.copyfile(staged_tabler / "VERSION", TABLER / "VERSION")
print(
f"embedded {len(icons)} of {total_available} Tabler outline icons "
f"from {version} in {BUNDLE}"
)
if __name__ == "__main__":
main()