| 1 |
#!/usr/bin/env python3 |
| 2 |
|
| 3 |
# Check Python version. |
| 4 |
import sys |
| 5 |
if sys.version_info < (3,7): |
| 6 |
print('While emo.py avoids recent Python features to maximize compatibility,') |
| 7 |
print('it does require 3.7 or later. Please upgrade your Python.') |
| 8 |
sys.exit(1) |
| 9 |
|
| 10 |
# ------------------------------------------------------------------------- |
| 11 |
# (C) Copyright 2023 by Robert Grimm, released under the Apache 2.0 license |
| 12 |
# ------------------------------------------------------------------------- |
| 13 |
|
| 14 |
from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter |
| 15 |
from dataclasses import dataclass, field |
| 16 |
from datetime import datetime |
| 17 |
from enum import Enum |
| 18 |
from itertools import chain |
| 19 |
import json |
| 20 |
import os |
| 21 |
from pathlib import Path |
| 22 |
import re |
| 23 |
import shutil |
| 24 |
import subprocess |
| 25 |
from typing import ( |
| 26 |
Any, Dict, Iterable, KeysView, List, Mapping, |
| 27 |
NoReturn, Optional, TextIO, Tuple, Union |
| 28 |
) |
| 29 |
from urllib.request import urlopen |
| 30 |
|
| 31 |
# -------------------------------------------------------------------------------------- |
| 32 |
# Provide a simple console logger |
| 33 |
|
| 34 |
class Logger: |
| 35 |
def __init__(self, out: TextIO = sys.stderr) -> None: |
| 36 |
self._out = out |
| 37 |
self._first_header = True |
| 38 |
|
| 39 |
def sgr(self, open: str, text: str, close: str) -> str: |
| 40 |
if self._out.isatty(): |
| 41 |
return f'\x1b[{open}m{text}\x1b[{close}m' |
| 42 |
return text |
| 43 |
|
| 44 |
def pln(self, text: str = '') -> None: |
| 45 |
print(text, file=self._out) |
| 46 |
|
| 47 |
def header(self, text: str) -> None: |
| 48 |
if self._first_header: |
| 49 |
self._first_header = False |
| 50 |
else: |
| 51 |
self.pln() |
| 52 |
self.pln(self.sgr('1', text, '0')) |
| 53 |
|
| 54 |
def detail(self, text: str) -> None: |
| 55 |
self.pln(f' {text}') |
| 56 |
|
| 57 |
def error(self, text: str) -> None: |
| 58 |
self.pln(self.sgr('1;31', f'ERROR: {text}', '0;39')) |
| 59 |
|
| 60 |
def warning(self, text: str) -> None: |
| 61 |
self.pln(self.sgr('1;38;5;208', f'WARNING: {text}', '0;39')) |
| 62 |
|
| 63 |
def info(self, text: str) -> None: |
| 64 |
self.pln(self.sgr('1;34', f'INFO: {text}', '0;39')) |
| 65 |
|
| 66 |
logger = Logger() |
| 67 |
|
| 68 |
# -------------------------------------------------------------------------------------- |
| 69 |
# Build a self-contained `demo.html` |
| 70 |
|
| 71 |
STYLE_LINK = re.compile( |
| 72 |
f'<link rel="stylesheet" href="(?P<sheet>[^"]+)" type="text/css">' |
| 73 |
) |
| 74 |
|
| 75 |
def make_demo(): |
| 76 |
# Write extra styles to file. |
| 77 |
logger.info('Writing auxiliary style sheet "demo.css"') |
| 78 |
with open('demo.css', mode='w', encoding='utf8') as file: |
| 79 |
file.write(""" |
| 80 |
:root { |
| 81 |
font-size: 300%; |
| 82 |
} |
| 83 |
""") |
| 84 |
|
| 85 |
# Convert to HTML and read in result. |
| 86 |
logger.info('Converting LaTeX source in "demo.tex" to HTML in "demo.tmp.html"') |
| 87 |
subprocess.run([ |
| 88 |
'latexmlc', |
| 89 |
'--css=demo.css', |
| 90 |
'--destination=demo.tmp.html', |
| 91 |
'demo.tex'] |
| 92 |
) |
| 93 |
with open('demo.tmp.html', mode='r', encoding='utf8') as file: |
| 94 |
content = file.read() |
| 95 |
|
| 96 |
# Find all links to style sheets and replace them with CSS content. |
| 97 |
style_sheets = [] |
| 98 |
fragments = [] |
| 99 |
|
| 100 |
last_index = 0 |
| 101 |
for link in STYLE_LINK.finditer(content): |
| 102 |
fragments.append(content[last_index:link.start()]) |
| 103 |
|
| 104 |
style_sheet = link.group('sheet') |
| 105 |
style_sheets.append(style_sheet) |
| 106 |
|
| 107 |
logger.info(f'Loading style sheet "{style_sheet}"') |
| 108 |
with open(style_sheet, mode='r', encoding='utf8') as file: |
| 109 |
css = file.read() |
| 110 |
if not css.startswith('\n'): |
| 111 |
css = f'\n{css}' |
| 112 |
|
| 113 |
fragments.append(f'<style>{css}</style>') |
| 114 |
last_index = link.end() |
| 115 |
|
| 116 |
fragments.append(content[last_index:]) |
| 117 |
|
| 118 |
# Write result and clean up. |
| 119 |
logger.info(f'Writing self-contained HTML document "demo.html"') |
| 120 |
with open('demo.html', mode='w', encoding='utf8') as file: |
| 121 |
for fragment in fragments: |
| 122 |
file.write(fragment) |
| 123 |
|
| 124 |
os.unlink('demo.tmp.html') |
| 125 |
for style_sheet in style_sheets: |
| 126 |
os.unlink(style_sheet) |
| 127 |
|
| 128 |
# -------------------------------------------------------------------------------------- |
| 129 |
# Build an archive for release |
| 130 |
|
| 131 |
EMO_FILES = ( |
| 132 |
'emo.def', |
| 133 |
'emo.dtx', |
| 134 |
'emo.pdf', |
| 135 |
'emo-lingchi.ttf', |
| 136 |
'README.md', |
| 137 |
'config/emo.py', |
| 138 |
'config/emoji-test.txt' |
| 139 |
) |
| 140 |
|
| 141 |
EMO_GRAPHICS = 'emo-graphics' |
| 142 |
|
| 143 |
EMO_METADATA = re.compile( |
| 144 |
r""" |
| 145 |
^[ ]{4}\[ |
| 146 |
(?P<date>\d{4}/\d{1,2}/\d{1,2}) |
| 147 |
[ ] |
| 148 |
v(?P<version>\d+\.\d+) |
| 149 |
[ ] |
| 150 |
(?P<info>[^\]]+) |
| 151 |
\] |
| 152 |
""", |
| 153 |
re.VERBOSE | re.MULTILINE |
| 154 |
) |
| 155 |
|
| 156 |
def make_release() -> None: |
| 157 |
# Determine repository root. |
| 158 |
source = Path(__file__).parent.parent |
| 159 |
|
| 160 |
# Determine package metadata. |
| 161 |
metadata = EMO_METADATA.search((source / 'emo.dtx').read_text(encoding='utf8')) |
| 162 |
if metadata is None: |
| 163 |
raise ValueError(f'Package metadata missing from "{source / "emo.dtx"}"') |
| 164 |
|
| 165 |
version = metadata.group('version') |
| 166 |
logger.info(f'Preparing release {version} for "{source}"') |
| 167 |
|
| 168 |
# Make sure no archive exists. |
| 169 |
archive = source / f'emo-{version}.zip' |
| 170 |
if archive.exists(): |
| 171 |
raise ValueError( |
| 172 |
f'Archive file "{archive}" already exists, please move out of way.' |
| 173 |
) |
| 174 |
|
| 175 |
# Set up staging directory. |
| 176 |
staging = source / 'emo' |
| 177 |
if staging.exists(): |
| 178 |
raise ValueError( |
| 179 |
f'Staging directory "{staging}" already exists, please move out of way.' |
| 180 |
) |
| 181 |
logger.info(f'Creating staging directory "{staging}"') |
| 182 |
staging.mkdir() |
| 183 |
|
| 184 |
# Process all files belonging into release. |
| 185 |
for path in chain(map(Path, EMO_FILES), source.glob('emo-graphics/emo-*.pdf')): |
| 186 |
path = source / path |
| 187 |
|
| 188 |
# To stage a file in the repository root, just copy it. |
| 189 |
if path.parent == source: |
| 190 |
logger.info(f'Staging "{path.name}"') |
| 191 |
shutil.copy(path, staging) |
| 192 |
continue |
| 193 |
|
| 194 |
# To stage a file in a subdirectory, get relative path and, if necessary, |
| 195 |
# recreate path in staging area. Then copy into that subdirectory. |
| 196 |
nested_staging = staging / path.parent.relative_to(source) |
| 197 |
if not nested_staging.exists(): |
| 198 |
logger.info(f'Creating nested staging directory "{nested_staging}"') |
| 199 |
nested_staging.mkdir(parents=True) |
| 200 |
|
| 201 |
logger.info(f'Staging "{path.relative_to(source)}"') |
| 202 |
shutil.copy(path, nested_staging) |
| 203 |
|
| 204 |
# Create archive. |
| 205 |
shutil.make_archive( |
| 206 |
str(archive.with_suffix('')), |
| 207 |
'zip', |
| 208 |
root_dir=staging.parent, |
| 209 |
base_dir=staging.name, |
| 210 |
) |
| 211 |
|
| 212 |
# -------------------------------------------------------------------------------------- |
| 213 |
# Normalize emoji names |
| 214 |
|
| 215 |
PUNCTUATION = re.compile(r"""["'’“”&!(),:]""") |
| 216 |
SEPARATORS = re.compile(r'[ _\-]+') |
| 217 |
|
| 218 |
# The list of name overrides. |
| 219 |
RENAMING = { |
| 220 |
'a-button-blood-type': 'a-button', |
| 221 |
'ab-button-blood-type': 'ab-button', |
| 222 |
'b-button-blood-type': 'b-button', |
| 223 |
'o-button-blood-type': 'o-button', |
| 224 |
'bust-in-silhouette': 'bust', |
| 225 |
'busts-in-silhouette': 'busts', |
| 226 |
'flag-european-union': 'eu', |
| 227 |
'globe-showing-americas': 'globe-americas', |
| 228 |
'globe-showing-asia-australia': 'globe-asia-australia', |
| 229 |
'globe-showing-europe-africa': 'globe-africa-europe', |
| 230 |
'hear-no-evil-monkey': 'hear-no-evil', |
| 231 |
'index-pointing-at-the-viewer': 'index-pointing-at-viewer', |
| 232 |
'index-pointing-at-the-viewer-darkest': 'index-pointing-at-viewer-darkest', |
| 233 |
'index-pointing-at-the-viewer-darker': 'index-pointing-at-viewer-darker', |
| 234 |
'index-pointing-at-the-viewer-medium': 'index-pointing-at-viewer-medium', |
| 235 |
'index-pointing-at-the-viewer-lighter': 'index-pointing-at-viewer-lighter', |
| 236 |
'index-pointing-at-the-viewer-lightest': 'index-pointing-at-viewer-lightest', |
| 237 |
'keycap-*': 'keycap-star', |
| 238 |
'keycap-#': 'keycap-hash', |
| 239 |
'keycap-0': 'keycap-zero', |
| 240 |
'keycap-1': 'keycap-one', |
| 241 |
'keycap-2': 'keycap-two', |
| 242 |
'keycap-3': 'keycap-three', |
| 243 |
'keycap-4': 'keycap-four', |
| 244 |
'keycap-5': 'keycap-five', |
| 245 |
'keycap-6': 'keycap-six', |
| 246 |
'keycap-7': 'keycap-seven', |
| 247 |
'keycap-8': 'keycap-eight', |
| 248 |
'keycap-9': 'keycap-nine', |
| 249 |
'keycap-10': 'keycap-ten', |
| 250 |
'magnifying-glass-tilted-left': 'loupe-left', |
| 251 |
'magnifying-glass-tilted-right': 'loupe-right', |
| 252 |
'palm-down-hand': 'palm-down', |
| 253 |
'palm-down-hand-darkest': 'palm-down-darkest', |
| 254 |
'palm-down-hand-darker': 'palm-down-darker', |
| 255 |
'palm-down-hand-medium': 'palm-down-medium', |
| 256 |
'palm-down-hand-lighter': 'palm-down-lighter', |
| 257 |
'palm-down-hand-lightest': 'palm-down-lightest', |
| 258 |
'palm-up-hand': 'palm-up', |
| 259 |
'palm-up-hand-darkest': 'palm-up-darkest', |
| 260 |
'palm-up-hand-darker': 'palm-up-darker', |
| 261 |
'palm-up-hand-medium': 'palm-up-medium', |
| 262 |
'palm-up-hand-lighter': 'palm-up-lighter', |
| 263 |
'palm-up-hand-lightest': 'palm-up-lightest', |
| 264 |
'rolling-on-the-floor-laughing': 'rofl', |
| 265 |
'see-no-evil-monkey': 'see-no-evil', |
| 266 |
'speak-no-evil-monkey': 'speak-no-evil', |
| 267 |
} |
| 268 |
|
| 269 |
def to_name(value: str) -> str: |
| 270 |
"""Turn the given string as an emoji name.""" |
| 271 |
name = value.lower() |
| 272 |
name = PUNCTUATION.sub('', name) |
| 273 |
name = SEPARATORS.sub('-', name) |
| 274 |
|
| 275 |
# Use simpler skin tone indicators. Do not reorder. |
| 276 |
name = name.replace('medium-dark-skin-tone', 'darker') |
| 277 |
name = name.replace('medium-light-skin-tone', 'lighter') |
| 278 |
name = name.replace('medium-skin-tone', 'medium') |
| 279 |
name = name.replace('dark-skin-tone', 'darkest') |
| 280 |
name = name.replace('light-skin-tone', 'lightest') |
| 281 |
|
| 282 |
return RENAMING.get(name, name) |
| 283 |
|
| 284 |
|
| 285 |
# -------------------------------------------------------------------------------------- |
| 286 |
# Handle emoji codepoints |
| 287 |
|
| 288 |
def to_codepoint(cp: Union[int, str]) -> int: |
| 289 |
if isinstance(cp, int): |
| 290 |
return cp |
| 291 |
if cp.startswith(('0x', 'U+')): |
| 292 |
cp = cp[2:] |
| 293 |
return int(cp, base=16) |
| 294 |
|
| 295 |
def to_codepoints(value: Union[str, Iterable[Union[int,str]]]) -> Tuple[int, ...]: |
| 296 |
if isinstance(value, str): |
| 297 |
return tuple(ord(c) for c in value) |
| 298 |
return tuple(to_codepoint(cp) for cp in value) |
| 299 |
|
| 300 |
REGIONAL_INDICATOR_A = 0x1f1e6 |
| 301 |
REGIONAL_INDICATOR_Z = 0x1f1ff |
| 302 |
LETTER_CAPITAL_A = ord('A') |
| 303 |
|
| 304 |
def is_regional_indicator(cp: int) -> bool: |
| 305 |
return REGIONAL_INDICATOR_A <= cp <= REGIONAL_INDICATOR_Z |
| 306 |
|
| 307 |
def regional_indicator_to_letter(cp: int) -> str: |
| 308 |
return chr(cp - REGIONAL_INDICATOR_A + LETTER_CAPITAL_A) |
| 309 |
|
| 310 |
|
| 311 |
# -------------------------------------------------------------------------------------- |
| 312 |
# Normalize emoji group and subgroup names |
| 313 |
|
| 314 |
AMPERSAND = re.compile('[ ]*&[ ]*') |
| 315 |
|
| 316 |
SHORT_GROUPS = { |
| 317 |
'animals': 'animals-and-nature', |
| 318 |
'body': 'people-and-body', |
| 319 |
'drink': 'food-and-drink', |
| 320 |
'emotion': 'smileys-and-emotion', |
| 321 |
'food': 'food-and-drink', |
| 322 |
'nature': 'animals-and-nature', |
| 323 |
'people': 'people-and-body', |
| 324 |
'places': 'travel-and-places', |
| 325 |
'smileys': 'smileys-and-emotion', |
| 326 |
'travel': 'travel-and-places', |
| 327 |
} |
| 328 |
|
| 329 |
def to_group(group: str) -> str: |
| 330 |
group = group.lower() |
| 331 |
group = SHORT_GROUPS.get(group, group) |
| 332 |
return AMPERSAND.sub('-and-', group) |
| 333 |
|
| 334 |
def to_subgroup(subgroup: str) -> str: |
| 335 |
subgroup = subgroup.lower() |
| 336 |
return AMPERSAND.sub('-and-', subgroup) |
| 337 |
|
| 338 |
def to_group_subgroup(group: str, subgroup: str) -> Tuple[str, str]: |
| 339 |
return to_group(group), to_subgroup(subgroup) |
| 340 |
|
| 341 |
def is_subgroup_selector(identifier: str) -> bool: |
| 342 |
return '::' in identifier |
| 343 |
|
| 344 |
def split_subgroup_selector(identifier: str) -> List[str]: |
| 345 |
return identifier.lower().split('::') |
| 346 |
|
| 347 |
|
| 348 |
# -------------------------------------------------------------------------------------- |
| 349 |
# Define emoji status |
| 350 |
|
| 351 |
class Status(str, Enum): |
| 352 |
COMPONENT = 'component' |
| 353 |
FULLY_QUALIFIED = 'fully-qualified' |
| 354 |
MINIMALLY_QUALIFIED = 'minimally-qualified' |
| 355 |
UNQUALIFIED = 'unqualified' |
| 356 |
|
| 357 |
|
| 358 |
# -------------------------------------------------------------------------------------- |
| 359 |
# Define emoji descriptor |
| 360 |
|
| 361 |
@dataclass(frozen=True, order=True) |
| 362 |
class Emoji: |
| 363 |
"""Representation of an emoji. The status is optional to allow for quick hacks.""" |
| 364 |
name: str = field(compare=False) |
| 365 |
codepoints: Tuple[int,...] |
| 366 |
display: str = field(init=False, compare=False) |
| 367 |
status: Optional[Status] = field(default=None, compare=False) |
| 368 |
version: Optional[float] = field(default=None, compare=False) |
| 369 |
|
| 370 |
def __post_init__(self) -> None: |
| 371 |
display = ''.join(map(lambda cp: chr(cp), self.codepoints)) |
| 372 |
object.__setattr__(self, 'display', display) |
| 373 |
|
| 374 |
@classmethod |
| 375 |
def of( |
| 376 |
cls, |
| 377 |
name: str, |
| 378 |
value: Union[str, Iterable[Union[int,str]]], |
| 379 |
status: Union[str, Status, None] = None, |
| 380 |
version: Union[str, float, None] = None, |
| 381 |
) -> 'Emoji': |
| 382 |
if status is not None and not isinstance(status, Status): |
| 383 |
status = Status(status) |
| 384 |
if isinstance(version, str): |
| 385 |
version = float(version) |
| 386 |
return Emoji(to_name(name), to_codepoints(value), status, version) |
| 387 |
|
| 388 |
def __str__(self) -> str: |
| 389 |
return self.display |
| 390 |
|
| 391 |
def __repr__(self) -> str: |
| 392 |
if self.status is None: |
| 393 |
return f'Emoji.of("{self.name}", "{self.display}")' |
| 394 |
else: |
| 395 |
return f'Emoji.of("{self.name}", "{self.display}", "{self.status.value}")' |
| 396 |
|
| 397 |
@property |
| 398 |
def has_compound_name(self) -> bool: |
| 399 |
return '-' in self.name |
| 400 |
|
| 401 |
@property |
| 402 |
def is_regional_flag(self) -> bool: |
| 403 |
return ( |
| 404 |
len(self.codepoints) == 2 and |
| 405 |
all(is_regional_indicator(cp) for cp in self.codepoints) |
| 406 |
) |
| 407 |
|
| 408 |
@property |
| 409 |
def is_component(self) -> bool: |
| 410 |
return self.status is Status.COMPONENT |
| 411 |
|
| 412 |
@property |
| 413 |
def is_fully_qualified(self) -> bool: |
| 414 |
return self.status is Status.FULLY_QUALIFIED |
| 415 |
|
| 416 |
@property |
| 417 |
def unicode(self) -> str: |
| 418 |
return ' '.join(f'U+{cp:04X}' for cp in self.codepoints) |
| 419 |
|
| 420 |
@property |
| 421 |
def latex_chars(self) -> str: |
| 422 |
return ''.join(f'\char"{cp:04X}' for cp in self.codepoints) |
| 423 |
|
| 424 |
@property |
| 425 |
def svg_file(self) -> str: |
| 426 |
# Emoji for national flags leverage the country's ISO 3166-1 alpha-2 code. |
| 427 |
if self.is_regional_flag: |
| 428 |
return ''.join( |
| 429 |
regional_indicator_to_letter(cp) for cp in self.codepoints |
| 430 |
) + '.svg' |
| 431 |
|
| 432 |
# Skip Emoji presentation selector. |
| 433 |
codepoints = '_'.join(f'{cp:04x}' for cp in self.codepoints if cp != 0xFE0F) |
| 434 |
return f'emoji_u{codepoints}.svg' |
| 435 |
|
| 436 |
@property |
| 437 |
def svg_path(self) -> str: |
| 438 |
if self.is_regional_flag: |
| 439 |
return f'third_party/regional-flags/svg/{self.svg_file}' |
| 440 |
return f'svg/{self.svg_file}' |
| 441 |
|
| 442 |
@property |
| 443 |
def pdf_file(self) -> str: |
| 444 |
return f'emo-{self.name}.pdf' |
| 445 |
|
| 446 |
@property |
| 447 |
def latex_table_entry(self) -> str: |
| 448 |
if self.has_compound_name: |
| 449 |
prefix = f'\expandafter\def\csname emo@emoji@{self.name}\endcsname' |
| 450 |
else: |
| 451 |
prefix = f'\def\emo@emoji@{self.name}' |
| 452 |
|
| 453 |
return f'{prefix}{{{str(self)}}}' |
| 454 |
|
| 455 |
|
| 456 |
# -------------------------------------------------------------------------------------- |
| 457 |
# Parse Unicode TR-51's `emoji-test.txt` |
| 458 |
|
| 459 |
NameTable = Mapping[str, Emoji] |
| 460 |
CodepointTable = Mapping[Tuple[int, ...], Emoji] |
| 461 |
SubgroupTable = Mapping[str, Tuple[Emoji, ...]] |
| 462 |
GroupTable = Mapping[str, SubgroupTable] |
| 463 |
|
| 464 |
class RegistryParser: |
| 465 |
""" |
| 466 |
Parser for the |
| 467 |
`[emoji-test.txt](https://www.unicode.org/Public/emoji/latest/emoji-test.txt)` |
| 468 |
file accompanying [Unicode TR-51](https://www.unicode.org/reports/tr51/). It |
| 469 |
is the most complete listing of Unicode emoji sequences and names and |
| 470 |
conveniently also organizes them into meaningful groups and subgroups. The |
| 471 |
`run()` method returns two tables: |
| 472 |
|
| 473 |
1. The identifier table maps emoji names, emoji (fully qualified and |
| 474 |
otherwise), and Unicode code sequences (fully qualified and otherwise) |
| 475 |
to Emoji instances (fully qualified only). |
| 476 |
2. The group table maps group names to subgroup names to sequences of |
| 477 |
Emoji instances. For group "component," those emoji have component |
| 478 |
status. For all other groups, they are fully qualified. |
| 479 |
""" |
| 480 |
|
| 481 |
def __init__(self, path: Union[str, Path]) -> None: |
| 482 |
self._path: Union[str, Path] = path |
| 483 |
self._lineno = 0 |
| 484 |
self._name_table: Dict[str, Emoji] = {} |
| 485 |
self._codepoint_table: Dict[Tuple[int, ...], Emoji] = {} |
| 486 |
self._group_table: Dict[str, Dict[str, Tuple[Emoji, ...]]] = {} |
| 487 |
self._group_name: Optional[str] = None |
| 488 |
self._group: Optional[Dict[str, Tuple[Emoji, ...]]] = None |
| 489 |
self._subgroup_name: Optional[str] = None |
| 490 |
self._subgroup: Optional[List[Emoji]] = None |
| 491 |
|
| 492 |
def error(self, msg: str) -> NoReturn: |
| 493 |
raise ValueError(f'{self._path}:{self._lineno}: {msg}') |
| 494 |
|
| 495 |
GROUP_PREFIX = '# group: ' |
| 496 |
SUBGROUP_PREFIX = '# subgroup: ' |
| 497 |
EMOJI_DECLARATION = re.compile(r""" |
| 498 |
^ |
| 499 |
(?P<codepoints>[0-9A-F][0-9A-F ]+[0-9A-F]) |
| 500 |
[ ]+ [;] [ ] |
| 501 |
(?P<status>component|fully-qualified|minimally-qualified|unqualified) |
| 502 |
[ ]+ [#] [ ] |
| 503 |
(?P<display>[^ ]+) |
| 504 |
[ ] |
| 505 |
[E](?P<version>[0-9.]+) |
| 506 |
[ ] |
| 507 |
(?P<name>.+) |
| 508 |
$ |
| 509 |
""", re.X) |
| 510 |
|
| 511 |
def parse_line(self, line: str) -> Union[Emoji, Tuple[str, str], None]: |
| 512 |
line = line.strip() |
| 513 |
# Group and subgroup are specified in comments. |
| 514 |
if line.startswith(self.GROUP_PREFIX): |
| 515 |
return 'group', to_group(line[len(self.GROUP_PREFIX):]) |
| 516 |
if line.startswith(self.SUBGROUP_PREFIX): |
| 517 |
return 'subgroup', to_subgroup(line[len(self.SUBGROUP_PREFIX):]) |
| 518 |
if line == '' or line[0] == '#': |
| 519 |
return None |
| 520 |
|
| 521 |
match = self.EMOJI_DECLARATION.match(line) |
| 522 |
if match is None: |
| 523 |
self.error('neither empty, comment, or emoji') |
| 524 |
return Emoji.of( |
| 525 |
match.group('name'), |
| 526 |
match.group('codepoints').split(), |
| 527 |
match.group('status'), |
| 528 |
match.group('version') |
| 529 |
) |
| 530 |
|
| 531 |
def enter_group(self, name: str) -> None: |
| 532 |
assert self._subgroup_name is None |
| 533 |
self._group_name = name |
| 534 |
self._group = self._group_table.setdefault(name, {}) |
| 535 |
|
| 536 |
def enter_subgroup(self, name: str) -> None: |
| 537 |
assert self._subgroup_name is None |
| 538 |
if self._group is None: |
| 539 |
self.error('subgroup without prior group declaration') |
| 540 |
self._subgroup_name = name |
| 541 |
self._subgroup = list(self._group[name]) if name in self._group else [] |
| 542 |
|
| 543 |
def maybe_exit_subgroup(self) -> None: |
| 544 |
if self._subgroup_name is not None: |
| 545 |
assert self._group is not None |
| 546 |
assert self._subgroup is not None |
| 547 |
self._group[self._subgroup_name] = tuple(self._subgroup) |
| 548 |
self._subgroup_name = None |
| 549 |
self._subgroup = None |
| 550 |
|
| 551 |
def add_emoji(self, emoji: Emoji) -> None: |
| 552 |
# There must be a group and subgroup. |
| 553 |
if self._subgroup_name is None: |
| 554 |
self.error('emoji without prior group and subgroup declaration') |
| 555 |
# Only register emoji with new codepoints. |
| 556 |
if emoji.codepoints in self._codepoint_table: |
| 557 |
self.error( |
| 558 |
f'duplicate emoji by codepoints {emoji.display} ({emoji.unicode})' |
| 559 |
) |
| 560 |
# Only register component and fully qualified emoji with new names. |
| 561 |
if emoji.is_component and emoji.name in self._name_table: |
| 562 |
self.error( |
| 563 |
'duplicate declaration of component ' |
| 564 |
f'emoji by name {emoji.display} ({emoji.unicode})' |
| 565 |
) |
| 566 |
if emoji.is_fully_qualified and emoji.name in self._name_table: |
| 567 |
self.error( |
| 568 |
'duplicate declaration of fully qualified ' |
| 569 |
f'emoji by name {emoji.display} ({emoji.unicode})' |
| 570 |
) |
| 571 |
# Only the component group contains only component emoji. |
| 572 |
if self._group_name == 'component' and not emoji.is_component: |
| 573 |
self.error( |
| 574 |
'component group with non-component ' |
| 575 |
f'emoji {emoji.display} ({emoji.unicode})' |
| 576 |
) |
| 577 |
if emoji.is_component and self._group_name != 'component': |
| 578 |
self.error( |
| 579 |
f'component emoji {emoji.display} ({emoji.unicode}) ' |
| 580 |
'outside component group' |
| 581 |
) |
| 582 |
|
| 583 |
# Record all emoji by codepoints. |
| 584 |
self._codepoint_table[emoji.codepoints] = emoji |
| 585 |
|
| 586 |
# Record component and fully qualified emoji also by name and group/subgroup. |
| 587 |
if emoji.is_component or emoji.is_fully_qualified: |
| 588 |
self._name_table[emoji.name] = emoji |
| 589 |
assert self._subgroup is not None |
| 590 |
self._subgroup.append(emoji) |
| 591 |
|
| 592 |
def run(self) -> Tuple[NameTable, CodepointTable, GroupTable]: |
| 593 |
assert self._lineno == 0 |
| 594 |
|
| 595 |
with open(self._path, mode='r', encoding='utf8') as file: |
| 596 |
while True: |
| 597 |
line = file.readline() |
| 598 |
if line == '': |
| 599 |
break |
| 600 |
self._lineno += 1 |
| 601 |
item = self.parse_line(line[:-1]) |
| 602 |
|
| 603 |
if item is None: |
| 604 |
continue |
| 605 |
if isinstance(item, Emoji): |
| 606 |
self.add_emoji(item) |
| 607 |
continue |
| 608 |
|
| 609 |
self.maybe_exit_subgroup() |
| 610 |
grouping, name = item |
| 611 |
if grouping == 'group': |
| 612 |
self.enter_group(name) |
| 613 |
else: |
| 614 |
self.enter_subgroup(name) |
| 615 |
|
| 616 |
self.maybe_exit_subgroup() |
| 617 |
|
| 618 |
# Patch non-component identifiers to point to fully qualified emoji descriptors. |
| 619 |
for identifier, emoji in self._codepoint_table.items(): |
| 620 |
if emoji.is_component or emoji.is_fully_qualified: |
| 621 |
continue |
| 622 |
fully_qualified_emoji = self._name_table.get(emoji.name) |
| 623 |
if fully_qualified_emoji is None: |
| 624 |
self.error( |
| 625 |
f'no fully qualified emoji for {emoji.display} ({emoji.unicode})' |
| 626 |
) |
| 627 |
self._codepoint_table[identifier] = fully_qualified_emoji |
| 628 |
|
| 629 |
return self._name_table, self._codepoint_table, self._group_table |
| 630 |
|
| 631 |
|
| 632 |
# -------------------------------------------------------------------------------------- |
| 633 |
# Maintain emoji registry |
| 634 |
|
| 635 |
class Registry: |
| 636 |
def __init__( |
| 637 |
self, |
| 638 |
name_table: NameTable, |
| 639 |
codepoint_table: CodepointTable, |
| 640 |
group_table: GroupTable |
| 641 |
) -> None: |
| 642 |
"""Create a new emoji registry. Use `from_file()` instead.""" |
| 643 |
self._name_table = name_table |
| 644 |
self._codepoint_table = codepoint_table |
| 645 |
self._group_table = group_table |
| 646 |
|
| 647 |
@classmethod |
| 648 |
def from_file(cls, path: Union[str, Path]) -> 'Registry': |
| 649 |
"""Instantiate a new registry instance from the given file.""" |
| 650 |
return Registry(*RegistryParser(path).run()) |
| 651 |
|
| 652 |
def emoji_names(self) -> KeysView[str]: |
| 653 |
"""Get the names of all registered emoji.""" |
| 654 |
return self._name_table.keys() |
| 655 |
|
| 656 |
def lookup(self, identifier: Union[str, Tuple[int, ...]]) -> Optional[Emoji]: |
| 657 |
"""Look up an emoji by name or codepoints.""" |
| 658 |
if isinstance(identifier, str): |
| 659 |
return self._name_table.get(identifier.lower()) |
| 660 |
return self._codepoint_table.get(identifier) |
| 661 |
|
| 662 |
def is_group(self, group: str) -> bool: |
| 663 |
"""Determine if the group name is valid.""" |
| 664 |
return group in self._group_table |
| 665 |
|
| 666 |
def is_subgroup(self, group: str, subgroup: str) -> bool: |
| 667 |
"""Determine if the subgroup name is valid. The group name must be valid.""" |
| 668 |
return subgroup in self._group_table[group] |
| 669 |
|
| 670 |
def group_names(self) -> KeysView[str]: |
| 671 |
"""Get the names of all groups.""" |
| 672 |
return self._group_table.keys() |
| 673 |
|
| 674 |
def subgroup_names(self, group: str) -> KeysView[str]: |
| 675 |
"""Get the names of all subgroups.""" |
| 676 |
return self._group_table[group].keys() |
| 677 |
|
| 678 |
def subgroup(self, group: str, subgroup: str) -> Tuple[Emoji, ...]: |
| 679 |
"""Get the subgroup of the group.""" |
| 680 |
return self._group_table[group][subgroup] |
| 681 |
|
| 682 |
def subgroup_from_selector(self, selector: str) -> Tuple[Emoji, ...]: |
| 683 |
"""Get the subgroup for the given `group::subgroup` selector.""" |
| 684 |
names = split_subgroup_selector(selector) |
| 685 |
if len(names) != 2: |
| 686 |
raise KeyError(f'selector "{selector}" does not combine two names') |
| 687 |
group, subgroup = to_group_subgroup(*names) |
| 688 |
if not self.is_group(group): |
| 689 |
raise KeyError(f'selector "{selector}" names non-existent group') |
| 690 |
if not self.is_subgroup(group, subgroup): |
| 691 |
raise KeyError(f'selector "{selector}" names non-existent subgroup') |
| 692 |
return self.subgroup(group, subgroup) |
| 693 |
|
| 694 |
def select(self, *selectors: str) -> List[Emoji]: |
| 695 |
"""Get the emoji matching the given selectors.""" |
| 696 |
selection: List[Emoji] = list() |
| 697 |
|
| 698 |
for selector in selectors: |
| 699 |
# 'ALL' -- all emoji |
| 700 |
if selector == 'ALL': |
| 701 |
for group in self.group_names(): |
| 702 |
for subgroup in self.subgroup_names(group): |
| 703 |
selection.extend(self.subgroup(group, subgroup)) |
| 704 |
continue |
| 705 |
|
| 706 |
# group::subgroup -- all emoji in the subgroup |
| 707 |
if is_subgroup_selector(selector): |
| 708 |
selection.extend(self.subgroup_from_selector(selector)) |
| 709 |
continue |
| 710 |
|
| 711 |
# name -- all emoji in the group, if it exists |
| 712 |
group = to_group(selector) |
| 713 |
if self.is_group(group): |
| 714 |
for subgroup in self.subgroup_names(group): |
| 715 |
selection.extend(self.subgroup(group, subgroup)) |
| 716 |
continue |
| 717 |
|
| 718 |
# name -- the named emoji, if it exists |
| 719 |
name = selector.lower() |
| 720 |
if name in self._name_table: |
| 721 |
selection.append(self._name_table[name]) |
| 722 |
continue |
| 723 |
|
| 724 |
raise KeyError(f'selector "{selector}" names neither emoji nor group') |
| 725 |
|
| 726 |
return selection |
| 727 |
|
| 728 |
def dump(self, file: Optional[TextIO] = None) -> None: |
| 729 |
"""Dump the registry contents by groups and subgroups.""" |
| 730 |
if file is None: |
| 731 |
file = sys.stdout |
| 732 |
|
| 733 |
for group in self.group_names(): |
| 734 |
for subgroup in self.subgroup_names(group): |
| 735 |
file.write(group) |
| 736 |
file.write('∷') |
| 737 |
file.write(subgroup) |
| 738 |
file.write(' ≡ ') |
| 739 |
file.write(''.join(e.display for e in self.subgroup(group, subgroup))) |
| 740 |
file.write('\n') |
| 741 |
|
| 742 |
|
| 743 |
# -------------------------------------------------------------------------------------- |
| 744 |
# Download Noto emoji sources |
| 745 |
|
| 746 |
NOTO_REPOSITORY = 'https://github.com/googlefonts/noto-emoji/archive/refs/heads/main.zip' |
| 747 |
|
| 748 |
def is_valid_noto_emoji(noto_path: Path) -> bool: |
| 749 |
if not noto_path.exists(): |
| 750 |
return False |
| 751 |
if not noto_path.is_dir(): |
| 752 |
raise ValueError( |
| 753 |
f'The Noto emoji path "{noto_path}" is not even a directory. ' |
| 754 |
'Please move file out of the way or change path with --noto-emoji.' |
| 755 |
) |
| 756 |
|
| 757 |
entries = set(entry.name for entry in noto_path.iterdir()) |
| 758 |
if ( |
| 759 |
'colrv1' in entries |
| 760 |
and 'svg' in entries |
| 761 |
and 'third_party' in entries |
| 762 |
and 'emoji_aliases.txt' in entries |
| 763 |
): |
| 764 |
return True |
| 765 |
|
| 766 |
raise ValueError( |
| 767 |
f'The Noto emoji path "{noto_path}" points to a directory without ' |
| 768 |
'expected contents. Please move directory out of the way or change ' |
| 769 |
'path with --noto-emoji' |
| 770 |
) |
| 771 |
|
| 772 |
def ensure_local_noto_emoji(noto_path: Path, verbose: bool = False) -> None: |
| 773 |
if is_valid_noto_emoji(noto_path): |
| 774 |
if verbose: |
| 775 |
logger.info(f'Seemingly valid Noto emoji sources at "{noto_path}"') |
| 776 |
return |
| 777 |
|
| 778 |
noto_zip = noto_path.with_name('noto-emoji.zip') |
| 779 |
if not noto_zip.exists(): |
| 780 |
if verbose: |
| 781 |
logger.info(f'Downloading Noto emoji sources from "{NOTO_REPOSITORY}"') |
| 782 |
with urlopen(NOTO_REPOSITORY) as response, open(noto_zip, mode='wb') as file: |
| 783 |
shutil.copyfileobj(response, file) |
| 784 |
|
| 785 |
# With archive representing main branch, it is unpacked into |
| 786 |
# noto-emoji-main. We fix that after unpacking. |
| 787 |
if verbose: |
| 788 |
logger.info(f'Unpacking Noto emoji sources into "{noto_path}"') |
| 789 |
shutil.unpack_archive(noto_zip, noto_path.parent, 'zip') |
| 790 |
noto_path.with_name('noto-emoji-main').rename(noto_path) |
| 791 |
|
| 792 |
|
| 793 |
# -------------------------------------------------------------------------------------- |
| 794 |
# Convert SVG to PDF |
| 795 |
|
| 796 |
def remove_page_group_object(document: dict) -> Optional[dict]: |
| 797 |
"""Remove the /Page /Group object from the document in qpdf's JSON format.""" |
| 798 |
|
| 799 |
objects = document['qpdf'][1] |
| 800 |
|
| 801 |
def resolve(ref: str) -> Any: |
| 802 |
key = ref if ref == 'trailer' else f'obj:{ref}' |
| 803 |
if key not in objects: |
| 804 |
raise KeyError(ref) |
| 805 |
return objects[key] |
| 806 |
|
| 807 |
def resolve_value(ref, type=None) -> Any: |
| 808 |
o = resolve(ref) |
| 809 |
if 'value' not in o: |
| 810 |
raise ValueError(f'{ref} does not reference object') |
| 811 |
v = o['value'] |
| 812 |
if type is not None and v.get('/Type') != type: |
| 813 |
raise ValueError( |
| 814 |
f'{ref} references object of type {v["/Type"]} not {type}' |
| 815 |
) |
| 816 |
return v |
| 817 |
|
| 818 |
trailer = resolve_value('trailer') |
| 819 |
root = resolve_value(trailer['/Root'], '/Catalog') |
| 820 |
pages = resolve_value(root['/Pages'], '/Pages')['/Kids'] |
| 821 |
if len(pages) > 1: |
| 822 |
raise ValueError(f'PDF has {len(pages)} pages instead of just one') |
| 823 |
page = resolve_value(pages[0], '/Page') |
| 824 |
|
| 825 |
if not '/Group' in page: |
| 826 |
return None |
| 827 |
|
| 828 |
del page['/Group'] |
| 829 |
return document |
| 830 |
|
| 831 |
def remove_page_group(path: Path) -> bool: |
| 832 |
with open(path, mode='r', encoding='utf8') as file: |
| 833 |
document = json.load(file) |
| 834 |
|
| 835 |
document = remove_page_group_object(document) |
| 836 |
if document is None: |
| 837 |
return False |
| 838 |
|
| 839 |
tmp = path.with_suffix('.patched.json') |
| 840 |
with open(tmp, mode='w', encoding='utf8') as file: |
| 841 |
json.dump(document, file) |
| 842 |
tmp.replace(path) |
| 843 |
return True |
| 844 |
|
| 845 |
def fix_pdf(qpdf: str, path: Path) -> None: |
| 846 |
json_path = path.with_suffix('.json') |
| 847 |
subprocess.run([qpdf, str(path), '--json-output', str(json_path)], check=True) |
| 848 |
changed = remove_page_group(json_path) |
| 849 |
if not changed: |
| 850 |
return |
| 851 |
|
| 852 |
tmp = path.with_suffix('.patched.pdf') |
| 853 |
subprocess.run([qpdf, str(json_path), '--json-input', str(tmp)], check=True) |
| 854 |
json_path.unlink() |
| 855 |
tmp.replace(path) |
| 856 |
|
| 857 |
def convert_svg_to_pdf(rsvg_convert: str, source: Path, target: Path) -> None: |
| 858 |
subprocess.run([rsvg_convert, str(source), '-f', 'Pdf', '-o', str(target)], check=True) |
| 859 |
|
| 860 |
def which(tool: str) -> str: |
| 861 |
path = shutil.which(tool) |
| 862 |
if path is None: |
| 863 |
raise FileNotFoundError(tool) |
| 864 |
return path |
| 865 |
|
| 866 |
@dataclass(frozen=True) |
| 867 |
class Converter: |
| 868 |
qpdf: str |
| 869 |
rsvg_convert: str |
| 870 |
source_dir: Path |
| 871 |
target_dir: Path |
| 872 |
|
| 873 |
@classmethod |
| 874 |
def create( |
| 875 |
cls, |
| 876 |
source_dir: Union[Path, str], |
| 877 |
target_dir: Union[Path, str], |
| 878 |
) -> 'Converter': |
| 879 |
return cls( |
| 880 |
qpdf = which('qpdf'), |
| 881 |
rsvg_convert = which('rsvg-convert'), |
| 882 |
source_dir = Path(source_dir), |
| 883 |
target_dir = Path(target_dir), |
| 884 |
) |
| 885 |
|
| 886 |
def __call__(self, emoji: 'Emoji', verbose: bool = False) -> Path: |
| 887 |
source = self.source_dir / emoji.svg_path |
| 888 |
target = self.target_dir / emoji.pdf_file |
| 889 |
if not target.exists(): |
| 890 |
if verbose: |
| 891 |
logger.info(f'Converting "{source}" to "{target}"') |
| 892 |
convert_svg_to_pdf(self.rsvg_convert, source, target) |
| 893 |
if verbose: |
| 894 |
logger.info(f'Fixing /Page /Group in "{target}"') |
| 895 |
fix_pdf(self.qpdf, target) |
| 896 |
return target |
| 897 |
|
| 898 |
|
| 899 |
# -------------------------------------------------------------------------------------- |
| 900 |
# Provide tool help and command line options |
| 901 |
|
| 902 |
DESCRIPTION = """ |
| 903 |
Generate emoji table and PDF files for the given selectors. A selector may be a |
| 904 |
group name, a group and subgroup name with a double colon and no spaces between |
| 905 |
them, an emoji name, or `ALL` for all emoji. With some exceptions, an emoji's |
| 906 |
name is the emoji's Unicode name with punctuation stripped, spaces replaced by |
| 907 |
dashes, and skin tone modifiers simplified to `darkest`, `darker`, `medium`, |
| 908 |
`lighter`, and `lightest` (instead of `dark-skin-tone`, `medium-dark-skin-tone`, |
| 909 |
`medium-skin-tone`, `medium-light-skin-tone`, and `light-skin-tone`). If |
| 910 |
suitably named PDF files exist in the graphics directory, they are not recreated |
| 911 |
but included in the emoji table. |
| 912 |
""" |
| 913 |
|
| 914 |
def resolved_path(path: str) -> Path: |
| 915 |
return Path(path).resolve() |
| 916 |
|
| 917 |
def create_parser() -> ArgumentParser: |
| 918 |
parser = ArgumentParser( |
| 919 |
description=DESCRIPTION, |
| 920 |
formatter_class=ArgumentDefaultsHelpFormatter, |
| 921 |
) |
| 922 |
parser.add_argument( |
| 923 |
'--dry-run', |
| 924 |
action='store_true', |
| 925 |
help='do not write to file system' |
| 926 |
) |
| 927 |
parser.add_argument( |
| 928 |
'-v', '--verbose', |
| 929 |
action='store_true', |
| 930 |
help='enable verbose mode' |
| 931 |
) |
| 932 |
parser.add_argument( |
| 933 |
'--registry', |
| 934 |
type=resolved_path, |
| 935 |
default='config/emoji-test.txt', |
| 936 |
metavar='PATH', |
| 937 |
help='use path for file with Unicode emoji sequences', |
| 938 |
) |
| 939 |
parser.add_argument( |
| 940 |
'--noto-emoji', |
| 941 |
type=resolved_path, |
| 942 |
default='noto-emoji', |
| 943 |
metavar='PATH', |
| 944 |
help='use path for directory with Noto color emoji sources', |
| 945 |
) |
| 946 |
parser.add_argument( |
| 947 |
'--graphics', |
| 948 |
type=resolved_path, |
| 949 |
default='emo-graphics', |
| 950 |
metavar='PATH', |
| 951 |
help='use path for directory with generated PDF graphics', |
| 952 |
) |
| 953 |
parser.add_argument( |
| 954 |
'--latex-table', |
| 955 |
type=resolved_path, |
| 956 |
default='emo.def', |
| 957 |
metavar='PATH', |
| 958 |
help='use path for file with LaTeX emoji table', |
| 959 |
) |
| 960 |
|
| 961 |
group = parser.add_mutually_exclusive_group() |
| 962 |
group.add_argument( |
| 963 |
'--show-group-names', |
| 964 |
action='store_true', |
| 965 |
help='show supported group, subgroup names and exit', |
| 966 |
) |
| 967 |
group.add_argument( |
| 968 |
'--show-emoji-names', |
| 969 |
action='store_true', |
| 970 |
help='show supported emoji names and exit', |
| 971 |
) |
| 972 |
group.add_argument( |
| 973 |
'--show-special-names', |
| 974 |
action='store_true', |
| 975 |
help='show map from (simplified) Unicode names to emoji names and exit' |
| 976 |
) |
| 977 |
group.add_argument( |
| 978 |
'--show-names', |
| 979 |
action='store_true', |
| 980 |
help='show group, emoji, as well as special names and exit' |
| 981 |
) |
| 982 |
group.add_argument( |
| 983 |
'--make-demo', |
| 984 |
action='store_true', |
| 985 |
help='make the demo document and exit', |
| 986 |
) |
| 987 |
group.add_argument( |
| 988 |
'-r', '--make-release', |
| 989 |
action='store_true', |
| 990 |
help='make a release and exit', |
| 991 |
) |
| 992 |
|
| 993 |
parser.add_argument( |
| 994 |
'selectors', |
| 995 |
nargs='*', |
| 996 |
help='names of emoji groups or emoji', |
| 997 |
) |
| 998 |
return parser |
| 999 |
|
| 1000 |
# -------------------------------------------------------------------------------------- |
| 1001 |
# Show group, emoji, and special names |
| 1002 |
|
| 1003 |
def show_names(registry: Registry, options: Any) -> bool: |
| 1004 |
showed_something = False |
| 1005 |
|
| 1006 |
if options.show_group_names or options.show_names: |
| 1007 |
logger.header('Supported groups and subgroups:') |
| 1008 |
for group in registry.group_names(): |
| 1009 |
for subgroup in registry.subgroup_names(group): |
| 1010 |
logger.detail(f'{group}::{subgroup}') |
| 1011 |
showed_something = True |
| 1012 |
if options.show_emoji_names or options.show_names: |
| 1013 |
logger.header('Supported emoji names:') |
| 1014 |
names = list(registry.emoji_names()) |
| 1015 |
names.sort() |
| 1016 |
for name in names: |
| 1017 |
logger.detail(f'{name}') |
| 1018 |
showed_something = True |
| 1019 |
if options.show_special_names or options.show_names: |
| 1020 |
logger.header('Map from (simplified) Unicode to (special) emoji names:') |
| 1021 |
for unicode, selector in RENAMING.items(): |
| 1022 |
logger.detail(f'{unicode:40s} ▶ {selector}') |
| 1023 |
showed_something = True |
| 1024 |
return showed_something |
| 1025 |
|
| 1026 |
# -------------------------------------------------------------------------------------- |
| 1027 |
# Create emoji inventory |
| 1028 |
|
| 1029 |
SPECIAL_FILES = ('emo-lingchi.pdf', 'emo-YHWH.pdf') |
| 1030 |
|
| 1031 |
def create_inventory(registry: Registry, options: Any) -> List[Emoji]: |
| 1032 |
specials = list(SPECIAL_FILES) |
| 1033 |
inventory: List[Emoji] = [] |
| 1034 |
|
| 1035 |
if options.graphics.exists() and options.graphics.is_dir(): |
| 1036 |
for entry in options.graphics.iterdir(): |
| 1037 |
if not entry.is_file() or not entry.match('emo-*.pdf'): |
| 1038 |
continue |
| 1039 |
|
| 1040 |
if entry.name in SPECIAL_FILES: |
| 1041 |
specials.remove(entry.name) |
| 1042 |
continue |
| 1043 |
|
| 1044 |
emoji = registry.lookup(entry.stem[4:]) |
| 1045 |
if emoji is not None: |
| 1046 |
inventory.append(emoji) |
| 1047 |
elif options.verbose: |
| 1048 |
logger.warning(f'"{entry.name}" does not depict an emoji') |
| 1049 |
|
| 1050 |
if len(specials) == 1: |
| 1051 |
raise FileNotFoundError(f'PDF graphic "emo-graphics/{specials[0]}" is missing!') |
| 1052 |
elif len(specials) == 2: |
| 1053 |
raise FileNotFoundError( |
| 1054 |
f'PDF graphics "{specials[0]}" and "{specials[1]}" ' |
| 1055 |
'in "emo-graphics" are missing!' |
| 1056 |
) |
| 1057 |
|
| 1058 |
return inventory |
| 1059 |
|
| 1060 |
# -------------------------------------------------------------------------------------- |
| 1061 |
# Write emoji table |
| 1062 |
|
| 1063 |
def write_emoji_table( |
| 1064 |
requested_emoji: List[Emoji], existing_emoji: List[Emoji], options: Any |
| 1065 |
) -> List[Emoji]: |
| 1066 |
all_emoji = list(set(requested_emoji) | set(existing_emoji)) |
| 1067 |
all_emoji.sort() |
| 1068 |
|
| 1069 |
tmp_table = options.latex_table.with_suffix('.latest.def') |
| 1070 |
if not options.dry_run: |
| 1071 |
with open(tmp_table, mode='w', encoding='utf8') as file: |
| 1072 |
today = datetime.today().strftime('%Y-%m-%d') |
| 1073 |
file.write(f'\\ProvidesFile{{emo.def}}[{today}]\n') |
| 1074 |
for emoji in all_emoji: |
| 1075 |
file.write(emoji.latex_table_entry) |
| 1076 |
file.write('\n') |
| 1077 |
file.write(""" |
| 1078 |
\\ifemo@extra |
| 1079 |
\\def\\emo@emoji@lingchi{凌遲} |
| 1080 |
\\def\\emo@emoji@YHWH{\\begingroup\\textdir TRT יהוה\\endgroup} |
| 1081 |
\\fi |
| 1082 |
""") |
| 1083 |
tmp_table.replace(options.latex_table) |
| 1084 |
|
| 1085 |
return all_emoji |
| 1086 |
|
| 1087 |
# -------------------------------------------------------------------------------------- |
| 1088 |
# Run this script |
| 1089 |
|
| 1090 |
def main() -> None: |
| 1091 |
try: |
| 1092 |
# Parse command line options. |
| 1093 |
options = create_parser().parse_args() |
| 1094 |
|
| 1095 |
# Create release. |
| 1096 |
if (options.make_release or options.make_demo) and options.dry_run: |
| 1097 |
raise ValueError('Unable to dry run selected build function') |
| 1098 |
elif options.make_release: |
| 1099 |
make_release() |
| 1100 |
return |
| 1101 |
elif options.make_demo: |
| 1102 |
make_demo() |
| 1103 |
return |
| 1104 |
|
| 1105 |
# Populate registry, maybe list names. |
| 1106 |
registry = Registry.from_file(options.registry) |
| 1107 |
if show_names(registry, options): |
| 1108 |
return |
| 1109 |
|
| 1110 |
# Determine requested emoji. |
| 1111 |
requested_emoji = registry.select(*options.selectors) |
| 1112 |
|
| 1113 |
# Ensure directory for PDF graphics exists and create converter. |
| 1114 |
if not options.dry_run: |
| 1115 |
options.graphics.mkdir(parents=True, exist_ok=True) |
| 1116 |
convert = Converter.create(options.noto_emoji, options.graphics) |
| 1117 |
|
| 1118 |
# Create inventory of existing emoji. |
| 1119 |
existing_emoji = create_inventory(registry, options) |
| 1120 |
|
| 1121 |
# Download Noto emoji sources if they haven't been before. |
| 1122 |
if not options.dry_run: |
| 1123 |
ensure_local_noto_emoji(options.noto_emoji, options.verbose) |
| 1124 |
|
| 1125 |
# Convert requested emoji, which does not recreate existing emoji. |
| 1126 |
if not options.dry_run: |
| 1127 |
for emoji in requested_emoji: |
| 1128 |
convert(emoji, options.verbose) |
| 1129 |
|
| 1130 |
# Write the emoji table for all emoji. |
| 1131 |
all_emoji = write_emoji_table(requested_emoji, existing_emoji, options) |
| 1132 |
|
| 1133 |
if options.verbose: |
| 1134 |
logger.info('Supported emoji: ' + ' '.join(e.display for e in all_emoji)) |
| 1135 |
|
| 1136 |
except Exception as x: |
| 1137 |
logger.error(str(x)) |
| 1138 |
|
| 1139 |
|
| 1140 |
if __name__ == '__main__': |
| 1141 |
main() |