parse .glyphs using glyphsLib

This commit is contained in:
subframe7536 2024-12-27 10:17:56 +08:00
parent 667d780297
commit e899c29c7a
3 changed files with 39 additions and 47 deletions

View file

@ -532,42 +532,34 @@ def drop_mac_names(dir: str):
def rename_glyph_name(
font: TTFont,
old_glyph_name: str,
new_glyph_name: str,
map: dict[str, str],
post_extra_names: bool = True,
):
not_ci = not is_ci()
glyph_names = font.getGlyphOrder()
modified = False
for i, _ in enumerate(glyph_names):
_old = str(glyph_names[i])
if _old == old_glyph_name:
glyph_names[i] = new_glyph_name
print(f"{old_glyph_name} renamed to {new_glyph_name}")
if not _old.startswith("uni"):
continue
_new = map.get(_old)
if not _new or _new == _old:
continue
if not_ci:
print(f"[Rename] {_old} -> {_new}")
glyph_names[i] = _new
modified = True
# elif _old.startswith("uni"):
# new_name = map.get(_old)
# if new_name:
# print(f"{_old} renamed to {new_name}")
# glyph_names[i] = new_name
# modified = True
# else:
# arr = re.split(r"[\._]", _old, maxsplit=2)
# print(arr[0])
# _new = map.get(arr[0])
# if _new:
# print(f"{_old} renamed to {_new + arr[1]}")
# glyph_names[i] = _new + arr[1]
# modified = True
if post_extra_names:
index = font["post"].extraNames.index(_old)
if index != -1:
font["post"].extraNames[index] = _new
if modified:
font.setGlyphOrder(glyph_names)
if post_extra_names:
index = font["post"].extraNames.index(old_glyph_name)
if index != -1:
font["post"].extraNames[index] = new_glyph_name
def get_unique_identifier(
font_config: FontConfig,
@ -927,16 +919,11 @@ def main():
font = TTFont(input_file)
# fix auto rename by FontLab
with open(
input_file.replace(".ttf", ".glyphs").replace("-VF", ""),
"r",
encoding="utf-8",
) as f:
rename_glyph_name(
font=font,
old_glyph_name="uni2047.liga",
new_glyph_name="question_question.liga",
map=match_unicode_names(f.read()),
map=match_unicode_names(
input_file.replace(".ttf", ".glyphs").replace("-VF", "")
),
)
font.save(

View file

@ -1 +1,2 @@
foundrytools-cli==1.1.22
glyphsLib==6.6.1

View file

@ -1,12 +1,11 @@
from os import environ, path, remove
import platform
import re
import shutil
import subprocess
from urllib.request import Request, urlopen
from zipfile import ZipFile
from fontTools.ttLib import TTFont
from glyphsLib import GSFont
def is_ci():
ci_envs = [
@ -170,11 +169,16 @@ def download_cn_base_font(
)
def match_unicode_names(text: str) -> dict[str, str]:
pattern = r"glyphname = ([^;]+);[\s\S]*?unicode = (\d+);"
matches = re.findall(pattern, text)
return {
f"uni{int(match[1]):04X}": match[0].strip('"')
for match in matches
if not str(match[0]).startswith("uni")
}
def match_unicode_names(file_path: str) -> dict[str, str]:
font = GSFont(file_path)
result = {}
for glyph in font.glyphs:
glyph_name = glyph.name
unicode_values = glyph.unicode
if glyph_name and unicode_values:
unicode_str = f"uni{''.join(unicode_values).upper().zfill(4)}"
result[unicode_str]=glyph_name
return result