| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
from __future__ import annotations |
| 15 |
from collections import Counter |
| 16 |
from data.makeutypedata import VISUAL_ALTS, Pose, get_pose |
| 17 |
from functools import partial |
| 18 |
from itertools import chain |
| 19 |
from typing import Iterator, List, Optional, Set, Tuple |
| 20 |
|
| 21 |
import dataclasses |
| 22 |
import enum |
| 23 |
import os |
| 24 |
import re |
| 25 |
import sys |
| 26 |
|
| 27 |
BASE = os.path.dirname(os.path.abspath(__file__)) |
| 28 |
SCRIPT = os.path.basename(__file__) |
| 29 |
|
| 30 |
UNIDATA_VERSION = "17.0.0" |
| 31 |
UNICODE_DATA = "UnicodeData%s.txt" |
| 32 |
DERIVED_CORE_PROPERTIES = "DerivedCoreProperties%s.txt" |
| 33 |
PROP_LIST = "PropList%s.txt" |
| 34 |
BIDI_MIRRORING = "BidiMirroring%s.txt" |
| 35 |
BLOCKS = "Blocks%s.txt" |
| 36 |
NAMES_LIST = "NamesList%s.txt" |
| 37 |
UNICODE_MAX = 0x110000 |
| 38 |
|
| 39 |
DATA_DIR = "data" |
| 40 |
|
| 41 |
|
| 42 |
class UcdTypeFlags(enum.IntFlag): |
| 43 |
FF_UNICODE_ISUNICODEPOINTASSIGNED = 0x1 |
| 44 |
FF_UNICODE_ISALPHA = 0x2 |
| 45 |
FF_UNICODE_ISIDEOGRAPHIC = 0x4 |
| 46 |
FF_UNICODE_ISLEFTTORIGHT = 0x10 |
| 47 |
FF_UNICODE_ISRIGHTTOLEFT = 0x20 |
| 48 |
FF_UNICODE_ISLOWER = 0x40 |
| 49 |
FF_UNICODE_ISUPPER = 0x80 |
| 50 |
FF_UNICODE_ISDIGIT = 0x100 |
| 51 |
FF_UNICODE_ISLIGVULGFRAC = 0x200 |
| 52 |
FF_UNICODE_ISCOMBINING = 0x400 |
| 53 |
FF_UNICODE_ISZEROWIDTH = 0x800 |
| 54 |
FF_UNICODE_ISEURONUMERIC = 0x1000 |
| 55 |
FF_UNICODE_ISEURONUMTERM = 0x2000 |
| 56 |
FF_UNICODE_ISARABNUMERIC = 0x4000 |
| 57 |
FF_UNICODE_ISDECOMPOSITIONNORMATIVE = 0x8000 |
| 58 |
FF_UNICODE_ISDECOMPCIRCLE = 0x10000 |
| 59 |
FF_UNICODE_ISARABINITIAL = 0x20000 |
| 60 |
FF_UNICODE_ISARABMEDIAL = 0x40000 |
| 61 |
FF_UNICODE_ISARABFINAL = 0x80000 |
| 62 |
FF_UNICODE_ISARABISOLATED = 0x100000 |
| 63 |
|
| 64 |
|
| 65 |
@dataclasses.dataclass |
| 66 |
class UcdRecord: |
| 67 |
|
| 68 |
|
| 69 |
codepoint: str |
| 70 |
name: str |
| 71 |
general_category: str |
| 72 |
canonical_combining_class: str |
| 73 |
bidi_class: str |
| 74 |
decomposition_type: str |
| 75 |
numeric_value1: str |
| 76 |
numeric_value2: str |
| 77 |
numeric_value3: str |
| 78 |
bidi_mirrored: str |
| 79 |
unicode_1_name: str |
| 80 |
iso_comment: str |
| 81 |
simple_uppercase_mapping: str |
| 82 |
simple_lowercase_mapping: str |
| 83 |
simple_titlecase_mapping: str |
| 84 |
|
| 85 |
|
| 86 |
|
| 87 |
|
| 88 |
|
| 89 |
binary_properties: Set[str] |
| 90 |
|
| 91 |
|
| 92 |
|
| 93 |
bidi_mirroring: str |
| 94 |
|
| 95 |
@staticmethod |
| 96 |
def from_row(row: List[str]) -> UcdRecord: |
| 97 |
return UcdRecord(*row, set(), "") |
| 98 |
|
| 99 |
|
| 100 |
class UcdFile: |
| 101 |
""" |
| 102 |
A file in the standard format of the UCD. |
| 103 |
|
| 104 |
See: https://www.unicode.org/reports/tr44/#Format_Conventions |
| 105 |
|
| 106 |
Note that, as described there, the Unihan data files have their |
| 107 |
own separate format. |
| 108 |
""" |
| 109 |
|
| 110 |
@staticmethod |
| 111 |
def open_data(template, version): |
| 112 |
local = os.path.join(DATA_DIR, template % ("-" + version,)) |
| 113 |
if not os.path.exists(local): |
| 114 |
import urllib.request |
| 115 |
|
| 116 |
url = ("https://www.unicode.org/Public/%s/ucd/" + template) % (version, "") |
| 117 |
print("Fetching", url) |
| 118 |
os.makedirs(DATA_DIR, exist_ok=True) |
| 119 |
urllib.request.urlretrieve(url, filename=local) |
| 120 |
if local.endswith(".txt"): |
| 121 |
return open(local, encoding="utf-8") |
| 122 |
else: |
| 123 |
|
| 124 |
return open(local, "rb") |
| 125 |
|
| 126 |
@staticmethod |
| 127 |
def expand_range(char_range: str) -> Iterator[int]: |
| 128 |
""" |
| 129 |
Parses ranges of code points, as described in UAX #44: |
| 130 |
https://www.unicode.org/reports/tr44/#Code_Point_Ranges |
| 131 |
""" |
| 132 |
if ".." in char_range: |
| 133 |
first, last = [int(c, 16) for c in char_range.split("..")] |
| 134 |
else: |
| 135 |
first = last = int(char_range, 16) |
| 136 |
for char in range(first, last + 1): |
| 137 |
yield char |
| 138 |
|
| 139 |
def __init__(self, template: str, version: str) -> None: |
| 140 |
self.template = template |
| 141 |
self.version = version |
| 142 |
|
| 143 |
def records(self) -> Iterator[List[str]]: |
| 144 |
print("Reading", self.template % ("-" + self.version,)) |
| 145 |
with self.open_data(self.template, self.version) as file: |
| 146 |
for line in file: |
| 147 |
line = line.split("#", 1)[0].strip() |
| 148 |
if not line: |
| 149 |
continue |
| 150 |
yield [field.strip() for field in line.split(";")] |
| 151 |
|
| 152 |
def __iter__(self) -> Iterator[List[str]]: |
| 153 |
return self.records() |
| 154 |
|
| 155 |
def expanded(self) -> Iterator[Tuple[int, List[str]]]: |
| 156 |
for record in self.records(): |
| 157 |
char_range, rest = record[0], record[1:] |
| 158 |
for char in self.expand_range(char_range): |
| 159 |
yield char, rest |
| 160 |
|
| 161 |
|
| 162 |
class NamesList: |
| 163 |
def __init__(self, template: str, version: str) -> None: |
| 164 |
self.template = template |
| 165 |
self.version = version |
| 166 |
|
| 167 |
def records(self) -> Iterator[List[str]]: |
| 168 |
with UcdFile.open_data(self.template, self.version) as file: |
| 169 |
parts = [] |
| 170 |
for line in file: |
| 171 |
line = line.split(";", 1)[0] |
| 172 |
if not line: |
| 173 |
continue |
| 174 |
line = [field.strip() for field in line.split("\t")] |
| 175 |
if not line: |
| 176 |
continue |
| 177 |
if line[0] and parts: |
| 178 |
yield parts |
| 179 |
parts.clear() |
| 180 |
parts.append(line) |
| 181 |
if parts: |
| 182 |
yield parts |
| 183 |
|
| 184 |
def __iter__(self) -> Iterator[List[str]]: |
| 185 |
return self.records() |
| 186 |
|
| 187 |
|
| 188 |
|
| 189 |
|
| 190 |
|
| 191 |
|
| 192 |
|
| 193 |
|
| 194 |
|
| 195 |
class UnicodeData: |
| 196 |
table: List[Optional[UcdRecord]] |
| 197 |
|
| 198 |
def __init__(self, version): |
| 199 |
table = [None] * UNICODE_MAX |
| 200 |
for s in UcdFile(UNICODE_DATA, version): |
| 201 |
char = int(s[0], 16) |
| 202 |
table[char] = UcdRecord.from_row(s) |
| 203 |
|
| 204 |
|
| 205 |
special_name_ranges = { |
| 206 |
"HANGUL SYLLABLE": [], |
| 207 |
"CJK UNIFIED IDEOGRAPH": [], |
| 208 |
"TANGUT IDEOGRAPH": [], |
| 209 |
} |
| 210 |
|
| 211 |
|
| 212 |
field = None |
| 213 |
for i in range(0, UNICODE_MAX): |
| 214 |
|
| 215 |
|
| 216 |
|
| 217 |
s = table[i] |
| 218 |
if s: |
| 219 |
if s.name[-6:] == "First>": |
| 220 |
s.name = "" |
| 221 |
field = dataclasses.astuple(s)[:15] |
| 222 |
elif s.name[-5:] == "Last>": |
| 223 |
field_range = (int(field[0], 16), int(s.codepoint, 16)) |
| 224 |
if s.name.startswith("<Hangul Syllable"): |
| 225 |
special_name_ranges["HANGUL SYLLABLE"].append(field_range) |
| 226 |
elif s.name.startswith("<CJK Ideograph"): |
| 227 |
special_name_ranges["CJK UNIFIED IDEOGRAPH"].append(field_range) |
| 228 |
elif s.name.startswith("<Tangut Ideograph"): |
| 229 |
special_name_ranges["TANGUT IDEOGRAPH"].append(field_range) |
| 230 |
s.name = "" |
| 231 |
field = None |
| 232 |
elif field: |
| 233 |
table[i] = UcdRecord.from_row(("%X" % i,) + field[1:]) |
| 234 |
|
| 235 |
blocks = [] |
| 236 |
for block_range, block in UcdFile(BLOCKS, version): |
| 237 |
start, end = [int(c, 16) for c in block_range.split("..")] |
| 238 |
first_char = next((i for i in range(start, end + 1) if table[i]), start) |
| 239 |
num_assigned = sum(1 for i in range(start, end + 1) if table[i]) |
| 240 |
blocks.append((start, end, first_char, num_assigned, block)) |
| 241 |
planes = [ |
| 242 |
(0x0, 0xFFFD, "Basic Multilingual Plane"), |
| 243 |
(0x10000, 0x1FFFD, "Supplementary Multilingual Plane"), |
| 244 |
(0x20000, 0x2FFFD, "Supplementary Ideographic Plane"), |
| 245 |
(0x30000, 0x3FFFD, "Tertiary Ideographic Plane"), |
| 246 |
(0xE0000, 0xEFFFD, "Supplementary Special-purpose Plane"), |
| 247 |
(0xF0000, 0xFFFFD, "Plane 15 (Supplementary Private Use Area-A)"), |
| 248 |
(0x100000, 0x10FFFD, "Plane 16 (Supplementary Private Use Area-B)"), |
| 249 |
] |
| 250 |
planes = [ |
| 251 |
(s, e, s, sum(1 for i in range(s, e + 1) if table[i]), n) |
| 252 |
for s, e, n in planes |
| 253 |
] |
| 254 |
for i in range(0x40000, 0xE0000, 0x10000): |
| 255 |
if all(x is None for x in table[i : i + 0x10000]): |
| 256 |
planes.append( |
| 257 |
(i, i + 0x10000 - 3, i, 0, f"<Unassigned Plane {i//0x10000}>") |
| 258 |
) |
| 259 |
else: |
| 260 |
raise ValueError( |
| 261 |
f"Assigned codepoints in plane {i//0x10000}, give this a name" |
| 262 |
) |
| 263 |
|
| 264 |
max_name, max_annot = 0, 0 |
| 265 |
special_names = {} |
| 266 |
names = {} |
| 267 |
for l in NamesList(NAMES_LIST, version): |
| 268 |
if l[0][0].isalnum(): |
| 269 |
char = int(l[0][0], 16) |
| 270 |
name = [x[1] for x in l] |
| 271 |
assert (len(x) == 2 for x in l) |
| 272 |
m = re.match( |
| 273 |
r"^(CJK COMPATIBILITY IDEOGRAPH|KHITAN SMALL SCRIPT CHARACTER|NUSHU CHARACTER)-[A-F0-9]+$", |
| 274 |
name[0], |
| 275 |
) |
| 276 |
if name[0].startswith("<") or m: |
| 277 |
name[0] = "" |
| 278 |
if m: |
| 279 |
specials = special_names.setdefault(m.group(1), set()) |
| 280 |
specials.add(char) |
| 281 |
if any(l for l in name): |
| 282 |
nlines = len(name) |
| 283 |
name = "\n".join(name).encode("utf-8") + b"\0" |
| 284 |
name_split = name.split(b"\n", 1) |
| 285 |
max_name = max(max_name, len(name_split[0]) + 1) |
| 286 |
if len(name_split) > 1: |
| 287 |
|
| 288 |
max_annot = max(max_annot, len(name_split[1]) + nlines * 3 + 1) |
| 289 |
names[char] = name |
| 290 |
|
| 291 |
for k, v in special_names.items(): |
| 292 |
ranges = [] |
| 293 |
min_range, prev_char = None, None |
| 294 |
for char in sorted(v): |
| 295 |
if min_range is None: |
| 296 |
min_range = char |
| 297 |
elif char != prev_char + 1: |
| 298 |
ranges.append((min_range, prev_char)) |
| 299 |
min_range = char |
| 300 |
prev_char = char |
| 301 |
if min_range is not None: |
| 302 |
ranges.append((min_range, prev_char)) |
| 303 |
special_name_ranges[k] = ranges |
| 304 |
|
| 305 |
|
| 306 |
self.filename = UNICODE_DATA % "" |
| 307 |
self.table = table |
| 308 |
self.chars = list(range(UNICODE_MAX)) |
| 309 |
self.names = names |
| 310 |
self.special_name_ranges = special_name_ranges |
| 311 |
self.max_name = ((max_name + 31) // 32) * 32 |
| 312 |
self.max_annot = ((max_annot + 31) // 32) * 32 |
| 313 |
self.blocks = sorted(blocks, key=lambda x: x[0]) |
| 314 |
self.planes = sorted(planes, key=lambda x: x[0]) |
| 315 |
|
| 316 |
for char, (p, *_) in UcdFile(DERIVED_CORE_PROPERTIES, version).expanded(): |
| 317 |
if table[char]: |
| 318 |
|
| 319 |
|
| 320 |
table[char].binary_properties.add(p) |
| 321 |
|
| 322 |
for char, (p,) in UcdFile(PROP_LIST, version).expanded(): |
| 323 |
if table[char]: |
| 324 |
table[char].binary_properties.add(p) |
| 325 |
|
| 326 |
for data in UcdFile(BIDI_MIRRORING, version): |
| 327 |
c = int(data[0], 16) |
| 328 |
table[c].bidi_mirroring = data[1] |
| 329 |
|
| 330 |
|
| 331 |
|
| 332 |
|
| 333 |
|
| 334 |
|
| 335 |
def makeutype(unicode, trace): |
| 336 |
FILE = "utype.c" |
| 337 |
|
| 338 |
print("--- Preparing", FILE, "...") |
| 339 |
|
| 340 |
|
| 341 |
case_dummy = (0, 0, 0, 0) |
| 342 |
case_table = [case_dummy] |
| 343 |
case_cache = {case_dummy: 0} |
| 344 |
case_index = [0] * len(unicode.chars) |
| 345 |
|
| 346 |
type_dummy = (0, 0) |
| 347 |
type_table = [type_dummy] |
| 348 |
type_cache = {type_dummy: 0} |
| 349 |
type_index = [0] * len(unicode.chars) |
| 350 |
|
| 351 |
switches = {} |
| 352 |
|
| 353 |
for char in unicode.chars: |
| 354 |
record = unicode.table[char] |
| 355 |
if record: |
| 356 |
|
| 357 |
category = record.general_category |
| 358 |
bidirectional = record.bidi_class |
| 359 |
properties = record.binary_properties |
| 360 |
flags = UcdTypeFlags.FF_UNICODE_ISUNICODEPOINTASSIGNED |
| 361 |
if category in ["Mn", "Mc", "Me"]: |
| 362 |
flags |= UcdTypeFlags.FF_UNICODE_ISCOMBINING |
| 363 |
if category == "Nd": |
| 364 |
flags |= UcdTypeFlags.FF_UNICODE_ISDIGIT |
| 365 |
if category == "Zs" or bidirectional in ("WS", "B", "S"): |
| 366 |
switches.setdefault("space", []).append(char) |
| 367 |
if category == "Lt": |
| 368 |
switches.setdefault("title", []).append(char) |
| 369 |
if category in ["Lm", "Lt", "Lu", "Ll", "Lo"]: |
| 370 |
flags |= UcdTypeFlags.FF_UNICODE_ISALPHA |
| 371 |
if "Lowercase" in properties: |
| 372 |
flags |= UcdTypeFlags.FF_UNICODE_ISLOWER |
| 373 |
if "Uppercase" in properties: |
| 374 |
flags |= UcdTypeFlags.FF_UNICODE_ISUPPER |
| 375 |
if "Ideographic" in properties: |
| 376 |
flags |= UcdTypeFlags.FF_UNICODE_ISIDEOGRAPHIC |
| 377 |
if "ASCII_Hex_Digit" in properties: |
| 378 |
switches.setdefault("hexdigit", []).append(char) |
| 379 |
if "Default_Ignorable_Code_Point" in properties: |
| 380 |
flags |= UcdTypeFlags.FF_UNICODE_ISZEROWIDTH |
| 381 |
|
| 382 |
|
| 383 |
if bidirectional in ("L", "LRE", "LRO"): |
| 384 |
flags |= UcdTypeFlags.FF_UNICODE_ISLEFTTORIGHT |
| 385 |
elif bidirectional in ("R", "AL", "RLE", "RLO"): |
| 386 |
flags |= UcdTypeFlags.FF_UNICODE_ISRIGHTTOLEFT |
| 387 |
elif bidirectional == "EN": |
| 388 |
flags |= UcdTypeFlags.FF_UNICODE_ISEURONUMERIC |
| 389 |
elif bidirectional == "AN": |
| 390 |
flags |= UcdTypeFlags.FF_UNICODE_ISARABNUMERIC |
| 391 |
elif bidirectional == "ES": |
| 392 |
switches.setdefault("euronumsep", []).append(char) |
| 393 |
elif bidirectional == "CS": |
| 394 |
switches.setdefault("commonsep", []).append(char) |
| 395 |
elif bidirectional == "ET": |
| 396 |
flags |= UcdTypeFlags.FF_UNICODE_ISEURONUMTERM |
| 397 |
|
| 398 |
|
| 399 |
if any(x in record.name for x in ("LIGATURE", "VULGAR", "FRACTION")): |
| 400 |
if char != 0x2044: |
| 401 |
flags |= UcdTypeFlags.FF_UNICODE_ISLIGVULGFRAC |
| 402 |
|
| 403 |
if record.decomposition_type: |
| 404 |
flags |= UcdTypeFlags.FF_UNICODE_ISDECOMPOSITIONNORMATIVE |
| 405 |
|
| 406 |
if record.decomposition_type.startswith("<circle>"): |
| 407 |
flags |= UcdTypeFlags.FF_UNICODE_ISDECOMPCIRCLE |
| 408 |
elif record.decomposition_type.startswith("<initial>"): |
| 409 |
flags |= UcdTypeFlags.FF_UNICODE_ISARABINITIAL |
| 410 |
elif record.decomposition_type.startswith("<medial>"): |
| 411 |
flags |= UcdTypeFlags.FF_UNICODE_ISARABMEDIAL |
| 412 |
elif record.decomposition_type.startswith("<final>"): |
| 413 |
flags |= UcdTypeFlags.FF_UNICODE_ISARABFINAL |
| 414 |
elif record.decomposition_type.startswith("<isolated>"): |
| 415 |
flags |= UcdTypeFlags.FF_UNICODE_ISARABISOLATED |
| 416 |
|
| 417 |
if record.simple_uppercase_mapping: |
| 418 |
upper = int(record.simple_uppercase_mapping, 16) |
| 419 |
else: |
| 420 |
upper = char |
| 421 |
if record.simple_lowercase_mapping: |
| 422 |
lower = int(record.simple_lowercase_mapping, 16) |
| 423 |
else: |
| 424 |
lower = char |
| 425 |
if record.simple_titlecase_mapping: |
| 426 |
title = int(record.simple_titlecase_mapping, 16) |
| 427 |
else: |
| 428 |
title = upper |
| 429 |
if record.bidi_mirroring: |
| 430 |
mirror = int(record.bidi_mirroring, 16) |
| 431 |
else: |
| 432 |
mirror = char |
| 433 |
|
| 434 |
|
| 435 |
if upper == lower == title == mirror: |
| 436 |
upper = lower = title = mirror = 0 |
| 437 |
else: |
| 438 |
upper = upper - char |
| 439 |
lower = lower - char |
| 440 |
title = title - char |
| 441 |
mirror = mirror - char |
| 442 |
assert ( |
| 443 |
abs(upper) <= 2147483647 |
| 444 |
and abs(lower) <= 2147483647 |
| 445 |
and abs(title) <= 2147483647 |
| 446 |
and abs(mirror) <= 2147483647 |
| 447 |
) |
| 448 |
|
| 449 |
|
| 450 |
ccc = int(record.canonical_combining_class) |
| 451 |
pose = get_pose(char, ccc, with_ccc=True) |
| 452 |
|
| 453 |
|
| 454 |
item = (upper, lower, title, mirror) |
| 455 |
i = case_cache.get(item) |
| 456 |
if i is None: |
| 457 |
case_cache[item] = i = len(case_table) |
| 458 |
case_table.append(item) |
| 459 |
case_index[char] = i |
| 460 |
|
| 461 |
|
| 462 |
item = (flags, pose) |
| 463 |
i = type_cache.get(item) |
| 464 |
if i is None: |
| 465 |
type_cache[item] = i = len(type_table) |
| 466 |
type_table.append(item) |
| 467 |
type_index[char] = i |
| 468 |
|
| 469 |
|
| 470 |
|
| 471 |
print(len(case_table), "unique case mapping entries") |
| 472 |
print(len(type_table), "unique character type entries") |
| 473 |
for k, v in switches.items(): |
| 474 |
print(len(v), k, "code points") |
| 475 |
|
| 476 |
print("--- Writing", FILE, "...") |
| 477 |
|
| 478 |
with open(FILE, "w") as fp: |
| 479 |
fprint = partial(print, file=fp) |
| 480 |
alignment = max(len(flag.name) for flag in UcdTypeFlags) |
| 481 |
|
| 482 |
License(extra="Contributions: Werner Lemberg, Khaled Hosny, Joe Da Silva").dump( |
| 483 |
fp |
| 484 |
) |
| 485 |
fprint("#include <assert.h>") |
| 486 |
fprint("#include <utype.h>") |
| 487 |
fprint() |
| 488 |
for flag in UcdTypeFlags: |
| 489 |
fprint("#define %-*s 0x%x" % (alignment, flag.name, flag.value)) |
| 490 |
fprint() |
| 491 |
fprint("struct utypecasing {") |
| 492 |
fprint(" /* deltas from the current character */") |
| 493 |
fprint(" int32_t upper, lower, title, mirror;") |
| 494 |
fprint("};") |
| 495 |
fprint() |
| 496 |
fprint("struct utypeflags {") |
| 497 |
fprint(" uint32_t flags; /* One or more of the above flags */") |
| 498 |
fprint(" uint32_t pose; /* Positioning info */") |
| 499 |
fprint("};") |
| 500 |
fprint() |
| 501 |
fprint("/* a list of unique simple case mappings */") |
| 502 |
fprint("static const struct utypecasing casing_data[] = {") |
| 503 |
for item in case_table: |
| 504 |
fprint(" {%d, %d, %d, %d}," % item) |
| 505 |
fprint("};") |
| 506 |
fprint() |
| 507 |
fprint("/* a list of unique type flags */") |
| 508 |
fprint("static const struct utypeflags type_data[] = {") |
| 509 |
for item in type_table: |
| 510 |
fprint(" {%d, %d}," % item) |
| 511 |
fprint("};") |
| 512 |
fprint() |
| 513 |
|
| 514 |
case_ind = Index("casing", "struct utypecasing", case_index) |
| 515 |
type_ind = Index("type", "struct utypeflags", type_index) |
| 516 |
|
| 517 |
case_ind.dump(fp, trace, accessor=False) |
| 518 |
type_ind.dump(fp, trace, accessor=False) |
| 519 |
|
| 520 |
case_ind.dump(fp, trace, index=False) |
| 521 |
type_ind.dump(fp, trace, index=False) |
| 522 |
|
| 523 |
for flag in UcdTypeFlags: |
| 524 |
fprint("int %s(unichar_t ch) {" % flag.name.lower()) |
| 525 |
fprint(" return get_type(ch)->flags & %s;" % (flag.name,)) |
| 526 |
fprint("}") |
| 527 |
fprint() |
| 528 |
|
| 529 |
for name, flag in [ |
| 530 |
("ff_unicode_isideoalpha", "FF_UNICODE_ISALPHA | FF_UNICODE_ISIDEOGRAPHIC"), |
| 531 |
("ff_unicode_isalnum", "FF_UNICODE_ISALPHA | FF_UNICODE_ISDIGIT"), |
| 532 |
]: |
| 533 |
fprint("int %s(unichar_t ch) {" % name) |
| 534 |
fprint(" return get_type(ch)->flags & (%s);" % flag) |
| 535 |
fprint("}") |
| 536 |
fprint() |
| 537 |
|
| 538 |
for k in sorted(switches.keys()): |
| 539 |
Switch("ff_unicode_is" + k, switches[k]).dump(fp) |
| 540 |
|
| 541 |
fprint("int ff_unicode_pose(unichar_t ch) {") |
| 542 |
fprint(" return get_type(ch)->pose & ~0xff;") |
| 543 |
fprint("}") |
| 544 |
fprint() |
| 545 |
fprint("int ff_unicode_combiningclass(unichar_t ch) {") |
| 546 |
fprint(" return get_type(ch)->pose & 0xff;") |
| 547 |
fprint("}") |
| 548 |
fprint() |
| 549 |
|
| 550 |
conv_types = ("lower", "upper", "title", "mirror") |
| 551 |
for n in conv_types: |
| 552 |
fprint("unichar_t ff_unicode_to%s(unichar_t ch) {" % n) |
| 553 |
fprint(" const struct utypecasing* rec = get_casing(ch);") |
| 554 |
if n == "mirror": |
| 555 |
fprint(" if (rec->mirror == 0) {") |
| 556 |
fprint(" return 0;") |
| 557 |
fprint(" }") |
| 558 |
fprint(" return (unichar_t)(((int32_t)ch) + rec->%s);" % n) |
| 559 |
fprint("}") |
| 560 |
fprint() |
| 561 |
|
| 562 |
return ( |
| 563 |
[("int", x.name.lower()) for x in UcdTypeFlags] |
| 564 |
+ [ |
| 565 |
("int", "ff_unicode_is" + k) |
| 566 |
for k in chain(["ideoalpha", "alnum"], switches) |
| 567 |
] |
| 568 |
+ [("int", "ff_unicode_pose"), ("int", "ff_unicode_combiningclass")] |
| 569 |
+ [("unichar_t", "ff_unicode_to" + n) for n in conv_types] |
| 570 |
) |
| 571 |
|
| 572 |
|
| 573 |
def makeunialt(unicode, trace): |
| 574 |
FILE = "unialt.c" |
| 575 |
|
| 576 |
print("--- Preparing", FILE, "...") |
| 577 |
|
| 578 |
unialt_data = [0] |
| 579 |
unialt_index = [0] * len(unicode.chars) |
| 580 |
unialt_chars = set() |
| 581 |
|
| 582 |
for char in unicode.chars: |
| 583 |
record = unicode.table[char] |
| 584 |
if not record: |
| 585 |
continue |
| 586 |
elif not record.decomposition_type and char not in VISUAL_ALTS: |
| 587 |
continue |
| 588 |
|
| 589 |
|
| 590 |
if record.decomposition_type: |
| 591 |
decomp = record.decomposition_type.split() |
| 592 |
if len(decomp) > 19: |
| 593 |
raise Exception( |
| 594 |
"character %x has a decomposition too large for nfd_nfkd" % char |
| 595 |
) |
| 596 |
if decomp[0].startswith("<"): |
| 597 |
decomp.pop(0) |
| 598 |
decomp = [int(s, 16) for s in decomp] |
| 599 |
unialt_chars.add(char) |
| 600 |
else: |
| 601 |
decomp = VISUAL_ALTS[char] |
| 602 |
assert len(decomp) <= 19 |
| 603 |
|
| 604 |
|
| 605 |
decomp = decomp + [0] |
| 606 |
unialt_index[char] = len(unialt_data) |
| 607 |
unialt_data.extend(decomp) |
| 608 |
|
| 609 |
|
| 610 |
print( |
| 611 |
"Ignored visual alts:", |
| 612 |
", ".join("U+%04x" % x for x in VISUAL_ALTS.keys() & unialt_chars), |
| 613 |
) |
| 614 |
print(len(unialt_data), "unique decomposition entries") |
| 615 |
|
| 616 |
print("--- Writing", FILE, "...") |
| 617 |
|
| 618 |
with open(FILE, "w") as fp: |
| 619 |
fprint = partial(print, file=fp) |
| 620 |
|
| 621 |
License().dump(fp) |
| 622 |
|
| 623 |
fprint("#include <assert.h>") |
| 624 |
fprint("#include <utype.h>") |
| 625 |
fprint() |
| 626 |
|
| 627 |
fprint("/* decomposition + visual alternates data */") |
| 628 |
Array("unialt_data", unialt_data).dump(fp, trace) |
| 629 |
|
| 630 |
Index("unialt", "unichar_t", unialt_index).dump(fp, trace) |
| 631 |
|
| 632 |
fprint("int ff_unicode_hasunialt(unichar_t ch) {") |
| 633 |
fprint(" return *get_unialt(ch) != 0;") |
| 634 |
fprint("}") |
| 635 |
fprint() |
| 636 |
|
| 637 |
fprint("const unichar_t* ff_unicode_unialt(unichar_t ch) {") |
| 638 |
fprint(" const unichar_t* ptr = get_unialt(ch);") |
| 639 |
fprint(" if (!*ptr) {") |
| 640 |
fprint(" return NULL;") |
| 641 |
fprint(" }") |
| 642 |
fprint(" return ptr;") |
| 643 |
fprint("}") |
| 644 |
fprint() |
| 645 |
|
| 646 |
return [ |
| 647 |
("int", "ff_unicode_hasunialt"), |
| 648 |
("const unichar_t*", "ff_unicode_unialt"), |
| 649 |
] |
| 650 |
|
| 651 |
|
| 652 |
def makearabicforms(unicode, trace): |
| 653 |
FILE = "ArabicForms.c" |
| 654 |
|
| 655 |
print("--- Preparing", FILE, "...") |
| 656 |
|
| 657 |
|
| 658 |
table = [] |
| 659 |
lookup = {x.name: i for i, x in enumerate(unicode.table) if x and x.name} |
| 660 |
|
| 661 |
for char in range(0x600, 0x700): |
| 662 |
record = unicode.table[char] |
| 663 |
initial, medial, final, isolated, isletter, joindual = 0, 0, 0, 0, 0, 0 |
| 664 |
required_lig_with_alef = char == 0x644 |
| 665 |
|
| 666 |
if record is not None: |
| 667 |
if not record.name.startswith("ARABIC LETTER "): |
| 668 |
|
| 669 |
initial = medial = final = isolated = char |
| 670 |
else: |
| 671 |
isletter = 1 |
| 672 |
initial = lookup.get(record.name + " INITIAL FORM", char) |
| 673 |
medial = lookup.get(record.name + " MEDIAL FORM", char) |
| 674 |
final = lookup.get(record.name + " FINAL FORM", char) |
| 675 |
isolated = lookup.get(record.name + " ISOLATED FORM", char) |
| 676 |
joindual = int(initial != char and medial != char) |
| 677 |
table.append( |
| 678 |
( |
| 679 |
initial, |
| 680 |
medial, |
| 681 |
final, |
| 682 |
isolated, |
| 683 |
isletter, |
| 684 |
joindual, |
| 685 |
required_lig_with_alef, |
| 686 |
) |
| 687 |
) |
| 688 |
|
| 689 |
print("--- Writing", FILE, "...") |
| 690 |
|
| 691 |
with open(FILE, "w") as fp: |
| 692 |
fprint = partial(print, file=fp) |
| 693 |
License(extra="Contributions: Khaled Hosny, Joe Da Silva").dump(fp) |
| 694 |
fprint("#include <utype.h>") |
| 695 |
fprint() |
| 696 |
fprint("static struct arabicforms arabic_forms[] = {") |
| 697 |
fprint( |
| 698 |
" /* initial, medial, final, isolated, isletter, joindual, required_lig_with_alef */" |
| 699 |
) |
| 700 |
for i, form in enumerate(table): |
| 701 |
fp.write(" { 0x%04x, 0x%04x, 0x%04x, 0x%04x, %d, %d, %d }," % form) |
| 702 |
fprint(f" /* 0x{0x600+i:04x} */" if (i % 32) == 0 else "") |
| 703 |
fprint("};") |
| 704 |
fprint() |
| 705 |
|
| 706 |
fprint("const struct arabicforms* arabicform(unichar_t ch) {") |
| 707 |
fprint(" if (ch >= 0x600 && ch <= 0x6ff) {") |
| 708 |
fprint(" return &arabic_forms[ch - 0x600];") |
| 709 |
fprint(" }") |
| 710 |
fprint(" return NULL;") |
| 711 |
fprint("}") |
| 712 |
|
| 713 |
|
| 714 |
def makeuninames(unicode, trace): |
| 715 |
FILE = "uninames_data.h" |
| 716 |
|
| 717 |
print("--- Preparing", FILE, "...") |
| 718 |
|
| 719 |
|
| 720 |
|
| 721 |
|
| 722 |
|
| 723 |
|
| 724 |
regexes = [ |
| 725 |
(100, re.compile(rb"[\x20-\x7F]{3,}[ -]")), |
| 726 |
(100, re.compile(rb"(?:[\x21-\x7F]+[ -]+){5}")), |
| 727 |
(150, re.compile(rb"(?:[\x21-\x7F]+[ -]+){4}")), |
| 728 |
(250, re.compile(rb"(?:[\x21-\x7F]+[ -]+){3}")), |
| 729 |
(750, re.compile(rb"(?:[\x21-\x7F]+[ -]+){2}")), |
| 730 |
(3400, re.compile(rb"(?:[\x21-\x7F]+[ -]+){1}")), |
| 731 |
(3440, re.compile(rb"\b(?:[a-z]{3,}|[\x21-\x60\x7B-\x7F]{3,})\b")), |
| 732 |
] |
| 733 |
|
| 734 |
|
| 735 |
|
| 736 |
|
| 737 |
total_count = sum([count for count, _ in regexes]) |
| 738 |
if total_count >= 2 ** 13: |
| 739 |
print("Warning: lexicon overflow possible", total_count) |
| 740 |
|
| 741 |
|
| 742 |
|
| 743 |
annot_re = re.compile(rb"\n(.) ") |
| 744 |
|
| 745 |
|
| 746 |
|
| 747 |
|
| 748 |
def benefit(w: bytes, f: int) -> int: |
| 749 |
return (len(w) - 2) * f - len(w) |
| 750 |
|
| 751 |
|
| 752 |
|
| 753 |
|
| 754 |
|
| 755 |
intermediate = {x: annot_re.sub(rb"\n", y) for x, y in unicode.names.items()} |
| 756 |
names = {**unicode.names} |
| 757 |
replacements = set() |
| 758 |
wordlist = {} |
| 759 |
for count, regex in regexes: |
| 760 |
replacements.update( |
| 761 |
x[0] |
| 762 |
for x in Counter( |
| 763 |
part for name in intermediate.values() for part in regex.findall(name) |
| 764 |
).most_common(count) |
| 765 |
if benefit(*x) > 0 |
| 766 |
) |
| 767 |
|
| 768 |
for char, name in intermediate.items(): |
| 769 |
wn = names[char] |
| 770 |
for part in regex.findall(name): |
| 771 |
if part in replacements: |
| 772 |
i = wordlist.get(part) |
| 773 |
if i is None: |
| 774 |
i = len(wordlist) |
| 775 |
assert i < 2 ** 13, "lexicon overflow; adjust regexes" |
| 776 |
i = bytes((0x80 | ((i >> 7) & 0x3F), 0x80 | (i & 0x7F))) |
| 777 |
wordlist[part] = i |
| 778 |
wn = wn.replace(part, i) |
| 779 |
name = name.replace(part, b"") |
| 780 |
intermediate[char] = name |
| 781 |
names[char] = wn |
| 782 |
|
| 783 |
lexicon = b"" |
| 784 |
lexicon_offset = [] |
| 785 |
lexicon_shifts = [] |
| 786 |
lexicon_shift = 12 |
| 787 |
|
| 788 |
current_offset = 0 |
| 789 |
|
| 790 |
for w in wordlist.keys(): |
| 791 |
|
| 792 |
assert w.isascii() |
| 793 |
ww = w[:-1] + bytes([int(w[-1]) | 0x80]) |
| 794 |
offset = len(lexicon) |
| 795 |
offset_index = len(lexicon_offset) >> lexicon_shift |
| 796 |
if offset_index + 1 > len(lexicon_shifts): |
| 797 |
current_offset = offset |
| 798 |
while len(lexicon_shifts) < offset_index: |
| 799 |
lexicon_shifts.append(lexicon_shifts[-1]) |
| 800 |
lexicon_shifts.append(current_offset) |
| 801 |
offset -= current_offset |
| 802 |
lexicon_offset.append(offset) |
| 803 |
lexicon += ww |
| 804 |
|
| 805 |
lexicon = list(lexicon) |
| 806 |
assert getsize(lexicon) == 1 |
| 807 |
assert getsize(lexicon_offset) < 4 |
| 808 |
assert getsize(lexicon_shifts) < 4 |
| 809 |
|
| 810 |
phrasebook = [0] |
| 811 |
phrasebook_offset = [0] * len(unicode.chars) |
| 812 |
phrasebook_shifts = [] |
| 813 |
phrasebook_shift = 11 |
| 814 |
phrasebook_shift_cap = 63 |
| 815 |
current_offset = 0 |
| 816 |
|
| 817 |
for char in unicode.chars: |
| 818 |
name = names.get(char) |
| 819 |
if name is not None: |
| 820 |
name = annot_re.sub(rb"\n\1", name) |
| 821 |
offset = len(phrasebook) |
| 822 |
offset_index = min(char >> phrasebook_shift, phrasebook_shift_cap) |
| 823 |
if offset_index + 1 > len(phrasebook_shifts): |
| 824 |
current_offset = offset - 1 |
| 825 |
while len(phrasebook_shifts) < offset_index: |
| 826 |
phrasebook_shifts.append(phrasebook_shifts[-1]) |
| 827 |
phrasebook_shifts.append(current_offset) |
| 828 |
offset -= current_offset |
| 829 |
assert offset > 0 |
| 830 |
phrasebook_offset[char] = offset |
| 831 |
phrasebook += list(name) |
| 832 |
|
| 833 |
assert getsize(phrasebook) == 1 |
| 834 |
assert getsize(phrasebook_offset) < 4 |
| 835 |
|
| 836 |
|
| 837 |
|
| 838 |
|
| 839 |
|
| 840 |
|
| 841 |
print("Number of lexicon entries:", len(lexicon_offset)) |
| 842 |
print("--- Writing", FILE, "...") |
| 843 |
|
| 844 |
with open(FILE, "w") as fp: |
| 845 |
fprint = partial(print, file=fp) |
| 846 |
|
| 847 |
License(copyright="2021 by Jeremy Tan").dump(fp) |
| 848 |
fprint("#ifndef FONTFORGE_UNINAMES_DATA_H") |
| 849 |
fprint("#define FONTFORGE_UNINAMES_DATA_H") |
| 850 |
fprint() |
| 851 |
|
| 852 |
fprint("#include <intl.h>") |
| 853 |
fprint("#include <ustring.h>") |
| 854 |
fprint("#include <utype.h>") |
| 855 |
fprint() |
| 856 |
|
| 857 |
fprint("/* Basic definitions */") |
| 858 |
fprint("#define MAX_NAME_LENGTH", unicode.max_name) |
| 859 |
fprint("#define MAX_ANNOTATION_LENGTH", unicode.max_annot) |
| 860 |
fprint() |
| 861 |
|
| 862 |
fprint("/* unicode ranges data */") |
| 863 |
fprint("static const struct unicode_range unicode_blocks[] = {") |
| 864 |
for block in unicode.blocks: |
| 865 |
fprint(' {0x%04X, 0x%04X, 0x%04X, %d, N_("%s")},' % block) |
| 866 |
fprint("};") |
| 867 |
fprint("static const struct unicode_range unicode_planes[] = {") |
| 868 |
for plane in unicode.planes: |
| 869 |
fprint(' {0x%04X, 0x%04X, 0x%04X, %d, N_("%s")},' % plane) |
| 870 |
fprint("};") |
| 871 |
fprint() |
| 872 |
|
| 873 |
fprint("/* lexicon data */") |
| 874 |
fprint("#define LEXICON_SHIFT", lexicon_shift) |
| 875 |
Array("lexicon_data", lexicon).dump(fp, trace) |
| 876 |
Array("lexicon_offset", lexicon_offset).dump(fp, trace) |
| 877 |
Array("lexicon_shift", lexicon_shifts).dump(fp, trace) |
| 878 |
|
| 879 |
index1, index2, shift = splitbins(phrasebook_offset, 1) |
| 880 |
|
| 881 |
fprint("/* phrasebook data */") |
| 882 |
fprint("#define PHRASEBOOK_SHIFT1", shift) |
| 883 |
fprint("#define PHRASEBOOK_SHIFT2", phrasebook_shift) |
| 884 |
fprint("#define PHRASEBOOK_SHIFT2_CAP", phrasebook_shift_cap) |
| 885 |
Array("phrasebook_data", phrasebook).dump(fp, trace) |
| 886 |
Array("phrasebook_index1", index1).dump(fp, trace) |
| 887 |
Array("phrasebook_index2", index2).dump(fp, trace) |
| 888 |
Array("phrasebook_shift", phrasebook_shifts).dump(fp, trace) |
| 889 |
|
| 890 |
|
| 891 |
jamo_l = ["G", "GG", "N", "D", "DD", "R", "M", "B", "BB", "S", "SS", |
| 892 |
"", "J", "JJ", "C", "K", "T", "P", "H"] |
| 893 |
jamo_v = ["A", "AE", "YA", "YAE", "EO", "E", "YEO", "YE", "O", "WA", |
| 894 |
"WAE", "OE", "YO", "U", "WEO", "WE", "WI","YU", "EU", "YI", "I"] |
| 895 |
jamo_t = ["", "G", "GG", "GS", "N", "NJ", "NH", "D", "L", "LG", "LM", |
| 896 |
"LB", "LS", "LT", "LP", "LH", "M","B", "BS", "S", "SS", "NG", |
| 897 |
"J", "C", "K", "T", "P", "H"] |
| 898 |
|
| 899 |
|
| 900 |
fprint("/* Unicode chapter 3.12 on Hangul Character Name Generation */") |
| 901 |
fprint("#define JAMO_V_COUNT", len(jamo_v)) |
| 902 |
fprint("#define JAMO_T_COUNT", len(jamo_t)) |
| 903 |
fprint("#define JAMO_N_COUNT (JAMO_V_COUNT * JAMO_T_COUNT)") |
| 904 |
Array("jamo_l", jamo_l).dump(fp, trace) |
| 905 |
Array("jamo_v", jamo_v).dump(fp, trace) |
| 906 |
Array("jamo_t", jamo_t).dump(fp, trace) |
| 907 |
|
| 908 |
fprint("static char* get_derived_name(unichar_t ch) {") |
| 909 |
|
| 910 |
|
| 911 |
hangul_range = unicode.special_name_ranges["HANGUL SYLLABLE"] |
| 912 |
assert hangul_range == [(0xAC00, 0xD7A3)] |
| 913 |
fprint(" if (ch >= 0xAC00 && ch <= 0xD7A3) {") |
| 914 |
fprint(" ch -= 0xAC00;") |
| 915 |
fprint(" int l = ch / JAMO_N_COUNT;") |
| 916 |
fprint(" int v = (ch % JAMO_N_COUNT) / JAMO_T_COUNT;") |
| 917 |
fprint(" int t = ch % JAMO_T_COUNT;") |
| 918 |
fprint(' return smprintf("HANGUL SYLLABLE %s%s%s",') |
| 919 |
fprint(" jamo_l[l], jamo_v[v], jamo_t[t]);") |
| 920 |
fprint(" }") |
| 921 |
|
| 922 |
|
| 923 |
items = sorted(unicode.special_name_ranges.items(), key=lambda x: x[1][0]) |
| 924 |
for name, ranges in items: |
| 925 |
if name == "HANGUL SYLLABLE": |
| 926 |
continue |
| 927 |
cond = " if (" |
| 928 |
for i, (start, end) in enumerate(ranges): |
| 929 |
if i > 0: |
| 930 |
cond += " || " |
| 931 |
range_cond = "ch >= 0x%X && ch <= 0x%X" % (start, end) |
| 932 |
if len(ranges) > 1: |
| 933 |
range_cond = "(" + range_cond + ")" |
| 934 |
if len(cond) + len(range_cond) > 78: |
| 935 |
fprint(cond.rstrip()) |
| 936 |
cond = " " + range_cond |
| 937 |
else: |
| 938 |
cond += range_cond |
| 939 |
fprint(cond + ") {") |
| 940 |
fprint(' return smprintf("%s-%%X", ch);' % name) |
| 941 |
fprint(" }") |
| 942 |
fprint(" return NULL;") |
| 943 |
fprint("}") |
| 944 |
fprint() |
| 945 |
|
| 946 |
fprint("#endif /* FONTFORGE_UNINAMES_DATA_H */") |
| 947 |
|
| 948 |
return ( |
| 949 |
phrasebook, |
| 950 |
phrasebook_offset, |
| 951 |
phrasebook_shifts, |
| 952 |
lexicon, |
| 953 |
lexicon_offset, |
| 954 |
lexicon_shifts, |
| 955 |
lexicon_shift, |
| 956 |
) |
| 957 |
|
| 958 |
|
| 959 |
def makeutypeheader(utype_funcs): |
| 960 |
FILE = "utype.h" |
| 961 |
utype_funcs = [(t, n, n.replace("ff_unicode_", "")) for t, n in utype_funcs] |
| 962 |
|
| 963 |
print("--- Writing", FILE, "...") |
| 964 |
|
| 965 |
with open(os.path.join(BASE, "..", "inc", FILE), "w") as fp: |
| 966 |
fprint = partial(print, file=fp) |
| 967 |
|
| 968 |
License().dump(fp) |
| 969 |
fprint("#ifndef FONTFORGE_UNICODE_UTYPE2_H") |
| 970 |
fprint("#define FONTFORGE_UNICODE_UTYPE2_H") |
| 971 |
fprint() |
| 972 |
fprint( |
| 973 |
"#include <ctype.h> /* Include here so we can control it. If a system header includes it later bad things happen */" |
| 974 |
) |
| 975 |
fprint( |
| 976 |
'#include "basics.h" /* Include here so we can use pre-defined int types to correctly size constant data arrays. */' |
| 977 |
) |
| 978 |
fprint() |
| 979 |
|
| 980 |
fprint("/* Unicode basics */") |
| 981 |
fprint('#define UNICODE_VERSION "%s"' % UNIDATA_VERSION) |
| 982 |
fprint("#define UNICODE_MAX 0x%x" % UNICODE_MAX) |
| 983 |
fprint() |
| 984 |
|
| 985 |
alignment = len("FF_UNICODE_") + max(len(x.name) for x in Pose) |
| 986 |
fprint("/* Pose flags */") |
| 987 |
fprint("#define %-*s -1" % (alignment, "FF_UNICODE_NOPOSDATAGIVEN")) |
| 988 |
for c in Pose: |
| 989 |
fprint("#define %-*s 0x%x" % (alignment, "FF_UNICODE_" + c.name, c)) |
| 990 |
fprint() |
| 991 |
|
| 992 |
for rettype, fn, _ in utype_funcs: |
| 993 |
fprint("extern %s %s(unichar_t ch);" % (rettype, fn)) |
| 994 |
fprint() |
| 995 |
|
| 996 |
for _, fn, realfn in utype_funcs: |
| 997 |
fprint("#undef %s" % realfn) |
| 998 |
fprint() |
| 999 |
|
| 1000 |
alignment = max(len(x) + 4 for _, _, x in utype_funcs) |
| 1001 |
for _, fn, realfn in utype_funcs: |
| 1002 |
fprint("#define %-*s %s((ch))" % (alignment, realfn + "(ch)", fn)) |
| 1003 |
fprint() |
| 1004 |
|
| 1005 |
fprint("struct arabicforms {") |
| 1006 |
fprint(" unsigned short initial, medial, final, isolated;") |
| 1007 |
fprint(" unsigned int isletter: 1;") |
| 1008 |
fprint(" unsigned int joindual: 1;") |
| 1009 |
fprint(" unsigned int required_lig_with_alef: 1;") |
| 1010 |
fprint("};") |
| 1011 |
fprint() |
| 1012 |
fprint("extern const struct arabicforms* arabicform(unichar_t ch);") |
| 1013 |
fprint() |
| 1014 |
|
| 1015 |
fprint("struct unicode_range {") |
| 1016 |
fprint(" unichar_t start;") |
| 1017 |
fprint(" unichar_t end;") |
| 1018 |
fprint(" unichar_t first_char;") |
| 1019 |
fprint(" int num_assigned;") |
| 1020 |
fprint(" const char *name;") |
| 1021 |
fprint("};") |
| 1022 |
fprint() |
| 1023 |
|
| 1024 |
fprint("extern char* uniname_name(unichar_t ch);") |
| 1025 |
fprint("extern char* uniname_annotation(unichar_t ch, int prettify);") |
| 1026 |
fprint("extern char* uniname_formal_alias(unichar_t ch);") |
| 1027 |
fprint("extern const struct unicode_range* uniname_block(unichar_t ch);") |
| 1028 |
fprint("extern const struct unicode_range* uniname_plane(unichar_t ch);") |
| 1029 |
fprint("extern const struct unicode_range* uniname_blocks(int *sz);") |
| 1030 |
fprint("extern const struct unicode_range* uniname_planes(int *sz);") |
| 1031 |
fprint() |
| 1032 |
|
| 1033 |
fprint("#endif /* FONTFORGE_UNICODE_UTYPE2_H */") |
| 1034 |
|
| 1035 |
|
| 1036 |
|
| 1037 |
|
| 1038 |
|
| 1039 |
class Array: |
| 1040 |
def __init__(self, name, data): |
| 1041 |
self.name = name |
| 1042 |
self.data = data |
| 1043 |
self.is_str = isinstance(data[0], str) if data else False |
| 1044 |
|
| 1045 |
def dump(self, file, trace=0): |
| 1046 |
|
| 1047 |
file.write("static const ") |
| 1048 |
if self.is_str: |
| 1049 |
file.write("char *") |
| 1050 |
else: |
| 1051 |
size = getsize(self.data) |
| 1052 |
if trace: |
| 1053 |
print(self.name + ":", size * len(self.data), "bytes", file=sys.stderr) |
| 1054 |
if size == 1: |
| 1055 |
file.write("unsigned char") |
| 1056 |
elif size == 2: |
| 1057 |
file.write("unsigned short") |
| 1058 |
else: |
| 1059 |
file.write("unsigned int") |
| 1060 |
file.write(" " + self.name + "[] = {\n") |
| 1061 |
if self.data: |
| 1062 |
s = " " |
| 1063 |
for item in self.data: |
| 1064 |
i = str(int(item)) + ", " if not self.is_str else f'"{item}", ' |
| 1065 |
if len(s) + len(i) > 78: |
| 1066 |
file.write(s.rstrip() + "\n") |
| 1067 |
s = " " + i |
| 1068 |
else: |
| 1069 |
s = s + i |
| 1070 |
if s.strip(): |
| 1071 |
file.write(s.rstrip() + "\n") |
| 1072 |
file.write("};\n\n") |
| 1073 |
|
| 1074 |
|
| 1075 |
class Index: |
| 1076 |
def __init__(self, prefix, rectype, index): |
| 1077 |
self.prefix = prefix |
| 1078 |
self.rectype = rectype |
| 1079 |
self.index = index |
| 1080 |
|
| 1081 |
def dump(self, file, trace, index=True, accessor=True): |
| 1082 |
fprint = partial(print, file=file) |
| 1083 |
if index: |
| 1084 |
index1, index2, shift = splitbins(self.index, trace) |
| 1085 |
fprint("/* %s indexes */" % self.prefix) |
| 1086 |
fprint("#define %s_SHIFT" % self.prefix.upper(), shift) |
| 1087 |
Array(self.prefix + "_index1", index1).dump(file, trace) |
| 1088 |
Array(self.prefix + "_index2", index2).dump(file, trace) |
| 1089 |
if accessor: |
| 1090 |
prefix, rectype = self.prefix, self.rectype |
| 1091 |
func = f"get_{self.prefix.lower()}" |
| 1092 |
shift = self.prefix.upper() + "_SHIFT" |
| 1093 |
|
| 1094 |
|
| 1095 |
fprint(f"static const {rectype}* {func}(unichar_t ch) {{") |
| 1096 |
fprint(f" int index = 0;") |
| 1097 |
fprint(f" if (ch < UNICODE_MAX) {{") |
| 1098 |
fprint(f" index = {prefix}_index1[ch >> {shift}];") |
| 1099 |
fprint(f" index = {prefix}_index2[(index << {shift}) + (ch & ((1 << {shift}) - 1))];") |
| 1100 |
fprint(f" }}") |
| 1101 |
fprint(f" assert(index >= 0 && (size_t)index < sizeof({prefix}_data)/sizeof({prefix}_data[0]));") |
| 1102 |
fprint(f" return &{prefix}_data[index];") |
| 1103 |
fprint(f"}}") |
| 1104 |
fprint() |
| 1105 |
|
| 1106 |
|
| 1107 |
|
| 1108 |
class Switch: |
| 1109 |
def __init__(self, name, data): |
| 1110 |
self.name = name |
| 1111 |
self.data = data |
| 1112 |
|
| 1113 |
def dump(self, file): |
| 1114 |
fprint = partial(print, file=file) |
| 1115 |
fprint("int %s(unichar_t ch) {" % self.name) |
| 1116 |
fprint(" switch (ch) {") |
| 1117 |
|
| 1118 |
for codepoint in sorted(self.data): |
| 1119 |
fprint(" case 0x%04X:" % (codepoint,)) |
| 1120 |
fprint(" return 1;") |
| 1121 |
|
| 1122 |
fprint(" }") |
| 1123 |
fprint(" return 0;") |
| 1124 |
fprint("}") |
| 1125 |
fprint() |
| 1126 |
|
| 1127 |
|
| 1128 |
class License: |
| 1129 |
def __init__(self, copyright=None, extra=None): |
| 1130 |
self.copyright = copyright or "2000-2012 by George Williams" |
| 1131 |
self.extra = f"/* {extra} */\n" if extra else "" |
| 1132 |
|
| 1133 |
def dump(self, file): |
| 1134 |
file.write( |
| 1135 |
f"""/* This is a GENERATED file - from {SCRIPT} with Unicode {UNIDATA_VERSION} */ |
| 1136 |
|
| 1137 |
/* Copyright (C) {self.copyright} */ |
| 1138 |
{self.extra}/* |
| 1139 |
* Redistribution and use in source and binary forms, with or without |
| 1140 |
* modification, are permitted provided that the following conditions are met: |
| 1141 |
|
| 1142 |
* Redistributions of source code must retain the above copyright notice, this |
| 1143 |
* list of conditions and the following disclaimer. |
| 1144 |
|
| 1145 |
* Redistributions in binary form must reproduce the above copyright notice, |
| 1146 |
* this list of conditions and the following disclaimer in the documentation |
| 1147 |
* and/or other materials provided with the distribution. |
| 1148 |
|
| 1149 |
* The name of the author may not be used to endorse or promote products |
| 1150 |
* derived from this software without specific prior written permission. |
| 1151 |
|
| 1152 |
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED |
| 1153 |
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF |
| 1154 |
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO |
| 1155 |
* EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, |
| 1156 |
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, |
| 1157 |
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; |
| 1158 |
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, |
| 1159 |
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR |
| 1160 |
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF |
| 1161 |
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
| 1162 |
*/ |
| 1163 |
|
| 1164 |
""" |
| 1165 |
) |
| 1166 |
|
| 1167 |
|
| 1168 |
def getsize(data: List[int]) -> int: |
| 1169 |
|
| 1170 |
maxdata = max(data) |
| 1171 |
if maxdata < 256: |
| 1172 |
return 1 |
| 1173 |
elif maxdata < 65536: |
| 1174 |
return 2 |
| 1175 |
else: |
| 1176 |
return 4 |
| 1177 |
|
| 1178 |
|
| 1179 |
def splitbins(t: List[int], trace=0) -> Tuple[List[int], List[int], int]: |
| 1180 |
"""t, trace=0 -> (t1, t2, shift). Split a table to save space. |
| 1181 |
|
| 1182 |
t is a sequence of ints. This function can be useful to save space if |
| 1183 |
many of the ints are the same. t1 and t2 are lists of ints, and shift |
| 1184 |
is an int, chosen to minimize the combined size of t1 and t2 (in C |
| 1185 |
code), and where for each i in range(len(t)), |
| 1186 |
t[i] == t2[(t1[i >> shift] << shift) + (i & mask)] |
| 1187 |
where mask is a bitmask isolating the last "shift" bits. |
| 1188 |
|
| 1189 |
If optional arg trace is non-zero (default zero), progress info |
| 1190 |
is printed to sys.stderr. The higher the value, the more info |
| 1191 |
you'll get. |
| 1192 |
""" |
| 1193 |
|
| 1194 |
if trace: |
| 1195 |
|
| 1196 |
def dump(t1, t2, shift, bytes): |
| 1197 |
print( |
| 1198 |
"%d+%d bins at shift %d; %d bytes" % (len(t1), len(t2), shift, bytes), |
| 1199 |
file=sys.stderr, |
| 1200 |
) |
| 1201 |
|
| 1202 |
print("Size of original table:", len(t) * getsize(t), "bytes", file=sys.stderr) |
| 1203 |
n = len(t) - 1 |
| 1204 |
maxshift = 0 |
| 1205 |
if n > 0: |
| 1206 |
while n >> 1: |
| 1207 |
n >>= 1 |
| 1208 |
maxshift += 1 |
| 1209 |
del n |
| 1210 |
bytes = sys.maxsize |
| 1211 |
t = tuple(t) |
| 1212 |
for shift in range(maxshift + 1): |
| 1213 |
t1 = [] |
| 1214 |
t2 = [] |
| 1215 |
size = 2 ** shift |
| 1216 |
bincache = {} |
| 1217 |
for i in range(0, len(t), size): |
| 1218 |
bin = t[i : i + size] |
| 1219 |
index = bincache.get(bin) |
| 1220 |
if index is None: |
| 1221 |
index = len(t2) |
| 1222 |
bincache[bin] = index |
| 1223 |
t2.extend(bin) |
| 1224 |
t1.append(index >> shift) |
| 1225 |
|
| 1226 |
b = len(t1) * getsize(t1) + len(t2) * getsize(t2) |
| 1227 |
if trace > 1: |
| 1228 |
dump(t1, t2, shift, b) |
| 1229 |
if b < bytes: |
| 1230 |
best = t1, t2, shift |
| 1231 |
bytes = b |
| 1232 |
t1, t2, shift = best |
| 1233 |
if trace: |
| 1234 |
print("Best:", end=" ", file=sys.stderr) |
| 1235 |
dump(t1, t2, shift, bytes) |
| 1236 |
if __debug__: |
| 1237 |
|
| 1238 |
mask = ~((~0) << shift) |
| 1239 |
for i in range(len(t)): |
| 1240 |
assert t[i] == t2[(t1[i >> shift] << shift) + (i & mask)] |
| 1241 |
return best |
| 1242 |
|
| 1243 |
|
| 1244 |
def maketables(trace=0): |
| 1245 |
print("--- Reading", UNICODE_DATA % "", "...") |
| 1246 |
|
| 1247 |
unicode = UnicodeData(UNIDATA_VERSION) |
| 1248 |
utype_funcs = makeutype(unicode, trace) |
| 1249 |
unialt_funcs = makeunialt(unicode, trace) |
| 1250 |
makearabicforms(unicode, trace) |
| 1251 |
makeuninames(unicode, trace) |
| 1252 |
makeutypeheader(utype_funcs + unialt_funcs) |
| 1253 |
|
| 1254 |
|
| 1255 |
if __name__ == "__main__": |
| 1256 |
maketables(1) |