Debian Codegraph @

scripts/update-keysyms-case-mappings.py

raw
1 #!/usr/bin/env python3
2
3 # This script creates the keysym case mappings in `src/keysym-case-mappings.c`.
4 #
5 # Inspired from: https://github.com/apankrat/notes/blob/3c551cb028595fd34046c5761fd12d1692576003/fast-case-conversion/README.md
6
7 # NOTE: the following docstring is also used to document the resulting C file.
8
9 """
10 There are two kinds of keysyms to consider:
11 • Legacy keysyms: their case mappings is located at `data/keysyms.yaml`.
12 • Unicode keysyms: their case mappings come from the ICU library.
13
14 These mappings would create huge lookup tables if done naively. Fortunately,
15 we can observe that if we compute only the *difference* between a keysym and
16 its corresponding case mapping, there are a lot of repetitions that can be
17 efficiently compressed.
18
19 The idea for the compression is, for each kind of keysyms:
20 1. Compute the deltas between the keysyms and their case mappings.
21 2. Split the delta array in chunks of a given size.
22 3. Rearrange the order of the chunks in order to optimize consecutive
23 chunks overlap.
24 4. Create a data table with the reordered chunks and an index table that
25 maps the original chunk index to its offset in the data table.
26
27 Trivial example (chunk size: 4, from step 2):
28
29 [1, 2, 3, 4, 2, 3, 4, 5, 0, 1, 2, 3] # source data
30 -> [[1, 2, 3, 4], [2, 3, 4, 5], [0, 1, 2, 3]] # make chunks
31 -> [[0, 1, 2, 3], [1, 2, 3, 4], [2, 3, 4, 5]] # rearrange to have best overlaps
32 -> {data: [0, 1, 2, 3, 4, 5], offsets: [1, 2, 0]} # overlap chunks & compute
33 # their offsets
34
35 Then we can retrieve the data from the original array at index i with the
36 following formula:
37
38 mask = (1 << chunk_size) - 1;
39 original[i] = data[offsets[i >> chunk_size] + (i & mask)];
40
41 Since the index array is itself quite repetitive with the real data, we apply
42 the compression a second time to the offsets table.
43
44 The complete algorithm optimizes the chunk sizes for both arrays in order to
45 get the lowest total data size.
46
47 There are 6 resulting arrays, 3 for each kind of keysyms:
48 1. The data array. Each item is either:
49 • 0, if the keysym is not cased.
50 • A delta to lower case.
51 • A delta to upper case.
52 • For some special cases, there are both a lower *and* an upper case
53 mapping. The delta is identical in both cases.
54 2. The 1st offsets array, that provides offsets into the data array.
55 3. The 2nd offsets array, that provides offsets into the 1st index array.
56
57 Finally, given the chunks sizes `cs_data` and `cs_offsets`:
58 1. We compute the corresponding masks:
59 • `mask_data = (1 << cs_data) - 1` and
60 • `mask_offsets = (1 << cs_offsets) - 1`.
61 2. We can retrieve the case mapping of a keysyms `ks` with the following
62 formula:
63
64 data[
65 offsets1[
66 offsets2[ks >> (cs_data + cs_offsets)] +
67 ((ks >> cs_data) & mask_offsets)
68 ] +
69 (ks & mask_data)
70 ];
71 """
72
73 from __future__ import annotations
74
75 import argparse
76 import ctypes
77 import itertools
78 import math
79 import os
80 import re
81 import sys
82 import textwrap
83 from abc import ABCMeta, abstractmethod
84 from collections import defaultdict
85 from collections.abc import Callable
86 from ctypes.util import find_library
87 from dataclasses import dataclass
88 from enum import Enum, unique
89 from functools import cache, reduce
90 import importlib.util
91 from pathlib import Path
92 from typing import (
93 Any,
94 ClassVar,
95 Generator,
96 Generic,
97 Iterable,
98 NewType,
99 Protocol,
100 Self,
101 Sequence,
102 TypeAlias,
103 TypeVar,
104 cast,
105 )
106 import unicodedata
107
108 import jinja2
109 import yaml
110
111 assert sys.version_info >= (3, 12)
112
113 try:
114 import icu
115
116 c = icu.Locale.createFromName("C")
117 icu.Locale.setDefault(c)
118 except ImportError:
119 icu = None
120
121 SCRIPT = Path(__file__)
122 CodePoint = NewType("CodePoint", int)
123 Keysym = NewType("Keysym", int)
124 KeysymName = NewType("KeysymName", str)
125
126 T = TypeVar("T")
127 X = TypeVar("X", int, CodePoint, Keysym)
128
129 ################################################################################
130 # Configuration
131 ################################################################################
132
133
134 @dataclass
135 class Config:
136 check_error: bool
137 verbose: bool
138
139
140 ################################################################################
141 # XKBCOMMON
142 ################################################################################
143
144
145 class XKBCOMMON:
146 XKB_KEYSYM_MIN = Keysym(0)
147 XKB_KEYSYM_MAX = Keysym(0x1FFFFFFF)
148 XKB_KEYSYM_MIN_EXPLICIT = Keysym(0x00000000)
149 XKB_KEYSYM_MAX_EXPLICIT = Keysym(0x1008FFB8)
150 XKB_KEYSYM_UNICODE_OFFSET = Keysym(0x01000000)
151 XKB_KEYSYM_UNICODE_MIN = Keysym(0x01000100)
152 XKB_KEYSYM_UNICODE_MAX = Keysym(0x0110FFFF)
153 XKB_KEY_NoSymbol = Keysym(0)
154 xkb_keysym_t = ctypes.c_uint32
155 XKB_KEYSYM_NO_FLAGS = 0
156
157 def __init__(self) -> None:
158 self._xkbcommon_path = os.environ.get("XKBCOMMON_LIB_PATH")
159
160 if self._xkbcommon_path:
161 self._xkbcommon_path = str(Path(self._xkbcommon_path).resolve())
162 self._lib = ctypes.cdll.LoadLibrary(self._xkbcommon_path)
163 else:
164 self._xkbcommon_path = find_library("xkbcommon")
165 if self._xkbcommon_path:
166 self._lib = ctypes.cdll.LoadLibrary(self._xkbcommon_path)
167 else:
168 raise OSError("Cannot load libxbcommon")
169
170 self._lib.xkb_keysym_to_lower.argtypes = [self.xkb_keysym_t]
171 self._lib.xkb_keysym_to_lower.restype = self.xkb_keysym_t
172
173 self._lib.xkb_keysym_to_upper.argtypes = [self.xkb_keysym_t]
174 self._lib.xkb_keysym_to_upper.restype = self.xkb_keysym_t
175
176 self._lib.xkb_keysym_to_utf8.argtypes = [
177 self.xkb_keysym_t,
178 ctypes.c_char_p,
179 ctypes.c_size_t,
180 ]
181 self._lib.xkb_keysym_to_utf8.restype = ctypes.c_int
182
183 self._lib.xkb_keysym_to_utf32.argtypes = [self.xkb_keysym_t]
184 self._lib.xkb_keysym_to_utf32.restype = ctypes.c_uint32
185
186 self._lib.xkb_keysym_from_name.argtypes = [ctypes.c_char_p, ctypes.c_int]
187 self._lib.xkb_keysym_from_name.restype = self.xkb_keysym_t
188
189 self._lib.xkb_utf32_to_keysym.argtypes = [ctypes.c_uint32]
190 self._lib.xkb_utf32_to_keysym.restype = self.xkb_keysym_t
191
192 def keysym_from_name(self, keysym_name: KeysymName) -> Keysym:
193 return self._lib.xkb_keysym_from_name(
194 keysym_name.encode("utf-8"), self.XKB_KEYSYM_NO_FLAGS
195 )
196
197 def keysym_from_cp(self, cp: CodePoint) -> Keysym:
198 return self._lib.xkb_utf32_to_keysym(cp)
199
200 def keysym_from_char(self, char: str) -> Keysym:
201 return self._lib.xkb_utf32_to_keysym(ord(char))
202
203 def keysym_to_lower(self, keysym: Keysym) -> Keysym:
204 return self._lib.xkb_keysym_to_lower(keysym)
205
206 def keysym_to_upper(self, keysym: Keysym) -> Keysym:
207 return self._lib.xkb_keysym_to_upper(keysym)
208
209 def keysym_to_str(self, keysym: Keysym) -> str:
210 buf_len = 7
211 buf = ctypes.create_string_buffer(buf_len)
212 n = self._lib.xkb_keysym_to_utf8(keysym, buf, ctypes.c_size_t(buf_len))
213 if n < 0:
214 raise ValueError(f"Unsupported keysym: 0x{keysym:0>4X})")
215 elif n >= buf_len:
216 raise ValueError(f"Buffer is not big enough: expected at least {n}.")
217 else:
218 return buf.value.decode("utf-8")
219
220 def keysym_code_point(self, keysym: Keysym) -> int:
221 return self._lib.xkb_keysym_to_utf32(keysym)
222
223 def iter_case_mappings(self, unicode: bool) -> Iterable[tuple[Keysym, Entry]]:
224 for keysym in map(
225 Keysym,
226 range(self.XKB_KEYSYM_MIN_EXPLICIT, self.XKB_KEYSYM_MAX_EXPLICIT + 1),
227 ):
228 if (
229 not unicode
230 and self.XKB_KEYSYM_UNICODE_OFFSET
231 <= keysym
232 <= self.XKB_KEYSYM_UNICODE_MAX
233 ) or not self.keysym_code_point(keysym):
234 continue
235 cp = self.keysym_code_point(keysym)
236 yield (
237 keysym,
238 Entry(
239 lower=self.keysym_to_lower(keysym) - keysym,
240 upper=keysym - self.keysym_to_upper(keysym),
241 # FIXME: should use xkbcommon API, but it’s not exposed
242 is_lower=icu.Char.isULowercase(cp),
243 is_upper=icu.Char.isUUppercase(cp) or icu.istitle(cp),
244 ),
245 )
246
247 def case_mappings(self, unicode: bool) -> tuple[Entry, ...]:
248 mappings = dict(self.iter_case_mappings(unicode))
249 keysym_max = max(mappings)
250 return tuple(
251 mappings.get(cast(Keysym, ks), Entry.zeros())
252 for ks in range(0, keysym_max + 1)
253 )
254
255
256 xkbcommon = XKBCOMMON()
257
258
259 def load_keysyms(path: Path, unicode: bool) -> tuple[Entry, ...]:
260 with path.open("rt", encoding="utf-8") as fd:
261 keysyms = {
262 ks: entry
263 for ks, data in yaml.safe_load(fd).items()
264 if unicode
265 or (
266 ks < XKBCOMMON.XKB_KEYSYM_UNICODE_MIN
267 or ks > XKBCOMMON.XKB_KEYSYM_UNICODE_MAX
268 )
269 if data.get("code point")
270 if (
271 entry := Entry(
272 data.get("lower", ks) - ks,
273 ks - data.get("upper", ks),
274 is_lower=icu.Char.isULowercase(data.get("code point")),
275 is_upper=icu.Char.isUUppercase(data.get("code point"))
276 or icu.Char.istitle(data.get("code point")),
277 )
278 )
279 }
280 # Check either non-cased, upper or lower
281 errors = []
282 for ks, e in keysyms.items():
283 if e.lower and e.upper and e.lower != e.upper:
284 errors.append((ks, e))
285 if errors:
286 raise ValueError(errors)
287 keysym_max = max(keysyms)
288 return tuple(keysyms.get(ks, Entry.zeros()) for ks in range(0, keysym_max + 1))
289
290
291 ################################################################################
292 # Case mapping
293 ################################################################################
294
295
296 @dataclass(frozen=True, order=True)
297 class Entry:
298 """
299 Case mapping deltas for a character or a keysym.
300 """
301
302 lower: int
303 upper: int
304 is_lower: bool
305 is_upper: bool
306 # [NOTE] Exceptions must be documented in `xkbcommon.h`.
307 to_upper_exceptions: ClassVar[dict[str, str]] = {"ß": "ẞ"}
308 "Upper mappings exceptions"
309
310 @classmethod
311 def zeros(cls) -> Self:
312 return cls(lower=0, upper=0, is_lower=False, is_upper=False)
313
314 def __bool__(self) -> bool:
315 return any(self) or self.is_lower or self.is_upper
316
317 def __str__(self) -> str:
318 return str(tuple(self))
319
320 def __iter__(self) -> Generator[int, None, None]:
321 yield self.lower
322 yield self.upper
323
324 @classmethod
325 def from_code_point(cls, cp: CodePoint) -> Self:
326 return cls(
327 lower=cls.lower_delta(cp),
328 upper=cls.upper_delta(cp),
329 is_lower=icu.Char.isULowercase(cp),
330 is_upper=icu.Char.isUUppercase(cp) or icu.Char.istitle(cp),
331 )
332
333 @classmethod
334 def lower_delta(cls, cp: CodePoint) -> int:
335 return cls.to_lower_cp(cp) - cp
336
337 @classmethod
338 def upper_delta(cls, cp: CodePoint) -> int:
339 return cp - cls.to_upper_cp(cp)
340
341 @classmethod
342 def to_upper_cp(cls, cp: CodePoint) -> CodePoint:
343 if upper := cls.to_upper_exceptions.get(chr(cp)):
344 return ord(upper)
345 return icu.Char.toupper(cp)
346
347 @staticmethod
348 def to_lower_cp(cp: CodePoint) -> CodePoint:
349 return icu.Char.tolower(cp)
350
351 @classmethod
352 def to_upper_char(cls, char: str) -> str:
353 if upper := cls.to_upper_exceptions.get(char):
354 return upper
355 return icu.Char.toupper(char)
356
357 @staticmethod
358 def to_lower_char(char: str) -> str:
359 return icu.Char.tolower(char)
360
361 def to_lower(self, x: X) -> X:
362 return x.__class__(x + self.lower)
363
364 def to_upper(self, x: X) -> X:
365 return x.__class__(x - self.upper)
366
367
368 @dataclass
369 class Deltas(Generic[T]):
370 """
371 Sequences of case mappings deltas
372 """
373
374 keysyms: tuple[T, ...]
375 keysym_max: Keysym
376 "Maximum keysym with a case mapping"
377 unicode: tuple[T, ...]
378 unicode_max: CodePoint
379 "Maximum Unicode code point with a case mapping"
380
381
382 class Entries(Deltas[Entry]):
383 @classmethod
384 def compute(
385 cls,
386 config: Config,
387 path: Path | None = None,
388 ) -> Self:
389 # Keysyms
390 if path:
391 keysyms_deltas = load_keysyms(path, unicode=False)
392 else:
393 keysyms_deltas = xkbcommon.case_mappings(True)
394 max_keysym = max(Keysym(ks) for ks, e in enumerate(keysyms_deltas) if e)
395 assert max_keysym
396 keysyms_deltas = keysyms_deltas[: max_keysym + 1]
397
398 # Unicode
399 unicode_deltas = tuple(
400 Entry.from_code_point(CodePoint(cp)) for cp in range(0, sys.maxunicode + 1)
401 )
402 max_unicode = max((CodePoint(cp) for cp, d in enumerate(unicode_deltas) if d))
403 assert max_unicode
404 unicode_deltas = unicode_deltas[: max_unicode + 1]
405 errors = []
406 for n, e1 in enumerate(unicode_deltas):
407 cp = CodePoint(n)
408 # Check with legacy keysyms
409 keysym = xkbcommon.keysym_from_cp(cp)
410 if keysym <= max_keysym:
411 e2 = keysyms_deltas[keysym]
412 if e1 or e2:
413 cls.check(
414 config,
415 "lower",
416 cp,
417 e1.to_lower(cp),
418 keysym,
419 e2.to_lower(keysym),
420 )
421 cls.check(
422 config,
423 "upper",
424 cp,
425 e1.to_upper(cp),
426 keysym,
427 e2.to_upper(keysym),
428 )
429 # Check character has either
430 # • No case mapping
431 # • Lower or an upper mapping
432 # • Both, with the same delta
433 if e1.lower and e1.upper and e1.lower != e1.upper:
434 errors.append((cp, e1))
435 if errors:
436 raise ValueError(errors)
437 return cls(
438 keysyms=keysyms_deltas,
439 keysym_max=max_keysym,
440 unicode=unicode_deltas,
441 unicode_max=max_unicode,
442 )
443
444 @classmethod
445 def check(
446 cls,
447 config: Config,
448 casing: str,
449 cp: CodePoint,
450 cpʹ: CodePoint,
451 keysym: Keysym,
452 keysymʹ: Keysym,
453 ) -> None:
454 char = chr(cp)
455 expected = chr(cpʹ)
456 got = xkbcommon.keysym_to_str(keysymʹ)
457 data = (
458 hex(keysym),
459 hex(cp),
460 char,
461 hex(keysymʹ),
462 got,
463 expected,
464 )
465 if config.check_error:
466 assert got == expected, data
467 elif got != expected:
468 print(
469 f"Error: legacy keysym 0x{keysym:4>x} has incorrect {casing} mapping:",
470 data,
471 )
472
473 @property
474 def lower(self) -> Deltas[int]:
475 return Deltas(
476 keysyms=tuple(e.lower for e in self.keysyms),
477 keysym_max=self.keysym_max,
478 unicode=tuple(e.lower for e in self.unicode),
479 unicode_max=self.unicode_max,
480 )
481
482 @property
483 def upper(self) -> Deltas[int]:
484 return Deltas(
485 keysyms=tuple(e.upper for e in self.keysyms),
486 keysym_max=self.keysym_max,
487 unicode=tuple(e.upper for e in self.unicode),
488 unicode_max=self.unicode_max,
489 )
490
491
492 @dataclass(frozen=True)
493 class DeltasPair(Generic[T]):
494 d1: tuple[T, ...]
495 d2: tuple[T, ...]
496 overlap: int
497
498 def __contains__(self, x: tuple[T, ...]) -> bool:
499 return (x == self.d1) or (x == self.d2)
500
501 @classmethod
502 def compute_pairs_overlaps(
503 cls, deltas: Iterable[tuple[T, ...]]
504 ) -> Generator[DeltasPair[T], None, None]:
505 for d1, d2 in itertools.combinations(deltas, 2):
506 if overlap := Overlap.compute_simple(d1, d2):
507 yield DeltasPair(d1, d2, overlap)
508 if overlap := Overlap.compute_simple(d2, d1):
509 yield DeltasPair(d2, d1, overlap)
510
511 def remove_from_pairs(
512 self, pairs: list[DeltasPair[T]]
513 ) -> Generator[DeltasPair[T], None, None]:
514 for p in pairs:
515 if p.d1 not in self and p.d2 not in self:
516 yield p
517
518 @classmethod
519 def remove_chunk_from_pairs(
520 cls, pairs: Iterable[DeltasPair[T]], chunk: tuple[T, ...]
521 ) -> Generator[DeltasPair[T], None, None]:
522 for p in pairs:
523 if chunk not in p:
524 yield p
525
526 @classmethod
527 def compute_best_pair(cls, pairs: Iterable[DeltasPair[T]]) -> DeltasPair[T]:
528 return max(pairs, key=lambda p: p.overlap)
529
530
531 ################################################################################
532 # Overlap
533 ################################################################################
534
535
536 @dataclass
537 class Overlap:
538 "Overlap of two sequences"
539
540 offset: int
541 overlap: int
542
543 @staticmethod
544 @cache
545 def compute_simple(s1: Sequence[T], s2: Sequence[T]) -> int:
546 return max((n for n in range(0, len(s1) + 1) if s1[-n:] == s2[:n]), default=0)
547
548 @classmethod
549 @cache
550 def compute(cls, s1: Sequence[T], s2: Sequence[T]) -> Self:
551 l1 = len(s1)
552 l2 = len(s2)
553 return max(
554 (
555 cls(offset=start, overlap=overlap)
556 for start in range(0, l1)
557 if (end := min(start + l2, l1))
558 and (overlap := end - start)
559 and s1[start:end] == s2[:overlap]
560 ),
561 key=lambda x: x.overlap,
562 default=cls(offset=l1, overlap=0),
563 )
564
565 @classmethod
566 def test(cls) -> None:
567 c1 = (1, 2, 3, 4)
568 c2 = (2, 3)
569 c3 = (3, 2, 1)
570 c4 = (3, 4, 5)
571 c5 = (1, 2, 4)
572 overlap = cls.compute(c1, c2)
573 assert overlap == cls(1, 2)
574 overlap = cls.compute(c3, c1)
575 assert overlap == cls(2, 1)
576 overlap = cls.compute(c1, c4)
577 assert overlap == cls(2, 2)
578 overlap = cls.compute(c1, c5)
579 assert overlap == cls(4, 0), overlap
580
581
582 ################################################################################
583 # Groups
584 ################################################################################
585
586 Groups: TypeAlias = dict[tuple[T, ...], list[int]]
587
588
589 def generate_groups(block_size: int, data: Iterable[T]) -> Groups[T]:
590 groups: defaultdict[tuple[T, ...], list[int]] = defaultdict(list)
591 for n, d in enumerate(itertools.batched(data, block_size)):
592 groups[d].append(n)
593 return groups
594
595
596 ################################################################################
597 # Overlapped Sequences
598 ################################################################################
599
600
601 @dataclass
602 class OverlappedSequences(Generic[T]):
603 data: tuple[T, ...]
604 offsets: dict[tuple[T, ...], int]
605
606 def __bool__(self) -> bool:
607 return bool(self.data)
608
609 def __hash__(self) -> int:
610 return hash((self.data, tuple(self.offsets)))
611
612 def __add__(self, x: Any) -> Self:
613 if isinstance(x, self.__class__):
614 return self.extend(x)
615 elif isinstance(x, tuple):
616 return self.add(x)
617 else:
618 return NotImplemented
619
620 def __iadd__(self, x: Any) -> Self:
621 if isinstance(x, self.__class__):
622 overlap = Overlap.compute(self.data, x.data)
623 self.data = (
624 self.data
625 if overlap.offset <= len(self.data) - len(x.data)
626 else self.data + x.data[overlap.overlap :]
627 )
628 for c, o in x.offsets.items():
629 self.offsets[c] = overlap.offset + o
630 return self
631 elif isinstance(x, tuple):
632 overlap = Overlap.compute(self.data, x)
633 self.data = (
634 self.data
635 if overlap.offset <= len(self.data) - len(x)
636 else self.data + x[overlap.overlap :]
637 )
638 self.offsets[x] = overlap.offset
639 return self
640 else:
641 return NotImplemented
642
643 @classmethod
644 def from_singleton(cls, chunk: tuple[T, ...]) -> Self:
645 return cls(data=chunk, offsets={chunk: 0})
646
647 @classmethod
648 def from_pair(cls, pair: DeltasPair[T]) -> Self:
649 return cls(
650 data=pair.d1 + pair.d2[pair.overlap :],
651 offsets={
652 pair.d1: 0,
653 pair.d2: len(pair.d1) - pair.overlap,
654 },
655 )
656
657 @classmethod
658 def from_iterable(cls, ts: Iterable[tuple[T, ...]]) -> Self:
659 return reduce(lambda s, t: s.add(t), ts, cls((), {}))
660
661 @classmethod
662 def from_ordered_iterable(cls, ts: Iterable[tuple[T, ...]]) -> Self:
663 return reduce(lambda s, t: s.append(t), ts, cls((), {}))
664
665 def extend(self, s: Self) -> Self:
666 overlap: Overlap
667 s1: Self
668 s2: Self
669 overlap, s1, s2 = max(
670 (
671 (Overlap.compute(self.data, s.data), self, s),
672 (Overlap.compute(s.data, self.data), s, self),
673 ),
674 key=lambda x: x[0].overlap,
675 )
676
677 data = (
678 s1.data
679 if overlap.offset <= len(s1.data) - len(s2.data)
680 else s1.data + s2.data[overlap.overlap :]
681 )
682 offsets = dict(s1.offsets)
683 for c, o in s2.offsets.items():
684 offsets[c] = overlap.offset + o
685 return self.__class__(data=data, offsets=offsets)
686
687 def add(self, chunk: tuple[T, ...]) -> Self:
688 return self.extend(self.from_singleton(chunk))
689
690 def append(self, chunk: tuple[T, ...]) -> Self:
691 overlap = Overlap.compute(self.data, chunk)
692 self.data = (
693 self.data
694 if overlap.offset <= len(self.data) - len(chunk)
695 else self.data + chunk[overlap.overlap :]
696 )
697 self.offsets[chunk] = overlap.offset
698 return self
699
700 def insert(self, offset: int, overlap: int, chunk: tuple[T, ...]) -> None:
701 chunk_length = len(chunk)
702 if offset < 0:
703 self.data = chunk[:-overlap] + self.data
704 assert chunk == self.data[:chunk_length]
705 for c in self.offsets:
706 self.offsets[c] += -offset
707 self.offsets[chunk] = 0
708 elif offset <= len(self.data) - len(chunk):
709 assert self.data[offset : offset + chunk_length] == chunk
710 self.offsets[chunk] = offset
711 else:
712 self.data += chunk[overlap:]
713 assert self.data[offset:] == chunk
714 self.offsets[chunk] = offset
715
716 def merge(self, offset: int, overlap: int, s: OverlappedSequences[T]) -> None:
717 s_length = len(s.data)
718 if offset < 0:
719 self.data = s.data[:-overlap] + self.data
720 assert s.data == self.data[:s_length]
721 for c in self.offsets:
722 self.offsets[c] += -offset
723 self.offsets.update(s.offsets)
724 elif offset <= len(self.data) - len(s.data):
725 assert self.data[offset : offset + s_length] == s.data
726 for c, offset2 in s.offsets.items():
727 self.offsets[c] = offset2 + offset
728 else:
729 self.data += s.data[overlap:]
730 assert self.data[offset:] == s.data
731 for c, offset2 in s.offsets.items():
732 self.offsets[c] = offset2 + offset
733
734 def flatten_iter(self) -> Generator[tuple[T, ...], None, None]:
735 for t, _ in sorted(self.offsets.items(), key=lambda x: x[1]):
736 yield t
737
738 def flatten(self) -> list[tuple[T, ...]]:
739 return list(self.flatten_iter())
740
741 def flatten_groups_iter(self) -> Generator[list[tuple[T, ...]], None, None]:
742 i = self.flatten_iter()
743 g = [next(i)]
744 for t in i:
745 if Overlap.compute(g[-1], t).overlap:
746 g.append(t)
747 else:
748 yield g
749 g = [t]
750 yield g
751
752 def split(self) -> list[OverlappedSequences[T]]:
753 offsets = sorted(self.offsets.items(), key=lambda x: x[1])
754 start = 0
755 pending: dict[tuple[T, ...], int] = {}
756 end = 0
757 new: list[OverlappedSequences[T]] = []
758 for d, i in offsets:
759 # print(start, end, d, i)
760 if end and i >= end:
761 assert start < end
762 new.append(
763 OverlappedSequences(data=self.data[start:end], offsets=pending)
764 )
765 pending = {d: 0}
766 start = i
767 else:
768 pending[d] = i - start
769 end = max(end, i + len(d))
770 assert start < end
771 new.append(OverlappedSequences(data=self.data[start:end], offsets=pending))
772 return new
773
774 def total_overlap(self) -> int:
775 return sum(len(d) for d in self.offsets) - len(self.data)
776
777
778 class _OverlappedSequences(OverlappedSequences[int]):
779 @classmethod
780 def test(cls) -> None:
781 c1: tuple[int, ...] = (1, 2, 3, 4)
782 c2: tuple[int, ...] = (2, 3)
783 c3: tuple[int, ...] = (3, 4, 5)
784 c4: tuple[int, ...] = (1, 3)
785 assert cls(c1, {}).add(c2) == cls(c1, {c2: 1})
786 assert cls(c1, {}).add(c3) == cls(c1 + c3[2:], {c3: 2})
787 assert cls(c1, {}).add(c4) == cls(c1 + c4, {c4: len(c1)})
788
789 assert cls(c1, {}) + cls(c2, {c2: 0}) == cls(c1, {c2: 1})
790 assert cls(c1, {}) + cls(c3, {c3: 0}) == cls(c1 + c3[2:], {c3: 2})
791 assert cls(c1, {}) + cls(c4, {c4: 0}) == cls(c1 + c4, {c4: len(c1)})
792
793 assert cls(c2, {c2: 0}) + cls(c1, {}) == cls(c1, {c2: 1})
794 assert cls(c3, {c3: 0}) + cls(c1, {}) == cls(c1 + c3[2:], {c3: 2})
795 assert cls(c4, {c4: 0}) + cls(c1, {}) == cls(c4 + c1, {c4: 0})
796
797 c5 = (1, 2, 3, 4, 5, 6)
798 c6 = (1,)
799 c7 = (6,)
800 s = cls(c5, {c6: 0, c2: 1, c3: 2, c7: 5})
801 assert s.total_overlap() == 1, s.total_overlap()
802 assert s.split() == [
803 cls(c6, {c6: 0}),
804 cls(c5[1:-1], {c2: 0, c3: 1}),
805 cls(c7, {c7: 0}),
806 ], s.split()
807
808 cs = s.flatten()
809 assert cs == [c6, c2, c3, c7], cs
810 assert cls.from_iterable(cs) == s
811
812
813 ################################################################################
814 # Chunks compressor
815 ################################################################################
816
817
818 class Move(Protocol, Generic[T]):
819 def __call__(
820 self,
821 pairs: list[DeltasPair[T]],
822 remaining_chunks: set[tuple[T, ...]],
823 overlapped_sequences: list[OverlappedSequences[T]],
824 ) -> None: ...
825
826
827 @dataclass
828 class ChunksCompressor:
829 verbose: bool
830
831 @classmethod
832 def _insert(
833 cls, chunk: tuple[T, ...], index: int, offset: int, overlap: int
834 ) -> Move[T]:
835 def action(
836 pairs: list[DeltasPair[T]],
837 remaining_chunks: set[tuple[T, ...]],
838 overlapped_sequences: list[OverlappedSequences[T]],
839 ) -> None:
840 remaining_chunks.remove(chunk)
841 pairs[:] = DeltasPair.remove_chunk_from_pairs(pairs, chunk)
842 s = overlapped_sequences[index]
843 s.insert(offset, overlap, chunk)
844
845 return action
846
847 @classmethod
848 def _merge(cls, index1: int, index2: int, offset: int, overlap: int) -> Move[T]:
849 def action(
850 pairs: list[DeltasPair[T]],
851 remaining_chunks: set[tuple[T, ...]],
852 overlapped_sequences: list[OverlappedSequences[T]],
853 ) -> None:
854 s1 = overlapped_sequences[index1]
855 s2 = overlapped_sequences.pop(index2)
856 s1.merge(offset, overlap, s2)
857
858 return action
859
860 @classmethod
861 def _add_new_singleton(cls, chunk: tuple[T, ...]) -> Move[T]:
862 def action(
863 pairs: list[DeltasPair[T]],
864 remaining_chunks: set[tuple[T, ...]],
865 overlapped_sequences: list[OverlappedSequences[T]],
866 ) -> None:
867 remaining_chunks.remove(chunk)
868 pairs[:] = DeltasPair.remove_chunk_from_pairs(pairs, chunk)
869 overlapped_sequences.append(OverlappedSequences.from_singleton(chunk))
870
871 return action
872
873 @classmethod
874 def _add_new_sequence(cls, pair: DeltasPair[T]) -> Move[T]:
875 def action(
876 pairs: list[DeltasPair[T]],
877 remaining_chunks: set[tuple[T, ...]],
878 overlapped_sequences: list[OverlappedSequences[T]],
879 ) -> None:
880 remaining_chunks.remove(pair.d1)
881 remaining_chunks.remove(pair.d2)
882 pairs[:] = pair.remove_from_pairs(pairs)
883 assert pair not in pairs
884 overlapped_sequences.append(OverlappedSequences.from_pair(pair))
885
886 return action
887
888 def compress(self, chunks: Iterable[tuple[T, ...]]) -> OverlappedSequences[T]:
889 # Prepare data and offsets
890 pairs = list(DeltasPair.compute_pairs_overlaps(chunks))
891
892 remaining_chunks = set(chunks)
893
894 if self.verbose:
895 print(
896 "Count of chunks:",
897 len(remaining_chunks),
898 )
899
900 overlapped_sequences: list[OverlappedSequences[T]] = []
901 best_move: Move[T] | None = None
902 total_chunks = len(remaining_chunks)
903 while remaining_chunks or (len(overlapped_sequences) > 1 and best_move):
904 if self.verbose:
905 print(
906 f"# Remaining: {len(remaining_chunks)}/{total_chunks}",
907 "Current pairs:",
908 len(overlapped_sequences),
909 )
910 best_move = None
911 best_overlap: int = 0
912 # Try inserting
913 for n, s in enumerate(overlapped_sequences):
914 for d in remaining_chunks:
915 # Try prepend
916 overlap = Overlap.compute_simple(d, s.data)
917 if overlap > best_overlap:
918 best_overlap = overlap
919 best_move = self._insert(d, n, overlap - len(d), overlap)
920 if self.verbose:
921 print(
922 "Insert chunk (prepend)",
923 best_overlap,
924 len(overlapped_sequences),
925 )
926 # Try insert
927 overlap_max = Overlap.compute(s.data, d)
928 if overlap_max.overlap > best_overlap:
929 best_overlap = overlap_max.overlap
930 best_move = self._insert(
931 d, n, overlap_max.offset, overlap_max.overlap
932 )
933 if self.verbose:
934 print(
935 "Insert chunk (append)",
936 overlap_max,
937 len(overlapped_sequences),
938 )
939 # Try merging
940 for n1, n2 in itertools.permutations(range(len(overlapped_sequences)), 2):
941 s1 = overlapped_sequences[n1]
942 s2 = overlapped_sequences[n2]
943 # Try insert
944 overlap_max = Overlap.compute(s1.data, s2.data)
945 if overlap_max.overlap > best_overlap:
946 best_overlap = overlap_max.overlap
947 best_move = self._merge(
948 n1, n2, overlap_max.offset, overlap_max.overlap
949 )
950 if self.verbose:
951 print(
952 "Merge 2 sequences",
953 overlap_max,
954 len(overlapped_sequences),
955 )
956
957 # Take next best pair
958 if (
959 pairs
960 and (best_pair := DeltasPair.compute_best_pair(pairs))
961 and best_pair.overlap > best_overlap
962 ):
963 best_overlap = best_pair.overlap
964 best_move = self._add_new_sequence(best_pair)
965 if self.verbose:
966 print("Add new sequence", best_overlap, len(overlapped_sequences))
967 if not best_move:
968 if self.verbose:
969 print("No best move", len(overlapped_sequences))
970 if remaining_chunks:
971 best_move = self._add_new_singleton(min(remaining_chunks))
972 if best_move:
973 best_move(
974 pairs=pairs,
975 remaining_chunks=remaining_chunks,
976 overlapped_sequences=overlapped_sequences,
977 )
978
979 assert len(overlapped_sequences) >= 1
980 assert not remaining_chunks
981
982 if (l := len(overlapped_sequences)) > 1:
983 if self.verbose:
984 print("Force merging remaining sequences", l)
985
986 for n1, n2 in itertools.permutations(range(len(overlapped_sequences)), 2):
987 s1 = overlapped_sequences[n1]
988 s2 = overlapped_sequences[n2]
989 overlap_max = Overlap.compute(s1.data, s2.data)
990 assert overlap_max.overlap == 0, overlap_max
991
992 for _ in range(1, len(overlapped_sequences)):
993 move: Move[T] = self._merge(0, 1, len(overlapped_sequences[0].data), 0)
994 move(
995 pairs=pairs,
996 remaining_chunks=remaining_chunks,
997 overlapped_sequences=overlapped_sequences,
998 )
999
1000 assert len(overlapped_sequences) == 1, overlapped_sequences
1001
1002 s = overlapped_sequences[0]
1003
1004 return s
1005
1006 @classmethod
1007 def test_moves(cls) -> None:
1008 c1 = (1, 2, 3, 4, 5)
1009 c2 = (6, 1)
1010 c3 = (7, 6, 1)
1011 c4 = (3, 4)
1012 c5 = (5, 6, 7)
1013 c6 = (6, 1, 2)
1014 c7 = (8, 7, 6)
1015 chunks0 = {c1, c2, c3, c4, c5, c6, c7}
1016 chunks = set(chunks0)
1017 sequences: list[OverlappedSequences[int]] = []
1018 offsets: dict[tuple[int, ...], int]
1019
1020 overlap_max = Overlap.compute((1, 2, 3), c1)
1021 assert overlap_max == Overlap(offset=0, overlap=3)
1022 pairs: list[DeltasPair[int]] = []
1023
1024 move = ChunksCompressor._add_new_singleton(c1)
1025 move(pairs, chunks, sequences)
1026 offsets = {c1: 0}
1027 data: tuple[int, ...] = c1
1028 assert len(sequences) == 1
1029 s = sequences[0]
1030 assert s.data == data
1031 assert s.offsets == offsets
1032
1033 overlap = Overlap.compute_simple(c2, s.data)
1034 assert overlap == 1
1035 overlap_max = Overlap.compute(c2, s.data)
1036 assert overlap_max.overlap == overlap
1037 move = ChunksCompressor._insert(
1038 chunk=c2, index=0, offset=-overlap, overlap=overlap
1039 )
1040 move(pairs, chunks, sequences)
1041 offsets[c1] = 1
1042 offsets[c2] = 0
1043 data = c2[:-overlap] + data
1044 assert len(sequences) == 1
1045 assert s.data == data
1046 assert s.offsets == offsets
1047
1048 overlap = Overlap.compute_simple(c3, s.data)
1049 assert overlap == 2
1050 overlap_max = Overlap.compute(c3, s.data)
1051 assert overlap_max.overlap == overlap
1052 move = ChunksCompressor._insert(
1053 chunk=c3, index=0, offset=overlap - len(c3), overlap=overlap
1054 )
1055 move(pairs, chunks, sequences)
1056 offsets[c1] += 1
1057 offsets[c2] += 1
1058 offsets[c3] = 0
1059 data = c3[:-overlap] + data
1060 assert len(sequences) == 1
1061 assert s.data == data
1062 assert s.offsets == offsets
1063
1064 overlap_max = Overlap.compute(s.data, c4)
1065 assert overlap_max.overlap == 2, (s.data, c4, overlap_max)
1066 assert overlap_max.offset == 4, (s.data, c4, overlap_max)
1067 move = ChunksCompressor._insert(
1068 chunk=c4, index=0, offset=overlap_max.offset, overlap=overlap_max.overlap
1069 )
1070 move(pairs, chunks, sequences)
1071 offsets[c4] = overlap_max.offset
1072 assert len(sequences) == 1
1073 assert s.data == data
1074 assert s.offsets == offsets
1075
1076 overlap_max = Overlap.compute(s.data, c5)
1077 assert overlap_max.overlap == 1, (s.data, c5, overlap_max)
1078 assert overlap_max.offset == 6, (s.data, c5, overlap_max)
1079 move = ChunksCompressor._insert(
1080 chunk=c5, index=0, offset=overlap_max.offset, overlap=overlap_max.overlap
1081 )
1082 move(pairs, chunks, sequences)
1083 offsets[c5] = overlap_max.offset
1084 data += c5[overlap_max.overlap :]
1085 assert len(sequences) == 1
1086 assert s.data == data, (s.data, data)
1087 assert s.offsets == offsets
1088
1089 overlap_max = Overlap.compute(s.data, c6)
1090 assert overlap_max.overlap == 3, (s.data, c6, overlap_max)
1091 assert overlap_max.offset == 1, (s.data, c6, overlap_max)
1092 move = ChunksCompressor._insert(
1093 chunk=c6, index=0, offset=overlap_max.offset, overlap=overlap_max.overlap
1094 )
1095 move(pairs, chunks, sequences)
1096 offsets[c6] = overlap_max.offset
1097 assert len(sequences) == 1
1098 assert s.data == data, (s.data, data)
1099 assert s.offsets == offsets
1100
1101 overlap = Overlap.compute_simple(c7, s.data)
1102 assert overlap == 2
1103 overlap_max = Overlap.compute(c7, s.data)
1104 assert overlap_max.overlap == overlap
1105 move = ChunksCompressor._insert(
1106 chunk=c7, index=0, offset=overlap - len(c7), overlap=overlap
1107 )
1108 move(pairs, chunks, sequences)
1109 for c in offsets:
1110 offsets[c] += len(c7) - overlap
1111 offsets[c7] = 0
1112 data = c7[:-overlap] + data
1113 assert len(sequences) == 1
1114 assert s.data == data
1115 assert s.offsets == offsets
1116
1117 for c in chunks0:
1118 offset = s.offsets[c]
1119 assert c == s.data[offset : offset + len(c)], (
1120 c,
1121 s.data[offset : offset + len(c)],
1122 )
1123
1124 @classmethod
1125 def test_compression(cls) -> None:
1126 c1 = (1, 2, 3)
1127 c2 = (-1, 0, 1)
1128 c3 = (-2, -1, 0)
1129 c4 = (3, 4, 5)
1130 c5 = (0, 1, 2)
1131 c6 = (2, 3, 5)
1132 chunks = {c1, c2, c3, c4, c5, c6}
1133 compressor = cls(verbose=True)
1134 r = compressor.compress(chunks)
1135 assert set(r.offsets) == {c1, c2, c3, c4, c5, c6}
1136 for c in chunks:
1137 offset = r.offsets[c]
1138 assert c == r.data[offset : offset + len(c)], (
1139 c,
1140 r.data[offset : offset + len(c)],
1141 )
1142
1143
1144 ################################################################################
1145 # Stats
1146 ################################################################################
1147
1148
1149 @dataclass
1150 class Stats:
1151 data_length: int
1152 data_int_size: int
1153 data_overlap: int
1154 offsets1_length: int
1155 offsets1_int_size: int
1156 offsets2_length: int
1157 offsets2_int_size: int
1158
1159 @property
1160 def data_size(self) -> int:
1161 return self.data_length * self.data_int_size
1162
1163 @property
1164 def offsets1_size(self) -> int:
1165 return self.offsets1_length * self.offsets1_int_size
1166
1167 @property
1168 def offsets2_size(self) -> int:
1169 return self.offsets2_length * self.offsets2_int_size
1170
1171 @property
1172 def total(self) -> int:
1173 return self.data_size + self.offsets1_size + self.offsets2_size
1174
1175
1176 def _int_size(ts: Sequence[Iterable[int] | int], offset: int = 0) -> int:
1177 assert ts
1178 if isinstance(ts[0], int):
1179 ts = cast(Sequence[int], ts)
1180 min_delta: int = min(ts)
1181 max_delta: int = max(ts)
1182 else:
1183 ts = cast(Sequence[Iterable[int]], ts)
1184 min_delta = min(min(t) for t in ts)
1185 max_delta = max(max(t) for t in ts)
1186 if offset:
1187 min_delta <<= offset
1188 max_delta <<= offset
1189 for n in range(3, 7):
1190 size: int = 2**n
1191 min_int = -(1 << (size - 1))
1192 max_int = -min_int - 1
1193 if min_int <= min_delta and max_delta <= max_int:
1194 return size
1195 else:
1196 raise ValueError((min_delta, max_delta))
1197
1198
1199 def uint_size(ts: Sequence[int]) -> int:
1200 min_delta = min(ts)
1201 if min_delta < 0:
1202 raise ValueError(min_delta)
1203 max_delta = max(ts)
1204 for n in range(3, 7):
1205 size: int = 2**n
1206 max_int = (1 << size) - 1
1207 if max_delta <= max_int:
1208 return size
1209 else:
1210 raise ValueError((min_delta, max_delta))
1211
1212
1213 ################################################################################
1214 # Compressed array
1215 ################################################################################
1216
1217 I = TypeVar("I", Entry, int)
1218
1219
1220 @dataclass
1221 class CompressedArray(Generic[I]):
1222 data: tuple[I, ...]
1223 offsets: tuple[int, ...]
1224 chunk_offsets: dict[tuple[I, ...], int]
1225
1226 @classmethod
1227 def from_overlapped_sequences(
1228 cls, s: OverlappedSequences[I], groups: Groups[I]
1229 ) -> Self:
1230 offsets = tuple(
1231 s.offsets[d]
1232 for _, d in sorted(
1233 ((g, d0) for d0, gs in groups.items() for g in gs),
1234 key=lambda x: x[0],
1235 )
1236 )
1237 return cls(data=s.data, offsets=offsets, chunk_offsets=s.offsets)
1238
1239 def total_overlap(self) -> int:
1240 return sum(len(d) for d in self.chunk_offsets) - len(self.data)
1241
1242 def stats(self, int_size: Callable[[Sequence[Iterable[int] | int]], int]) -> Stats:
1243 return Stats(
1244 data_length=len(self.data),
1245 data_int_size=int_size(self.data),
1246 data_overlap=self.total_overlap(),
1247 offsets1_length=len(self.offsets),
1248 offsets1_int_size=_int_size(self.offsets),
1249 offsets2_length=0,
1250 offsets2_int_size=0,
1251 )
1252
1253 @staticmethod
1254 def test() -> None:
1255 c1 = (1, 2, 3, 4)
1256 c2 = (2, 3)
1257 c3 = (3, 4, 5)
1258 c4 = (1, 3)
1259 s = OverlappedSequences.from_singleton(c1)
1260 s += c2
1261 s += c3
1262 s += c4
1263 groups: Groups[int] = {c1: [0, 3], c2: [4], c3: [1, 2]}
1264 a = CompressedArray.from_overlapped_sequences(s, groups)
1265 assert a == CompressedArray(
1266 data=s.data, offsets=(0, 2, 2, 0, 1), chunk_offsets=s.offsets
1267 ), a
1268
1269
1270 @dataclass
1271 class ArrayCompressor:
1272 compressor: ChunksCompressor
1273 verbose: bool
1274
1275 def run(self, groups: Groups[I]) -> CompressedArray[I]:
1276 s = self.compressor.compress(groups)
1277 return CompressedArray.from_overlapped_sequences(s, groups)
1278
1279 @classmethod
1280 def compress(
1281 cls,
1282 compressor: ChunksCompressor,
1283 block_size: int,
1284 data: Iterable[I],
1285 default: I,
1286 verbose: bool = False,
1287 ) -> CompressedArray[I]:
1288 groups = generate_groups(block_size=block_size, data=data)
1289 array_compressor = cls(compressor=compressor, verbose=verbose)
1290 return array_compressor.run(groups)
1291
1292 @classmethod
1293 def test_compression(cls) -> None:
1294 c1 = (1, 2, 3)
1295 c2 = (-1, 0, 1)
1296 c3 = (-2, -1, 0)
1297 c4 = (3, 4, 5)
1298 c5 = (0, 1, 2)
1299 c6 = (2, 3, 5)
1300 groups: Groups[int] = {
1301 c1: [0],
1302 c2: [1],
1303 c3: [2],
1304 c4: [3],
1305 c5: [4],
1306 c6: [5],
1307 }
1308 compressor = cls(
1309 compressor=ChunksCompressor(verbose=True),
1310 verbose=True,
1311 )
1312 r = compressor.run(groups)
1313 assert set(r.chunk_offsets) == {c1, c2, c3, c4, c5, c6}
1314 for c, gs in groups.items():
1315 for g in gs:
1316 offset = r.offsets[g]
1317 assert c == r.data[offset : offset + len(c)], (
1318 c,
1319 r.data[offset : offset + len(c)],
1320 )
1321
1322
1323 ################################################################################
1324 # Solutions
1325 ################################################################################
1326
1327
1328 @dataclass
1329 class SimpleSolution(Generic[T]):
1330 data_block_size_log2: int
1331 data_int_size: int
1332 data_overlap: int
1333 data: tuple[T, ...]
1334 offsets1_block_size_log2: int
1335 offsets1_int_size: int
1336 offsets1: tuple[int, ...]
1337 offsets2_int_size: int
1338 offsets2: tuple[int, ...]
1339 max: int
1340 total: int
1341
1342 @classmethod
1343 def zeros(cls) -> Self:
1344 return cls(
1345 data_block_size_log2=0,
1346 data_int_size=0,
1347 data_overlap=0,
1348 data=(),
1349 offsets1_block_size_log2=0,
1350 offsets1_int_size=0,
1351 offsets1=(),
1352 offsets2_int_size=0,
1353 offsets2=(),
1354 max=0,
1355 total=0,
1356 )
1357
1358 @property
1359 def case(self) -> str:
1360 return "both"
1361
1362 @property
1363 def data_size(self) -> int:
1364 return len(self.data) * self.data_int_size
1365
1366 def _convert(self, op: Callable[[X, T], X], x: X) -> X:
1367 mask1 = (1 << self.data_block_size_log2) - 1
1368 mask2 = (1 << self.offsets1_block_size_log2) - 1
1369 cpʹ = x >> self.data_block_size_log2
1370 offset = self.offsets2[cpʹ >> self.offsets1_block_size_log2] + (cpʹ & mask2)
1371 return op(x, self.data[self.offsets1[offset] + (x & mask1)])
1372
1373
1374 class SimpleSolutionCombinedMappings(SimpleSolution[Entry], metaclass=ABCMeta):
1375 @property
1376 @abstractmethod
1377 def type(self) -> str: ...
1378
1379 def to_lower(self, x: X) -> X:
1380 return self._convert(lambda a, e: e.to_lower(a), x)
1381
1382 def to_upper(self, x: X) -> X:
1383 return self._convert(lambda a, e: e.to_upper(a), x)
1384
1385
1386 class SimpleSolutionKeysymsCombinedMappings(SimpleSolutionCombinedMappings):
1387 @property
1388 def type(self) -> str:
1389 return "legacy_keysyms"
1390
1391 def test(self, config: Config) -> bool:
1392 # Check legacy keysyms
1393 r = True
1394 for ks in map(Keysym, range(0, self.max + 1)):
1395 if not (char := xkbcommon.keysym_to_str(ks)):
1396 continue
1397 cp = ord(char)
1398
1399 # Lower
1400 if ks <= self.max:
1401 expected = Entry.to_lower_char(char)
1402 ksʹ = xkbcommon.keysym_from_char(expected)
1403 ksʹʹ = self.to_lower(ks)
1404 got = xkbcommon.keysym_to_str(ksʹʹ)
1405 ok = got == expected
1406 data = (
1407 hex(ks),
1408 hex(cp),
1409 char,
1410 expected,
1411 char.lower(),
1412 hex(ksʹ),
1413 hex(ksʹʹ),
1414 got,
1415 )
1416 if config.check_error:
1417 assert ok, data
1418 elif not ok:
1419 print("Error:", data)
1420 r = False
1421
1422 # Upper
1423 if ks <= self.max:
1424 expected = Entry.to_upper_char(char)
1425 ksʹ = xkbcommon.keysym_from_char(expected)
1426 ksʹʹ = self.to_upper(ks)
1427 got = xkbcommon.keysym_to_str(ksʹʹ)
1428 ok = got == expected
1429 data = (
1430 hex(ks),
1431 hex(cp),
1432 char,
1433 expected,
1434 char.upper(),
1435 hex(ksʹ),
1436 hex(ksʹʹ),
1437 got,
1438 )
1439 if config.check_error:
1440 assert ok, data
1441 elif not ok:
1442 print("Error:", data)
1443 r = False
1444 return r
1445
1446
1447 class SimpleSolutionUnicodeCombinedMappings(SimpleSolutionCombinedMappings):
1448 @property
1449 def type(self) -> str:
1450 return "unicode"
1451
1452 def test(self, config: Config) -> bool:
1453 # Check Unicode keysyms
1454 unicode_min = (
1455 xkbcommon.XKB_KEYSYM_UNICODE_MIN - xkbcommon.XKB_KEYSYM_UNICODE_OFFSET
1456 )
1457 r = True
1458 for cp in map(CodePoint, range(unicode_min, self.max + 1)):
1459 char = chr(cp)
1460 # Lower
1461 if cp <= self.max:
1462 expected = Entry.to_lower_char(char)
1463 got = chr(self.to_lower(cp))
1464 ok = got == expected
1465 dataʹ = (hex(cp), char, expected, char.lower(), got)
1466 if config.check_error:
1467 assert ok, dataʹ
1468 elif not ok:
1469 print("Error:", dataʹ)
1470 r = False
1471 # Upper
1472 if cp <= self.max:
1473 expected = Entry.to_upper_char(char)
1474 got = chr(self.to_upper(cp))
1475 ok = got == expected
1476 dataʹ = (hex(cp), char, expected, char.upper(), got)
1477 if config.check_error:
1478 assert ok, dataʹ
1479 elif not ok:
1480 print("Error:", dataʹ)
1481 r = False
1482 return r
1483
1484
1485 S = TypeVar("S", bound=SimpleSolutionCombinedMappings)
1486
1487
1488 @dataclass
1489 class SeparateLegacyKeysymsAndUnicodeCombinedCaseMappings:
1490 legacy_keysyms: SimpleSolutionKeysymsCombinedMappings
1491 unicode: SimpleSolutionUnicodeCombinedMappings
1492
1493 def __iter__(self) -> Generator[SimpleSolutionCombinedMappings, None, None]:
1494 yield self.legacy_keysyms
1495 yield self.unicode
1496
1497 @property
1498 def total(self) -> int:
1499 return sum(s.total for s in self)
1500
1501 def test(self, config: Config) -> bool:
1502 r = True
1503 if self.legacy_keysyms.data:
1504 r &= self.legacy_keysyms.test(config)
1505 if self.unicode.data:
1506 r &= self.unicode.test(config)
1507 return r
1508
1509 @classmethod
1510 def optimize_groups(
1511 cls,
1512 data: tuple[Entry, ...],
1513 data_max: int,
1514 total0: int,
1515 config: Config,
1516 cls_: type[S],
1517 ) -> S:
1518 chunks_compressor = ChunksCompressor(verbose=config.verbose)
1519 total = total0
1520 max_int_size = sys.maxsize
1521 solution: S | None = None
1522 for k1 in range(1, 9):
1523 block_size1 = 2**k1
1524 if config.verbose:
1525 print("".center(80, "-"))
1526 print(f"{block_size1=} Step 1: Generating 1st compression level…")
1527 ca1 = ArrayCompressor.compress(
1528 compressor=chunks_compressor,
1529 block_size=block_size1,
1530 data=data,
1531 default=Entry.zeros(),
1532 verbose=config.verbose,
1533 )
1534 stats1 = ca1.stats(int_size=lambda x: _int_size(x, offset=2))
1535 if config.verbose:
1536 print("Step 1 done.")
1537 print(
1538 f"{block_size1=} Step 1:",
1539 f"data_overlap={stats1.data_overlap} data_length={stats1.data_length} data_size={stats1.data_size}",
1540 f"total={stats1.total}",
1541 )
1542 current_total = stats1.total
1543 if config.verbose:
1544 print(f"{current_total=}")
1545 if (data_size := stats1.data_size) >= total:
1546 if config.verbose:
1547 print(f"We cannot beat the current solution {data_size=} {total=}")
1548 continue
1549 current_int_size = max(stats1.data_int_size, stats1.offsets1_int_size)
1550 if current_total <= total and (
1551 current_total != total or current_int_size < max_int_size
1552 ):
1553 total = current_total
1554 max_int_size = current_int_size
1555 if config.verbose:
1556 print(f"✨ New best solution: {block_size1=} {total=}")
1557 # TODO: 1st level solution
1558 for k2 in range(7, 1, -1):
1559 block_size2 = 2**k2
1560 if config.verbose:
1561 print(
1562 f"{block_size1=} {block_size2=} Step 2: 2nd level compression… ",
1563 flush=True,
1564 )
1565 ca2 = ArrayCompressor.compress(
1566 compressor=chunks_compressor,
1567 block_size=block_size2,
1568 data=ca1.offsets,
1569 default=0,
1570 verbose=config.verbose,
1571 )
1572 stats2 = ca2.stats(int_size=_int_size)
1573 stats = Stats(
1574 data_length=stats1.data_length,
1575 data_int_size=stats1.data_int_size,
1576 data_overlap=stats1.data_overlap,
1577 offsets1_length=stats2.data_length,
1578 offsets1_int_size=stats2.data_int_size,
1579 offsets2_length=stats2.offsets1_length,
1580 offsets2_int_size=stats2.offsets1_int_size,
1581 )
1582 current_total = stats.total
1583 if config.verbose:
1584 print(
1585 f"{block_size1=} {block_size2=} Step 2:",
1586 f"data_overlap={stats.data_overlap} data_length={stats.data_length} data_size={stats.data_size}",
1587 f"total={stats.total}",
1588 )
1589 print("Step 2 done.", flush=True)
1590 current_int_size = max(
1591 stats.data_int_size,
1592 stats.offsets1_int_size,
1593 stats.offsets2_int_size,
1594 )
1595 if current_total < total or (
1596 current_total == total and current_int_size < max_int_size
1597 ):
1598 total = current_total
1599 max_int_size = current_int_size
1600 if config.verbose:
1601 print(
1602 f"✨ New best solution: {block_size1=} {block_size2=} {total=}"
1603 )
1604 solution = cls_(
1605 data_block_size_log2=k1,
1606 data_int_size=stats.data_int_size,
1607 data=ca1.data,
1608 data_overlap=stats.data_overlap,
1609 offsets1_block_size_log2=k2,
1610 offsets1=ca2.data,
1611 offsets1_int_size=stats.offsets1_int_size,
1612 offsets2=ca2.offsets,
1613 offsets2_int_size=stats.offsets2_int_size,
1614 max=data_max,
1615 total=stats.total,
1616 )
1617 assert solution
1618 if config.verbose:
1619 print(" Finished ".center(80, "*"))
1620 print(
1621 f"Best solution ({solution.case}):",
1622 f"data_block_size={2**solution.data_block_size_log2}",
1623 f"data_overlap={solution.data_overlap}",
1624 f"offsets1_block_size={2**solution.offsets1_block_size_log2}",
1625 f"total={solution.total}",
1626 )
1627 print("Total:", solution.total)
1628 print("".center(80, "*"))
1629 return solution
1630
1631 @classmethod
1632 def optimize(
1633 cls,
1634 config: Config,
1635 path: Path | None = None,
1636 ) -> Self:
1637 print("Computing deltas… ", end="", flush=True)
1638 entries = Entries.compute(config=config, path=path)
1639 print("Done.", flush=True)
1640 keysyms = cls.optimize_groups(
1641 config=config,
1642 data=entries.keysyms,
1643 data_max=entries.keysym_max,
1644 total0=32 * len(entries.keysyms),
1645 cls_=SimpleSolutionKeysymsCombinedMappings,
1646 )
1647 unicode = cls.optimize_groups(
1648 config=config,
1649 data=entries.unicode,
1650 data_max=entries.unicode_max,
1651 total0=32 * len(entries.unicode),
1652 cls_=SimpleSolutionUnicodeCombinedMappings,
1653 )
1654 result = cls(legacy_keysyms=keysyms, unicode=unicode)
1655 print(" Finished ".center(90, "*"))
1656 for s in result:
1657 if s.data:
1658 print(
1659 f"✨ {s.type}:",
1660 f"max: 0x{s.max:0>4x}",
1661 f"data_block_size={2**s.data_block_size_log2}",
1662 f"offsets_block_size={2**s.offsets1_block_size_log2}",
1663 f"data={len(s.data)} (int size: {s.data_int_size})",
1664 f"data_overlap={s.data_overlap}",
1665 f"offsets1={len(s.offsets1)} (uint size: {s.offsets1_int_size})",
1666 f"offsets2={len(s.offsets2)} (uint size: {s.offsets2_int_size})",
1667 f"total={s.total} ({s.total // 8})",
1668 )
1669 print(f"Total: {result.total} ({result.total // 8})")
1670 print("".center(90, "*"))
1671 return result
1672
1673 @classmethod
1674 def generate(cls, root: Path, write: bool, config: Config) -> None:
1675 s = cls.optimize(
1676 config=config,
1677 path=root / "data/keysyms.yaml",
1678 )
1679 s.test(config)
1680 if write:
1681 s.write(root)
1682
1683 MAPPING_TEMPLATE = """\
1684 static const struct CaseMappings {prefix}data[{data_length}] = {{
1685 {data}
1686 }};
1687
1688 static const uint{offsets1_int_size}_t {prefix}offsets1[{offsets1_length}] = {{
1689 {offsets1}
1690 }};
1691
1692 static const uint{offsets2_int_size}_t {prefix}offsets2[{offsets2_length}] = {{
1693 {offsets2}
1694 }};
1695
1696 static inline const struct CaseMappings *
1697 get_{prefix}entry(xkb_keysym_t ks)
1698 {{
1699 return &{prefix}data[{prefix}offsets1[{prefix}offsets2[ks >> {k12}] + ((ks >> {k1}) & 0x{mask2:0>2x})] + (ks & 0x{mask1:0>2x})];
1700 }}\
1701 """
1702
1703 TEMPLATE = """\
1704 // NOTE: This file has been generated automatically by “{python_script}”.
1705 // Do not edit manually!
1706
1707 /*
1708 * Copyright © 2024 Pierre Le Marre
1709 * SPDX-License-Identifier: MIT
1710 */
1711
1712 /* Case mappings for Unicode {unicode_version}
1713 *
1714 {doc}
1715 */
1716
1717 #include "config.h"
1718
1719 #include <stdint.h>
1720 #include <stdbool.h>
1721 #include <string.h>
1722 #include "xkbcommon/xkbcommon.h"
1723 #include "utils.h"
1724 #include "keysym.h"
1725
1726 struct CaseMappings{{
1727 bool lower:1;
1728 bool upper:1;
1729 int{data_int_size}_t offset:{data_int_size_with_offset};
1730 }};
1731
1732 {legacy_keysyms_mappings}
1733
1734 {unicode_mappings}
1735
1736 xkb_keysym_t
1737 xkb_keysym_to_lower(xkb_keysym_t ks)
1738 {{
1739 if (ks <= 0x{max_non_unicode:0>4x}) {{
1740 const struct CaseMappings *m = get_legacy_keysym_entry(ks);
1741 return (m->lower) ? ks + m->offset : ks;
1742 }} else if ({min_unicode} <= ks && ks <= 0x{max_unicode:0>8x}) {{
1743 const struct CaseMappings *m = get_unicode_entry(ks - XKB_KEYSYM_UNICODE_OFFSET);
1744 if (m->lower) {{
1745 ks = ks + m->offset;
1746 return (ks < {min_unicode}) ? ks - XKB_KEYSYM_UNICODE_OFFSET : ks;
1747 }} else {{
1748 return ks;
1749 }}
1750 }} else {{
1751 return ks;
1752 }}
1753 }}
1754
1755 xkb_keysym_t
1756 xkb_keysym_to_upper(xkb_keysym_t ks)
1757 {{
1758 if (ks <= 0x{max_non_unicode:0>4x}) {{
1759 const struct CaseMappings *m = get_legacy_keysym_entry(ks);
1760 return (m->upper) ? ks - m->offset : ks;
1761 }} else if ({min_unicode} <= ks && ks <= 0x{max_unicode:0>8x}) {{
1762 const struct CaseMappings *m = get_unicode_entry(ks - XKB_KEYSYM_UNICODE_OFFSET);
1763 if (m->upper) {{
1764 ks = ks - m->offset;
1765 return (ks < {min_unicode}) ? ks - XKB_KEYSYM_UNICODE_OFFSET : ks;
1766 }} else {{
1767 return ks;
1768 }}
1769 }} else {{
1770 return ks;
1771 }}
1772 }}
1773
1774 bool
1775 xkb_keysym_is_lower(xkb_keysym_t ks)
1776 {{
1777 /* This predicate matches keysyms with their corresponding Unicode code point
1778 * having the Unicode property “Lowercase”.
1779 *
1780 * Here: a keysym is lower case if it has an upper case and no lower case.
1781 * Note: title case letters may have both. Example for U+01F2:
1782 * • U+01F1 DZ: upper case
1783 * • U+01F2 Dz: title case
1784 * • U+01F3 dz: lower case
1785 */
1786 if (ks <= 0x{max_non_unicode:0>4x}) {{
1787 const struct CaseMappings *m = get_legacy_keysym_entry(ks);
1788 return m->upper && !m->lower;
1789 }} else if ({min_unicode} <= ks && ks <= 0x{max_unicode:0>8x}) {{
1790 const struct CaseMappings *m = get_unicode_entry(ks - XKB_KEYSYM_UNICODE_OFFSET);
1791 return m->upper && !m->lower;
1792 }} else {{
1793 return false;
1794 }}
1795 }}
1796
1797 bool
1798 xkb_keysym_is_upper_or_title(xkb_keysym_t ks)
1799 {{
1800 /* This predicate matches keysyms with their corresponding Unicode code point
1801 * having the Unicode properties “Uppercase” or General Category “Lt”.
1802 *
1803 * Here: a keysym is upper case or title case if it has a lower case. */
1804 if (ks <= 0x{max_non_unicode:0>4x}) {{
1805 return get_legacy_keysym_entry(ks)->lower;
1806 }} else if ({min_unicode} <= ks && ks <= 0x{max_unicode:0>8x}) {{
1807 return get_unicode_entry(ks - XKB_KEYSYM_UNICODE_OFFSET)->lower;
1808 }} else {{
1809 return false;
1810 }}
1811 }}
1812 """
1813
1814 @staticmethod
1815 def myHex(n: int, max_hex_length: int) -> str:
1816 return (
1817 f"""{"-" if n < 0 else " "}0x{hex(abs(n))[2:].rjust(max_hex_length, "0")}"""
1818 )
1819
1820 @classmethod
1821 def make_char_case_mappings(cls, e: Entry, max_hex_length: int) -> str:
1822 # If the entry has both lower and upper mappings, they must be equal.
1823 if e.lower and e.upper and e.lower != e.upper:
1824 raise ValueError(e)
1825 has_lower = e.is_upper or bool(e.lower)
1826 has_upper = e.is_lower or bool(e.upper)
1827 return f"{{{int(has_lower)}, {int(has_upper)},{cls.myHex(e.lower or e.upper, max_hex_length)}}}"
1828
1829 def generate_mapping(self, prefix: str, sol: SimpleSolutionCombinedMappings) -> str:
1830 if not sol.offsets1_block_size_log2:
1831 raise ValueError(f"generate_mapping: {prefix}")
1832 max_data = max(max(abs(e.lower), abs(e.upper)) for e in sol.data)
1833 max_hex_length = 1 + (int(math.log2(max_data)) >> 2)
1834 return self.MAPPING_TEMPLATE.format(
1835 prefix=prefix,
1836 data_length=len(sol.data),
1837 data=",\n ".join(
1838 ", ".join(
1839 "".join(self.make_char_case_mappings(x, max_hex_length)) for x in xs
1840 )
1841 for xs in itertools.batched(sol.data, 4)
1842 ),
1843 offsets1_int_size=sol.offsets1_int_size,
1844 offsets1_length=len(sol.offsets1),
1845 offsets1=",\n ".join(
1846 ", ".join(f"0x{x:0>4x}" for x in xs)
1847 for xs in itertools.batched(sol.offsets1, 10)
1848 ),
1849 offsets2_int_size=sol.offsets2_int_size,
1850 offsets2_length=len(sol.offsets2),
1851 offsets2=",\n ".join(
1852 ", ".join(f"0x{x:0>4x}" for x in xs)
1853 for xs in itertools.batched(sol.offsets2, 10)
1854 ),
1855 k1=sol.data_block_size_log2,
1856 k2=sol.offsets1_block_size_log2,
1857 k12=sol.data_block_size_log2 + sol.offsets1_block_size_log2,
1858 mask1=(1 << sol.data_block_size_log2) - 1,
1859 mask2=(1 << sol.offsets1_block_size_log2) - 1,
1860 )
1861
1862 def write(self, root: Path) -> None:
1863 path = root / "src/keysym-case-mappings.c"
1864 keysyms = self.generate_mapping("legacy_keysym_", self.legacy_keysyms)
1865 unicode = self.generate_mapping("unicode_", self.unicode)
1866 assert self.legacy_keysyms.data_int_size == self.unicode.data_int_size
1867 doc = textwrap.indent(
1868 textwrap.indent(__doc__.strip(), prefix=" "),
1869 prefix=" *",
1870 predicate=lambda _: True,
1871 )
1872 content = self.TEMPLATE.format(
1873 python_script=Path(__file__).name,
1874 unicode_version=icu.UNICODE_VERSION,
1875 doc=doc,
1876 data_int_size=self.legacy_keysyms.data_int_size,
1877 data_int_size_with_offset=self.legacy_keysyms.data_int_size - 2,
1878 legacy_keysyms_mappings=keysyms,
1879 unicode_mappings=unicode,
1880 max_non_unicode=self.legacy_keysyms.max,
1881 min_unicode="XKB_KEYSYM_UNICODE_MIN",
1882 max_unicode=XKBCOMMON.XKB_KEYSYM_UNICODE_OFFSET + self.unicode.max,
1883 keysym_unicode_offset="XKB_KEYSYM_UNICODE_OFFSET",
1884 )
1885 with path.open("wt", encoding="utf-8") as fd:
1886 fd.write(content)
1887
1888 unicode_version_array = ", ".join(
1889 (icu.UNICODE_VERSION + ".0.0.0").split(".")[:4]
1890 )
1891 path = root / "src/keysym.h.jinja"
1892 with path.open("rt", encoding="utf-8") as fd:
1893 content = fd.read()
1894 pattern: re.Pattern[str] = re.compile(
1895 r"^(#define\s+XKB_KEYSYM_UNICODE_VERSION\s+\{\s*)(?:\d+(?:,\s*\d+)*)*(\s*\})",
1896 re.MULTILINE,
1897 )
1898
1899 def replace(m: re.Match[str]) -> str:
1900 return f"{m.group(1)}{unicode_version_array}{m.group(2)}"
1901
1902 content = pattern.sub(replace, content)
1903 with path.open("wt", encoding="utf-8") as fd:
1904 fd.write(content)
1905
1906
1907 ################################################################################
1908 # Strategy
1909 ################################################################################
1910
1911
1912 @unique
1913 class Strategy(Enum):
1914 Default = SeparateLegacyKeysymsAndUnicodeCombinedCaseMappings
1915
1916 def __str__(self) -> str:
1917 return self.value.__name__
1918
1919 @classmethod
1920 def parse(cls, str: str) -> Self:
1921 for s in cls:
1922 if s.name == str:
1923 return s
1924 else:
1925 raise ValueError(str)
1926
1927 @classmethod
1928 def run(
1929 cls, root: Path, config: Config, strategies: list[Self], write: bool
1930 ) -> None:
1931 # FIXME: more generic type
1932 results: list[SeparateLegacyKeysymsAndUnicodeCombinedCaseMappings] = []
1933 best_total = math.inf
1934 best_solution: SeparateLegacyKeysymsAndUnicodeCombinedCaseMappings | None = None
1935 for strategy in strategies:
1936 print(f" Optimizing using {strategy.name} ".center(90, "="))
1937 sol = strategy.value.optimize(
1938 config=config, path=root / "data/keysyms.yaml"
1939 )
1940 sol.test(config)
1941 results.append(sol)
1942 if sol.total < best_total:
1943 best_total = sol.total
1944 best_solution = sol
1945 assert best_solution
1946 assert best_solution
1947 for strategy, sol in zip(strategies, results):
1948 print(
1949 f"{strategy.name}: {sol.total} ({sol.total // 8})",
1950 "✨✨✨" if sol is best_solution else "",
1951 )
1952 best_solution.test(config)
1953 if write:
1954 best_solution.write(root)
1955 cls.write_tests(root)
1956
1957 @classmethod
1958 def write_tests(cls, root: Path) -> None:
1959 # Configure Jinja
1960 template_loader = jinja2.FileSystemLoader(root, encoding="utf-8")
1961 jinja_env = jinja2.Environment(
1962 loader=template_loader,
1963 keep_trailing_newline=True,
1964 trim_blocks=True,
1965 lstrip_blocks=True,
1966 )
1967
1968 def code_point_name_constant(c: str, padding: int = 0) -> str:
1969 if not (name := unicodedata.name(c)):
1970 raise ValueError(f"No Unicode name for code point: U+{ord(c):0>4X}")
1971 name = name.replace("-", "_").replace(" ", "_").upper()
1972 return name.ljust(padding)
1973
1974 jinja_env.filters["code_point"] = lambda c: f"0x{ord(c):0>4x}"
1975 jinja_env.filters["code_point_name_constant"] = code_point_name_constant
1976 path = root / "test/keysym-case-mapping.h"
1977 template_path = path.with_suffix(f"{path.suffix}.jinja")
1978 template = jinja_env.get_template(str(template_path.relative_to(root)))
1979 with path.open("wt", encoding="utf-8") as fd:
1980 fd.writelines(
1981 template.generate(
1982 upper_exceptions=Entry.to_upper_exceptions,
1983 script=SCRIPT.relative_to(root),
1984 )
1985 )
1986
1987
1988 def import_from_path(module_name: str, file_path: Path):
1989 spec = importlib.util.spec_from_file_location(module_name, file_path)
1990 module = importlib.util.module_from_spec(spec)
1991 sys.modules[module_name] = module
1992 spec.loader.exec_module(module)
1993 return module
1994
1995
1996 ################################################################################
1997 # Main
1998 ################################################################################
1999
2000
2001 if __name__ == "__main__":
2002 # Root of the project
2003 ROOT = Path(__file__).parent.parent
2004
2005 # Parse commands
2006 parser = argparse.ArgumentParser(description="Generate keysyms case mapping files")
2007 parser.add_argument(
2008 "--root",
2009 type=Path,
2010 default=ROOT,
2011 help="Path to the root of the project (default: %(default)s)",
2012 )
2013 parser.add_argument(
2014 "--ucd",
2015 type=Path,
2016 help="Path to UCD directory to replace ICU",
2017 required=icu is None,
2018 )
2019 parser.add_argument(
2020 "--ucd-version",
2021 type=str,
2022 help="Version of the UCD",
2023 required=icu is None,
2024 )
2025 parser.add_argument(
2026 "--strategy",
2027 type=Strategy.parse,
2028 default=list(Strategy),
2029 nargs="+",
2030 choices=Strategy,
2031 help="Strategy (default: %(default)s)",
2032 dest="strategies",
2033 )
2034 parser.add_argument(
2035 "--dry",
2036 action="store_true",
2037 help="Do not write (default: %(default)s)",
2038 )
2039 parser.add_argument(
2040 "--verbose",
2041 action="store_true",
2042 help="Verbose (default: %(default)s)",
2043 )
2044 parser.add_argument(
2045 "--no-check",
2046 action="store_true",
2047 help="Do not check errors (default: %(default)s)",
2048 )
2049
2050 args = parser.parse_args()
2051
2052 if ucd_path := args.ucd:
2053 # Use a local UCD instead of ICU.
2054 # Useful when ICU is not available or when it does not support the latest
2055 # Unicode version.
2056 # Data are available at: https://www.unicode.org/Public/<UNICODE_VERSION>/ucd/
2057 icu = import_from_path(
2058 module_name="icu", file_path=Path(__file__).with_stem("ucd")
2059 )
2060 if ucd_version := args.ucd_version:
2061 icu.UNICODE_VERSION = ucd_version
2062 icu.Char = icu.DB.parse_ucd(ucd_path)
2063
2064 config = Config(
2065 check_error=not args.no_check,
2066 verbose=args.verbose,
2067 )
2068 Strategy.run(
2069 root=args.root, config=config, write=not args.dry, strategies=args.strategies
2070 )