Gitea CI / Build Android APK (pull_request) Canceled after 0s
Gitea CI / Build Windows x64 app (pull_request) Canceled after 0s
Gitea CI / Audit and package Windows x64 (pull_request) Canceled after 0s
Gitea CI / Assemble and validate CI artifacts (pull_request) Canceled after 0s
Gitea CI / Gitea CI passed (pull_request) Canceled after 0s
Gitea CI / Check code and tests (pull_request) Canceled after 6m29s
158 lines
6.6 KiB
Python
158 lines
6.6 KiB
Python
#!/usr/bin/env python3
|
|
"""Generate Flutter icon constants from a pinned Phosphor font catalog."""
|
|
|
|
import argparse
|
|
import hashlib
|
|
import json
|
|
from pathlib import Path
|
|
import re
|
|
import sys
|
|
from urllib.request import urlopen
|
|
|
|
|
|
ROOT = Path(__file__).resolve().parent.parent
|
|
SOURCE = ROOT / 'tool/phosphor/catalog.json'
|
|
OUTPUT = ROOT / 'lib/src/icons/phosphor_icons.g.dart'
|
|
STYLES = {
|
|
'regular': ('Phosphor.ttf', 'PhosphorRegular', 'PhosphorIconsRegular'),
|
|
'fill': ('Phosphor-Fill.ttf', 'PhosphorFill', 'PhosphorIconsFill'),
|
|
}
|
|
# Mirror navigation only, keeping playback, undo/redo, and logos unchanged.
|
|
MIRRORED = {'arrow-left', 'arrow-right', 'caret-left', 'caret-right',
|
|
'caret-double-left', 'caret-double-right'}
|
|
|
|
|
|
def read_upstream(revision, path):
|
|
url = f'https://raw.githubusercontent.com/phosphor-icons/web/{revision}/{path}'
|
|
with urlopen(url, timeout=30) as response:
|
|
return response.read()
|
|
|
|
|
|
def update_catalog(revision):
|
|
if not re.fullmatch(r'[0-9a-f]{40}', revision):
|
|
raise ValueError('--update requires a full Git commit SHA')
|
|
version = json.loads(read_upstream(revision, 'package.json'))['version']
|
|
catalog = {
|
|
'repository': 'https://github.com/phosphor-icons/web',
|
|
'revision': revision,
|
|
'version': version,
|
|
'styles': {},
|
|
}
|
|
# Fetch and validate everything before writing the local snapshot.
|
|
assets = {}
|
|
for style, (filename, family, _) in STYLES.items():
|
|
selection_path = f'src/{style}/selection.json'
|
|
selection = read_upstream(revision, selection_path)
|
|
icons = {}
|
|
for item in json.loads(selection)['icons']:
|
|
properties = item['properties']
|
|
for alias in properties['name'].split(','):
|
|
name = alias.strip()
|
|
if style == 'fill':
|
|
if not name.endswith('-fill'):
|
|
raise ValueError(f'Missing fill suffix: {name}')
|
|
name = name[:-5]
|
|
if name in icons:
|
|
raise ValueError(f'Duplicate icon: {name}')
|
|
icons[name] = properties['code']
|
|
font_path = f'src/{style}/{filename}'
|
|
font = read_upstream(revision, font_path)
|
|
local_path = f'assets/fonts/{family}.ttf'
|
|
assets[local_path] = font
|
|
catalog['styles'][style] = {
|
|
'font': local_path,
|
|
'fontSource': font_path,
|
|
'fontSha256': hashlib.sha256(font).hexdigest(),
|
|
'catalogSource': selection_path,
|
|
'catalogSha256': hashlib.sha256(selection).hexdigest(),
|
|
'icons': dict(sorted(icons.items())),
|
|
}
|
|
if catalog['styles']['regular']['icons'] != catalog['styles']['fill']['icons']:
|
|
raise ValueError('Regular and Fill catalogs do not match')
|
|
assets['assets/fonts/PHOSPHOR_LICENSE.txt'] = read_upstream(revision, 'LICENSE')
|
|
for path, data in assets.items():
|
|
target = ROOT / path
|
|
target.parent.mkdir(parents=True, exist_ok=True)
|
|
target.write_bytes(data)
|
|
SOURCE.parent.mkdir(parents=True, exist_ok=True)
|
|
SOURCE.write_text(json.dumps(catalog, indent=2) + '\n', encoding='utf-8')
|
|
|
|
|
|
def dart_name(name):
|
|
if not re.fullmatch(r'[a-z][a-z0-9]*(?:-[a-z0-9]+)*', name):
|
|
raise ValueError(f'Invalid icon name: {name}')
|
|
first, *rest = name.split('-')
|
|
result = first + ''.join(part[0].upper() + part[1:] for part in rest)
|
|
# Preserve Dart keywords as usable field names.
|
|
if result in {'as', 'assert', 'break', 'case', 'catch', 'class', 'const',
|
|
'continue', 'default', 'do', 'else', 'enum', 'extends', 'false',
|
|
'final', 'finally', 'for', 'if', 'in', 'is', 'new', 'null',
|
|
'rethrow', 'return', 'super', 'switch', 'this', 'throw', 'true',
|
|
'try', 'var', 'void', 'while', 'with'}:
|
|
result += 'Icon'
|
|
return result
|
|
|
|
|
|
def generate(catalog):
|
|
lines = [
|
|
'// GENERATED CODE - DO NOT MODIFY BY HAND.',
|
|
'// Run: python3 tool/generate_icons.py (from packages/cutdex_ui).',
|
|
f"// Phosphor web {catalog['version']} @ {catalog['revision']}",
|
|
"import 'package:flutter/widgets.dart';",
|
|
]
|
|
for style, (_, family, class_name) in STYLES.items():
|
|
source = catalog['styles'][style]
|
|
font = (ROOT / source['font']).read_bytes()
|
|
if hashlib.sha256(font).hexdigest() != source['fontSha256']:
|
|
raise ValueError(f'Font checksum mismatch: {source["font"]}')
|
|
lines.extend(['', f'/// Phosphor {style.title()} icons from the pinned font catalog.',
|
|
'@staticIconProvider', f'abstract final class {class_name} {{'])
|
|
identifiers = set()
|
|
for name, codepoint in sorted(source['icons'].items()):
|
|
identifier = dart_name(name)
|
|
if identifier in identifiers:
|
|
raise ValueError(f'Duplicate Dart identifier: {identifier}')
|
|
identifiers.add(identifier)
|
|
if type(codepoint) is not int or not 0xe000 <= codepoint <= 0xf8ff:
|
|
raise ValueError(f'Invalid private-use codepoint: {name}')
|
|
lines.extend([
|
|
f' static const IconData {identifier} = IconData(',
|
|
f' 0x{codepoint:04x},',
|
|
f" fontFamily: '{family}',",
|
|
" fontPackage: 'cutdex_ui',",
|
|
])
|
|
if name in MIRRORED:
|
|
lines.append(' matchTextDirection: true,')
|
|
lines.append(' );')
|
|
lines.append('}')
|
|
return '\n'.join(lines) + '\n'
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
actions = parser.add_mutually_exclusive_group()
|
|
actions.add_argument('--update', metavar='COMMIT_SHA', help='refresh official font resources')
|
|
actions.add_argument('--check', action='store_true', help='verify resources and generated output')
|
|
args = parser.parse_args()
|
|
try:
|
|
if args.update:
|
|
update_catalog(args.update)
|
|
output = generate(json.loads(SOURCE.read_text(encoding='utf-8')))
|
|
if args.check:
|
|
if not OUTPUT.exists() or OUTPUT.read_text(encoding='utf-8') != output:
|
|
print('Generated icons are stale. Run tool/generate_icons.py.', file=sys.stderr)
|
|
return 1
|
|
print('Phosphor font checksums and generated icons are current.')
|
|
else:
|
|
OUTPUT.parent.mkdir(parents=True, exist_ok=True)
|
|
OUTPUT.write_text(output, encoding='utf-8')
|
|
print(f'Generated {OUTPUT.relative_to(ROOT)}')
|
|
return 0
|
|
except (OSError, ValueError, KeyError) as error:
|
|
print(str(error), file=sys.stderr)
|
|
return 1
|
|
|
|
|
|
if __name__ == '__main__':
|
|
sys.exit(main())
|