Nacre/tools/icons.py

58 lines
2.6 KiB
Python

#!/usr/bin/env python3
"""Cut Material Symbols Outlined down to the icons in tools/icons.txt.
Writes assets/fonts/MaterialSymbolsOutlined-Nacre.ttf (axes FILL 0..1 and wght 100..700 kept, GRAD 0 and
opsz 24 pinned) and src/ui/icons.rs. Needs fontTools and the full variable font: by default the one from Arch's
ttf-material-symbols-variable package; pass another path as the first argument.
"""
import sys
from pathlib import Path
from fontTools import subset
from fontTools.ttLib import TTFont
from fontTools.ttLib.tables._c_m_a_p import CmapSubtable
from fontTools.varLib import instancer
ROOT = Path(__file__).resolve().parent.parent
SOURCE = sys.argv[1] if len(sys.argv) > 1 else "/usr/share/fonts/TTF/MaterialSymbolsOutlined[FILL,GRAD,opsz,wght].ttf"
OUT_FONT = ROOT / "assets/fonts/MaterialSymbolsOutlined-Nacre.ttf"
OUT_RS = ROOT / "src/ui/icons.rs"
names = [line.strip() for line in (ROOT / "tools/icons.txt").read_text().splitlines() if line.strip() and not line.startswith("#")]
font = TTFont(SOURCE)
by_name = {glyph: code for code, glyph in font.getBestCmap().items() if code >= 0xE000}
missing = [n for n in names if n not in by_name]
if missing:
sys.exit(f"not in the font: {', '.join(missing)}")
if len(set(names)) != len(names):
sys.exit("duplicate names in icons.txt")
options = subset.Options()
options.layout_features = [] # no ligatures: the UI uses code points
options.name_IDs = ["*"]
options.notdef_outline = True
subsetter = subset.Subsetter(options)
subsetter.populate(unicodes=[by_name[n] for n in names])
subsetter.subset(font)
font = instancer.instantiateVariableFont(font, {"GRAD": 0, "opsz": 24})
# egui's colour picker has a hard-coded 📋 (U+1F4CB) copy button that no interface font covers: alias it to content_copy.
cmap = font["cmap"]
best = dict(font.getBestCmap())
best[0x1F4CB] = best[by_name["content_copy"]]
table = CmapSubtable.newSubtable(12)
table.platformID, table.platEncID, table.language, table.cmap = 3, 10, 0, best
cmap.tables = [t for t in cmap.tables if not (t.platformID == 3 and t.platEncID == 10)] + [table]
font.save(OUT_FONT)
lines = [
"//! Material Symbols Outlined code points (Apache 2.0), from tools/icons.txt. Generated by tools/icons.py:",
"//! edit the list and run the tool, don't edit this file.",
"",
]
lines += [f'pub const {n.upper()}: &str = "\\u{{{by_name[n]:x}}}";' for n in names]
lines += ["", "/// Every icon with its name, for the gallery.", "pub const ALL: &[(&str, &str)] = &["]
lines += [f' ("{n}", {n.upper()}),' for n in names]
lines += ["];", ""]
OUT_RS.write_text("\n".join(lines))
print(f"{len(names)} icons, {OUT_FONT.stat().st_size // 1024} KB")