File: update-keysyms-case-mappings.py

package info (click to toggle)
libxkbcommon 1.13.1-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 8,344 kB
  • sloc: ansic: 57,807; xml: 8,905; python: 7,451; yacc: 913; sh: 253; makefile: 23
file content (2070 lines) | stat: -rwxr-xr-x 69,986 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
#!/usr/bin/env python3

# This script creates the keysym case mappings in `src/keysym-case-mappings.c`.
#
# Inspired from: https://github.com/apankrat/notes/blob/3c551cb028595fd34046c5761fd12d1692576003/fast-case-conversion/README.md

# NOTE: the following docstring is also used to document the resulting C file.

"""
There are two kinds of keysyms to consider:
• Legacy keysyms: their case mappings is located at `data/keysyms.yaml`.
• Unicode keysyms: their case mappings come from the ICU library.

These mappings would create huge lookup tables if done naively. Fortunately,
we can observe that if we compute only the *difference* between a keysym and
its corresponding case mapping, there are a lot of repetitions that can be
efficiently compressed.

The idea for the compression is, for each kind of keysyms:
1. Compute the deltas between the keysyms and their case mappings.
2. Split the delta array in chunks of a given size.
3. Rearrange the order of the chunks in order to optimize consecutive
   chunks overlap.
4. Create a data table with the reordered chunks and an index table that
   maps the original chunk index to its offset in the data table.

Trivial example (chunk size: 4, from step 2):

[1, 2, 3, 4, 2, 3, 4, 5, 0, 1, 2, 3]          # source data
-> [[1, 2, 3, 4], [2, 3, 4, 5], [0, 1, 2, 3]] # make chunks
-> [[0, 1, 2, 3], [1, 2, 3, 4], [2, 3, 4, 5]] # rearrange to have best overlaps
-> {data: [0, 1, 2, 3, 4, 5], offsets: [1, 2, 0]} # overlap chunks & compute
                                                  # their offsets

Then we can retrieve the data from the original array at index i with the
following formula:

    mask = (1 << chunk_size) - 1;
    original[i] = data[offsets[i >> chunk_size] + (i & mask)];

Since the index array is itself quite repetitive with the real data, we apply
the compression a second time to the offsets table.

The complete algorithm optimizes the chunk sizes for both arrays in order to
get the lowest total data size.

There are 6 resulting arrays, 3 for each kind of keysyms:
1. The data array. Each item is either:
   • 0, if the keysym is not cased.
   • A delta to lower case.
   • A delta to upper case.
   • For some special cases, there are both a lower *and* an upper case
     mapping. The delta is identical in both cases.
2. The 1st offsets array, that provides offsets into the data array.
3. The 2nd offsets array, that provides offsets into the 1st index array.

Finally, given the chunks sizes `cs_data` and `cs_offsets`:
1. We compute the corresponding masks:
   • `mask_data = (1 << cs_data) - 1` and
   • `mask_offsets = (1 << cs_offsets) - 1`.
2. We can retrieve the case mapping of a keysyms `ks` with the following
   formula:

    data[
        offsets1[
            offsets2[ks >> (cs_data + cs_offsets)] +
            ((ks >> cs_data) & mask_offsets)
        ] +
        (ks & mask_data)
    ];
"""

from __future__ import annotations

import argparse
import ctypes
import itertools
import math
import os
import re
import sys
import textwrap
from abc import ABCMeta, abstractmethod
from collections import defaultdict
from collections.abc import Callable
from ctypes.util import find_library
from dataclasses import dataclass
from enum import Enum, unique
from functools import cache, reduce
import importlib.util
from pathlib import Path
from typing import (
    Any,
    ClassVar,
    Generator,
    Generic,
    Iterable,
    NewType,
    Protocol,
    Self,
    Sequence,
    TypeAlias,
    TypeVar,
    cast,
)
import unicodedata

import jinja2
import yaml

assert sys.version_info >= (3, 12)

try:
    import icu

    c = icu.Locale.createFromName("C")
    icu.Locale.setDefault(c)
except ImportError:
    icu = None

SCRIPT = Path(__file__)
CodePoint = NewType("CodePoint", int)
Keysym = NewType("Keysym", int)
KeysymName = NewType("KeysymName", str)

T = TypeVar("T")
X = TypeVar("X", int, CodePoint, Keysym)

################################################################################
# Configuration
################################################################################


@dataclass
class Config:
    check_error: bool
    verbose: bool


################################################################################
# XKBCOMMON
################################################################################


class XKBCOMMON:
    XKB_KEYSYM_MIN = Keysym(0)
    XKB_KEYSYM_MAX = Keysym(0x1FFFFFFF)
    XKB_KEYSYM_MIN_EXPLICIT = Keysym(0x00000000)
    XKB_KEYSYM_MAX_EXPLICIT = Keysym(0x1008FFB8)
    XKB_KEYSYM_UNICODE_OFFSET = Keysym(0x01000000)
    XKB_KEYSYM_UNICODE_MIN = Keysym(0x01000100)
    XKB_KEYSYM_UNICODE_MAX = Keysym(0x0110FFFF)
    XKB_KEY_NoSymbol = Keysym(0)
    xkb_keysym_t = ctypes.c_uint32
    XKB_KEYSYM_NO_FLAGS = 0

    def __init__(self) -> None:
        self._xkbcommon_path = os.environ.get("XKBCOMMON_LIB_PATH")

        if self._xkbcommon_path:
            self._xkbcommon_path = str(Path(self._xkbcommon_path).resolve())
            self._lib = ctypes.cdll.LoadLibrary(self._xkbcommon_path)
        else:
            self._xkbcommon_path = find_library("xkbcommon")
            if self._xkbcommon_path:
                self._lib = ctypes.cdll.LoadLibrary(self._xkbcommon_path)
            else:
                raise OSError("Cannot load libxbcommon")

        self._lib.xkb_keysym_to_lower.argtypes = [self.xkb_keysym_t]
        self._lib.xkb_keysym_to_lower.restype = self.xkb_keysym_t

        self._lib.xkb_keysym_to_upper.argtypes = [self.xkb_keysym_t]
        self._lib.xkb_keysym_to_upper.restype = self.xkb_keysym_t

        self._lib.xkb_keysym_to_utf8.argtypes = [
            self.xkb_keysym_t,
            ctypes.c_char_p,
            ctypes.c_size_t,
        ]
        self._lib.xkb_keysym_to_utf8.restype = ctypes.c_int

        self._lib.xkb_keysym_to_utf32.argtypes = [self.xkb_keysym_t]
        self._lib.xkb_keysym_to_utf32.restype = ctypes.c_uint32

        self._lib.xkb_keysym_from_name.argtypes = [ctypes.c_char_p, ctypes.c_int]
        self._lib.xkb_keysym_from_name.restype = self.xkb_keysym_t

        self._lib.xkb_utf32_to_keysym.argtypes = [ctypes.c_uint32]
        self._lib.xkb_utf32_to_keysym.restype = self.xkb_keysym_t

    def keysym_from_name(self, keysym_name: KeysymName) -> Keysym:
        return self._lib.xkb_keysym_from_name(
            keysym_name.encode("utf-8"), self.XKB_KEYSYM_NO_FLAGS
        )

    def keysym_from_cp(self, cp: CodePoint) -> Keysym:
        return self._lib.xkb_utf32_to_keysym(cp)

    def keysym_from_char(self, char: str) -> Keysym:
        return self._lib.xkb_utf32_to_keysym(ord(char))

    def keysym_to_lower(self, keysym: Keysym) -> Keysym:
        return self._lib.xkb_keysym_to_lower(keysym)

    def keysym_to_upper(self, keysym: Keysym) -> Keysym:
        return self._lib.xkb_keysym_to_upper(keysym)

    def keysym_to_str(self, keysym: Keysym) -> str:
        buf_len = 7
        buf = ctypes.create_string_buffer(buf_len)
        n = self._lib.xkb_keysym_to_utf8(keysym, buf, ctypes.c_size_t(buf_len))
        if n < 0:
            raise ValueError(f"Unsupported keysym: 0x{keysym:0>4X})")
        elif n >= buf_len:
            raise ValueError(f"Buffer is not big enough: expected at least {n}.")
        else:
            return buf.value.decode("utf-8")

    def keysym_code_point(self, keysym: Keysym) -> int:
        return self._lib.xkb_keysym_to_utf32(keysym)

    def iter_case_mappings(self, unicode: bool) -> Iterable[tuple[Keysym, Entry]]:
        for keysym in map(
            Keysym,
            range(self.XKB_KEYSYM_MIN_EXPLICIT, self.XKB_KEYSYM_MAX_EXPLICIT + 1),
        ):
            if (
                not unicode
                and self.XKB_KEYSYM_UNICODE_OFFSET
                <= keysym
                <= self.XKB_KEYSYM_UNICODE_MAX
            ) or not self.keysym_code_point(keysym):
                continue
            cp = self.keysym_code_point(keysym)
            yield (
                keysym,
                Entry(
                    lower=self.keysym_to_lower(keysym) - keysym,
                    upper=keysym - self.keysym_to_upper(keysym),
                    # FIXME: should use xkbcommon API, but it’s not exposed
                    is_lower=icu.Char.isULowercase(cp),
                    is_upper=icu.Char.isUUppercase(cp) or icu.istitle(cp),
                ),
            )

    def case_mappings(self, unicode: bool) -> tuple[Entry, ...]:
        mappings = dict(self.iter_case_mappings(unicode))
        keysym_max = max(mappings)
        return tuple(
            mappings.get(cast(Keysym, ks), Entry.zeros())
            for ks in range(0, keysym_max + 1)
        )


xkbcommon = XKBCOMMON()


def load_keysyms(path: Path, unicode: bool) -> tuple[Entry, ...]:
    with path.open("rt", encoding="utf-8") as fd:
        keysyms = {
            ks: entry
            for ks, data in yaml.safe_load(fd).items()
            if unicode
            or (
                ks < XKBCOMMON.XKB_KEYSYM_UNICODE_MIN
                or ks > XKBCOMMON.XKB_KEYSYM_UNICODE_MAX
            )
            if data.get("code point")
            if (
                entry := Entry(
                    data.get("lower", ks) - ks,
                    ks - data.get("upper", ks),
                    is_lower=icu.Char.isULowercase(data.get("code point")),
                    is_upper=icu.Char.isUUppercase(data.get("code point"))
                    or icu.Char.istitle(data.get("code point")),
                )
            )
        }
        # Check either non-cased, upper or lower
        errors = []
        for ks, e in keysyms.items():
            if e.lower and e.upper and e.lower != e.upper:
                errors.append((ks, e))
        if errors:
            raise ValueError(errors)
        keysym_max = max(keysyms)
        return tuple(keysyms.get(ks, Entry.zeros()) for ks in range(0, keysym_max + 1))


################################################################################
# Case mapping
################################################################################


@dataclass(frozen=True, order=True)
class Entry:
    """
    Case mapping deltas for a character or a keysym.
    """

    lower: int
    upper: int
    is_lower: bool
    is_upper: bool
    # [NOTE] Exceptions must be documented in `xkbcommon.h`.
    to_upper_exceptions: ClassVar[dict[str, str]] = {"ß": "ẞ"}
    "Upper mappings exceptions"

    @classmethod
    def zeros(cls) -> Self:
        return cls(lower=0, upper=0, is_lower=False, is_upper=False)

    def __bool__(self) -> bool:
        return any(self) or self.is_lower or self.is_upper

    def __str__(self) -> str:
        return str(tuple(self))

    def __iter__(self) -> Generator[int, None, None]:
        yield self.lower
        yield self.upper

    @classmethod
    def from_code_point(cls, cp: CodePoint) -> Self:
        return cls(
            lower=cls.lower_delta(cp),
            upper=cls.upper_delta(cp),
            is_lower=icu.Char.isULowercase(cp),
            is_upper=icu.Char.isUUppercase(cp) or icu.Char.istitle(cp),
        )

    @classmethod
    def lower_delta(cls, cp: CodePoint) -> int:
        return cls.to_lower_cp(cp) - cp

    @classmethod
    def upper_delta(cls, cp: CodePoint) -> int:
        return cp - cls.to_upper_cp(cp)

    @classmethod
    def to_upper_cp(cls, cp: CodePoint) -> CodePoint:
        if upper := cls.to_upper_exceptions.get(chr(cp)):
            return ord(upper)
        return icu.Char.toupper(cp)

    @staticmethod
    def to_lower_cp(cp: CodePoint) -> CodePoint:
        return icu.Char.tolower(cp)

    @classmethod
    def to_upper_char(cls, char: str) -> str:
        if upper := cls.to_upper_exceptions.get(char):
            return upper
        return icu.Char.toupper(char)

    @staticmethod
    def to_lower_char(char: str) -> str:
        return icu.Char.tolower(char)

    def to_lower(self, x: X) -> X:
        return x.__class__(x + self.lower)

    def to_upper(self, x: X) -> X:
        return x.__class__(x - self.upper)


@dataclass
class Deltas(Generic[T]):
    """
    Sequences of case mappings deltas
    """

    keysyms: tuple[T, ...]
    keysym_max: Keysym
    "Maximum keysym with a case mapping"
    unicode: tuple[T, ...]
    unicode_max: CodePoint
    "Maximum Unicode code point with a case mapping"


class Entries(Deltas[Entry]):
    @classmethod
    def compute(
        cls,
        config: Config,
        path: Path | None = None,
    ) -> Self:
        # Keysyms
        if path:
            keysyms_deltas = load_keysyms(path, unicode=False)
        else:
            keysyms_deltas = xkbcommon.case_mappings(True)
        max_keysym = max(Keysym(ks) for ks, e in enumerate(keysyms_deltas) if e)
        assert max_keysym
        keysyms_deltas = keysyms_deltas[: max_keysym + 1]

        # Unicode
        unicode_deltas = tuple(
            Entry.from_code_point(CodePoint(cp)) for cp in range(0, sys.maxunicode + 1)
        )
        max_unicode = max((CodePoint(cp) for cp, d in enumerate(unicode_deltas) if d))
        assert max_unicode
        unicode_deltas = unicode_deltas[: max_unicode + 1]
        errors = []
        for n, e1 in enumerate(unicode_deltas):
            cp = CodePoint(n)
            # Check with legacy keysyms
            keysym = xkbcommon.keysym_from_cp(cp)
            if keysym <= max_keysym:
                e2 = keysyms_deltas[keysym]
                if e1 or e2:
                    cls.check(
                        config,
                        "lower",
                        cp,
                        e1.to_lower(cp),
                        keysym,
                        e2.to_lower(keysym),
                    )
                    cls.check(
                        config,
                        "upper",
                        cp,
                        e1.to_upper(cp),
                        keysym,
                        e2.to_upper(keysym),
                    )
            # Check character has either
            # • No case mapping
            # • Lower or an upper mapping
            # • Both, with the same delta
            if e1.lower and e1.upper and e1.lower != e1.upper:
                errors.append((cp, e1))
        if errors:
            raise ValueError(errors)
        return cls(
            keysyms=keysyms_deltas,
            keysym_max=max_keysym,
            unicode=unicode_deltas,
            unicode_max=max_unicode,
        )

    @classmethod
    def check(
        cls,
        config: Config,
        casing: str,
        cp: CodePoint,
        cpʹ: CodePoint,
        keysym: Keysym,
        keysymʹ: Keysym,
    ) -> None:
        char = chr(cp)
        expected = chr(cpʹ)
        got = xkbcommon.keysym_to_str(keysymʹ)
        data = (
            hex(keysym),
            hex(cp),
            char,
            hex(keysymʹ),
            got,
            expected,
        )
        if config.check_error:
            assert got == expected, data
        elif got != expected:
            print(
                f"Error: legacy keysym 0x{keysym:4>x} has incorrect {casing} mapping:",
                data,
            )

    @property
    def lower(self) -> Deltas[int]:
        return Deltas(
            keysyms=tuple(e.lower for e in self.keysyms),
            keysym_max=self.keysym_max,
            unicode=tuple(e.lower for e in self.unicode),
            unicode_max=self.unicode_max,
        )

    @property
    def upper(self) -> Deltas[int]:
        return Deltas(
            keysyms=tuple(e.upper for e in self.keysyms),
            keysym_max=self.keysym_max,
            unicode=tuple(e.upper for e in self.unicode),
            unicode_max=self.unicode_max,
        )


@dataclass(frozen=True)
class DeltasPair(Generic[T]):
    d1: tuple[T, ...]
    d2: tuple[T, ...]
    overlap: int

    def __contains__(self, x: tuple[T, ...]) -> bool:
        return (x == self.d1) or (x == self.d2)

    @classmethod
    def compute_pairs_overlaps(
        cls, deltas: Iterable[tuple[T, ...]]
    ) -> Generator[DeltasPair[T], None, None]:
        for d1, d2 in itertools.combinations(deltas, 2):
            if overlap := Overlap.compute_simple(d1, d2):
                yield DeltasPair(d1, d2, overlap)
            if overlap := Overlap.compute_simple(d2, d1):
                yield DeltasPair(d2, d1, overlap)

    def remove_from_pairs(
        self, pairs: list[DeltasPair[T]]
    ) -> Generator[DeltasPair[T], None, None]:
        for p in pairs:
            if p.d1 not in self and p.d2 not in self:
                yield p

    @classmethod
    def remove_chunk_from_pairs(
        cls, pairs: Iterable[DeltasPair[T]], chunk: tuple[T, ...]
    ) -> Generator[DeltasPair[T], None, None]:
        for p in pairs:
            if chunk not in p:
                yield p

    @classmethod
    def compute_best_pair(cls, pairs: Iterable[DeltasPair[T]]) -> DeltasPair[T]:
        return max(pairs, key=lambda p: p.overlap)


################################################################################
# Overlap
################################################################################


@dataclass
class Overlap:
    "Overlap of two sequences"

    offset: int
    overlap: int

    @staticmethod
    @cache
    def compute_simple(s1: Sequence[T], s2: Sequence[T]) -> int:
        return max((n for n in range(0, len(s1) + 1) if s1[-n:] == s2[:n]), default=0)

    @classmethod
    @cache
    def compute(cls, s1: Sequence[T], s2: Sequence[T]) -> Self:
        l1 = len(s1)
        l2 = len(s2)
        return max(
            (
                cls(offset=start, overlap=overlap)
                for start in range(0, l1)
                if (end := min(start + l2, l1))
                and (overlap := end - start)
                and s1[start:end] == s2[:overlap]
            ),
            key=lambda x: x.overlap,
            default=cls(offset=l1, overlap=0),
        )

    @classmethod
    def test(cls) -> None:
        c1 = (1, 2, 3, 4)
        c2 = (2, 3)
        c3 = (3, 2, 1)
        c4 = (3, 4, 5)
        c5 = (1, 2, 4)
        overlap = cls.compute(c1, c2)
        assert overlap == cls(1, 2)
        overlap = cls.compute(c3, c1)
        assert overlap == cls(2, 1)
        overlap = cls.compute(c1, c4)
        assert overlap == cls(2, 2)
        overlap = cls.compute(c1, c5)
        assert overlap == cls(4, 0), overlap


################################################################################
# Groups
################################################################################

Groups: TypeAlias = dict[tuple[T, ...], list[int]]


def generate_groups(block_size: int, data: Iterable[T]) -> Groups[T]:
    groups: defaultdict[tuple[T, ...], list[int]] = defaultdict(list)
    for n, d in enumerate(itertools.batched(data, block_size)):
        groups[d].append(n)
    return groups


################################################################################
# Overlapped Sequences
################################################################################


@dataclass
class OverlappedSequences(Generic[T]):
    data: tuple[T, ...]
    offsets: dict[tuple[T, ...], int]

    def __bool__(self) -> bool:
        return bool(self.data)

    def __hash__(self) -> int:
        return hash((self.data, tuple(self.offsets)))

    def __add__(self, x: Any) -> Self:
        if isinstance(x, self.__class__):
            return self.extend(x)
        elif isinstance(x, tuple):
            return self.add(x)
        else:
            return NotImplemented

    def __iadd__(self, x: Any) -> Self:
        if isinstance(x, self.__class__):
            overlap = Overlap.compute(self.data, x.data)
            self.data = (
                self.data
                if overlap.offset <= len(self.data) - len(x.data)
                else self.data + x.data[overlap.overlap :]
            )
            for c, o in x.offsets.items():
                self.offsets[c] = overlap.offset + o
            return self
        elif isinstance(x, tuple):
            overlap = Overlap.compute(self.data, x)
            self.data = (
                self.data
                if overlap.offset <= len(self.data) - len(x)
                else self.data + x[overlap.overlap :]
            )
            self.offsets[x] = overlap.offset
            return self
        else:
            return NotImplemented

    @classmethod
    def from_singleton(cls, chunk: tuple[T, ...]) -> Self:
        return cls(data=chunk, offsets={chunk: 0})

    @classmethod
    def from_pair(cls, pair: DeltasPair[T]) -> Self:
        return cls(
            data=pair.d1 + pair.d2[pair.overlap :],
            offsets={
                pair.d1: 0,
                pair.d2: len(pair.d1) - pair.overlap,
            },
        )

    @classmethod
    def from_iterable(cls, ts: Iterable[tuple[T, ...]]) -> Self:
        return reduce(lambda s, t: s.add(t), ts, cls((), {}))

    @classmethod
    def from_ordered_iterable(cls, ts: Iterable[tuple[T, ...]]) -> Self:
        return reduce(lambda s, t: s.append(t), ts, cls((), {}))

    def extend(self, s: Self) -> Self:
        overlap: Overlap
        s1: Self
        s2: Self
        overlap, s1, s2 = max(
            (
                (Overlap.compute(self.data, s.data), self, s),
                (Overlap.compute(s.data, self.data), s, self),
            ),
            key=lambda x: x[0].overlap,
        )

        data = (
            s1.data
            if overlap.offset <= len(s1.data) - len(s2.data)
            else s1.data + s2.data[overlap.overlap :]
        )
        offsets = dict(s1.offsets)
        for c, o in s2.offsets.items():
            offsets[c] = overlap.offset + o
        return self.__class__(data=data, offsets=offsets)

    def add(self, chunk: tuple[T, ...]) -> Self:
        return self.extend(self.from_singleton(chunk))

    def append(self, chunk: tuple[T, ...]) -> Self:
        overlap = Overlap.compute(self.data, chunk)
        self.data = (
            self.data
            if overlap.offset <= len(self.data) - len(chunk)
            else self.data + chunk[overlap.overlap :]
        )
        self.offsets[chunk] = overlap.offset
        return self

    def insert(self, offset: int, overlap: int, chunk: tuple[T, ...]) -> None:
        chunk_length = len(chunk)
        if offset < 0:
            self.data = chunk[:-overlap] + self.data
            assert chunk == self.data[:chunk_length]
            for c in self.offsets:
                self.offsets[c] += -offset
            self.offsets[chunk] = 0
        elif offset <= len(self.data) - len(chunk):
            assert self.data[offset : offset + chunk_length] == chunk
            self.offsets[chunk] = offset
        else:
            self.data += chunk[overlap:]
            assert self.data[offset:] == chunk
            self.offsets[chunk] = offset

    def merge(self, offset: int, overlap: int, s: OverlappedSequences[T]) -> None:
        s_length = len(s.data)
        if offset < 0:
            self.data = s.data[:-overlap] + self.data
            assert s.data == self.data[:s_length]
            for c in self.offsets:
                self.offsets[c] += -offset
            self.offsets.update(s.offsets)
        elif offset <= len(self.data) - len(s.data):
            assert self.data[offset : offset + s_length] == s.data
            for c, offset2 in s.offsets.items():
                self.offsets[c] = offset2 + offset
        else:
            self.data += s.data[overlap:]
            assert self.data[offset:] == s.data
            for c, offset2 in s.offsets.items():
                self.offsets[c] = offset2 + offset

    def flatten_iter(self) -> Generator[tuple[T, ...], None, None]:
        for t, _ in sorted(self.offsets.items(), key=lambda x: x[1]):
            yield t

    def flatten(self) -> list[tuple[T, ...]]:
        return list(self.flatten_iter())

    def flatten_groups_iter(self) -> Generator[list[tuple[T, ...]], None, None]:
        i = self.flatten_iter()
        g = [next(i)]
        for t in i:
            if Overlap.compute(g[-1], t).overlap:
                g.append(t)
            else:
                yield g
                g = [t]
        yield g

    def split(self) -> list[OverlappedSequences[T]]:
        offsets = sorted(self.offsets.items(), key=lambda x: x[1])
        start = 0
        pending: dict[tuple[T, ...], int] = {}
        end = 0
        new: list[OverlappedSequences[T]] = []
        for d, i in offsets:
            # print(start, end, d, i)
            if end and i >= end:
                assert start < end
                new.append(
                    OverlappedSequences(data=self.data[start:end], offsets=pending)
                )
                pending = {d: 0}
                start = i
            else:
                pending[d] = i - start
            end = max(end, i + len(d))
        assert start < end
        new.append(OverlappedSequences(data=self.data[start:end], offsets=pending))
        return new

    def total_overlap(self) -> int:
        return sum(len(d) for d in self.offsets) - len(self.data)


class _OverlappedSequences(OverlappedSequences[int]):
    @classmethod
    def test(cls) -> None:
        c1: tuple[int, ...] = (1, 2, 3, 4)
        c2: tuple[int, ...] = (2, 3)
        c3: tuple[int, ...] = (3, 4, 5)
        c4: tuple[int, ...] = (1, 3)
        assert cls(c1, {}).add(c2) == cls(c1, {c2: 1})
        assert cls(c1, {}).add(c3) == cls(c1 + c3[2:], {c3: 2})
        assert cls(c1, {}).add(c4) == cls(c1 + c4, {c4: len(c1)})

        assert cls(c1, {}) + cls(c2, {c2: 0}) == cls(c1, {c2: 1})
        assert cls(c1, {}) + cls(c3, {c3: 0}) == cls(c1 + c3[2:], {c3: 2})
        assert cls(c1, {}) + cls(c4, {c4: 0}) == cls(c1 + c4, {c4: len(c1)})

        assert cls(c2, {c2: 0}) + cls(c1, {}) == cls(c1, {c2: 1})
        assert cls(c3, {c3: 0}) + cls(c1, {}) == cls(c1 + c3[2:], {c3: 2})
        assert cls(c4, {c4: 0}) + cls(c1, {}) == cls(c4 + c1, {c4: 0})

        c5 = (1, 2, 3, 4, 5, 6)
        c6 = (1,)
        c7 = (6,)
        s = cls(c5, {c6: 0, c2: 1, c3: 2, c7: 5})
        assert s.total_overlap() == 1, s.total_overlap()
        assert s.split() == [
            cls(c6, {c6: 0}),
            cls(c5[1:-1], {c2: 0, c3: 1}),
            cls(c7, {c7: 0}),
        ], s.split()

        cs = s.flatten()
        assert cs == [c6, c2, c3, c7], cs
        assert cls.from_iterable(cs) == s


################################################################################
# Chunks compressor
################################################################################


class Move(Protocol, Generic[T]):
    def __call__(
        self,
        pairs: list[DeltasPair[T]],
        remaining_chunks: set[tuple[T, ...]],
        overlapped_sequences: list[OverlappedSequences[T]],
    ) -> None: ...


@dataclass
class ChunksCompressor:
    verbose: bool

    @classmethod
    def _insert(
        cls, chunk: tuple[T, ...], index: int, offset: int, overlap: int
    ) -> Move[T]:
        def action(
            pairs: list[DeltasPair[T]],
            remaining_chunks: set[tuple[T, ...]],
            overlapped_sequences: list[OverlappedSequences[T]],
        ) -> None:
            remaining_chunks.remove(chunk)
            pairs[:] = DeltasPair.remove_chunk_from_pairs(pairs, chunk)
            s = overlapped_sequences[index]
            s.insert(offset, overlap, chunk)

        return action

    @classmethod
    def _merge(cls, index1: int, index2: int, offset: int, overlap: int) -> Move[T]:
        def action(
            pairs: list[DeltasPair[T]],
            remaining_chunks: set[tuple[T, ...]],
            overlapped_sequences: list[OverlappedSequences[T]],
        ) -> None:
            s1 = overlapped_sequences[index1]
            s2 = overlapped_sequences.pop(index2)
            s1.merge(offset, overlap, s2)

        return action

    @classmethod
    def _add_new_singleton(cls, chunk: tuple[T, ...]) -> Move[T]:
        def action(
            pairs: list[DeltasPair[T]],
            remaining_chunks: set[tuple[T, ...]],
            overlapped_sequences: list[OverlappedSequences[T]],
        ) -> None:
            remaining_chunks.remove(chunk)
            pairs[:] = DeltasPair.remove_chunk_from_pairs(pairs, chunk)
            overlapped_sequences.append(OverlappedSequences.from_singleton(chunk))

        return action

    @classmethod
    def _add_new_sequence(cls, pair: DeltasPair[T]) -> Move[T]:
        def action(
            pairs: list[DeltasPair[T]],
            remaining_chunks: set[tuple[T, ...]],
            overlapped_sequences: list[OverlappedSequences[T]],
        ) -> None:
            remaining_chunks.remove(pair.d1)
            remaining_chunks.remove(pair.d2)
            pairs[:] = pair.remove_from_pairs(pairs)
            assert pair not in pairs
            overlapped_sequences.append(OverlappedSequences.from_pair(pair))

        return action

    def compress(self, chunks: Iterable[tuple[T, ...]]) -> OverlappedSequences[T]:
        # Prepare data and offsets
        pairs = list(DeltasPair.compute_pairs_overlaps(chunks))

        remaining_chunks = set(chunks)

        if self.verbose:
            print(
                "Count of chunks:",
                len(remaining_chunks),
            )

        overlapped_sequences: list[OverlappedSequences[T]] = []
        best_move: Move[T] | None = None
        total_chunks = len(remaining_chunks)
        while remaining_chunks or (len(overlapped_sequences) > 1 and best_move):
            if self.verbose:
                print(
                    f"# Remaining: {len(remaining_chunks)}/{total_chunks}",
                    "Current pairs:",
                    len(overlapped_sequences),
                )
            best_move = None
            best_overlap: int = 0
            # Try inserting
            for n, s in enumerate(overlapped_sequences):
                for d in remaining_chunks:
                    # Try prepend
                    overlap = Overlap.compute_simple(d, s.data)
                    if overlap > best_overlap:
                        best_overlap = overlap
                        best_move = self._insert(d, n, overlap - len(d), overlap)
                        if self.verbose:
                            print(
                                "Insert chunk (prepend)",
                                best_overlap,
                                len(overlapped_sequences),
                            )
                    # Try insert
                    overlap_max = Overlap.compute(s.data, d)
                    if overlap_max.overlap > best_overlap:
                        best_overlap = overlap_max.overlap
                        best_move = self._insert(
                            d, n, overlap_max.offset, overlap_max.overlap
                        )
                        if self.verbose:
                            print(
                                "Insert chunk (append)",
                                overlap_max,
                                len(overlapped_sequences),
                            )
            # Try merging
            for n1, n2 in itertools.permutations(range(len(overlapped_sequences)), 2):
                s1 = overlapped_sequences[n1]
                s2 = overlapped_sequences[n2]
                # Try insert
                overlap_max = Overlap.compute(s1.data, s2.data)
                if overlap_max.overlap > best_overlap:
                    best_overlap = overlap_max.overlap
                    best_move = self._merge(
                        n1, n2, overlap_max.offset, overlap_max.overlap
                    )
                    if self.verbose:
                        print(
                            "Merge 2 sequences",
                            overlap_max,
                            len(overlapped_sequences),
                        )

            # Take next best pair
            if (
                pairs
                and (best_pair := DeltasPair.compute_best_pair(pairs))
                and best_pair.overlap > best_overlap
            ):
                best_overlap = best_pair.overlap
                best_move = self._add_new_sequence(best_pair)
                if self.verbose:
                    print("Add new sequence", best_overlap, len(overlapped_sequences))
            if not best_move:
                if self.verbose:
                    print("No best move", len(overlapped_sequences))
                if remaining_chunks:
                    best_move = self._add_new_singleton(min(remaining_chunks))
            if best_move:
                best_move(
                    pairs=pairs,
                    remaining_chunks=remaining_chunks,
                    overlapped_sequences=overlapped_sequences,
                )

        assert len(overlapped_sequences) >= 1
        assert not remaining_chunks

        if (l := len(overlapped_sequences)) > 1:
            if self.verbose:
                print("Force merging remaining sequences", l)

            for n1, n2 in itertools.permutations(range(len(overlapped_sequences)), 2):
                s1 = overlapped_sequences[n1]
                s2 = overlapped_sequences[n2]
                overlap_max = Overlap.compute(s1.data, s2.data)
                assert overlap_max.overlap == 0, overlap_max

        for _ in range(1, len(overlapped_sequences)):
            move: Move[T] = self._merge(0, 1, len(overlapped_sequences[0].data), 0)
            move(
                pairs=pairs,
                remaining_chunks=remaining_chunks,
                overlapped_sequences=overlapped_sequences,
            )

        assert len(overlapped_sequences) == 1, overlapped_sequences

        s = overlapped_sequences[0]

        return s

    @classmethod
    def test_moves(cls) -> None:
        c1 = (1, 2, 3, 4, 5)
        c2 = (6, 1)
        c3 = (7, 6, 1)
        c4 = (3, 4)
        c5 = (5, 6, 7)
        c6 = (6, 1, 2)
        c7 = (8, 7, 6)
        chunks0 = {c1, c2, c3, c4, c5, c6, c7}
        chunks = set(chunks0)
        sequences: list[OverlappedSequences[int]] = []
        offsets: dict[tuple[int, ...], int]

        overlap_max = Overlap.compute((1, 2, 3), c1)
        assert overlap_max == Overlap(offset=0, overlap=3)
        pairs: list[DeltasPair[int]] = []

        move = ChunksCompressor._add_new_singleton(c1)
        move(pairs, chunks, sequences)
        offsets = {c1: 0}
        data: tuple[int, ...] = c1
        assert len(sequences) == 1
        s = sequences[0]
        assert s.data == data
        assert s.offsets == offsets

        overlap = Overlap.compute_simple(c2, s.data)
        assert overlap == 1
        overlap_max = Overlap.compute(c2, s.data)
        assert overlap_max.overlap == overlap
        move = ChunksCompressor._insert(
            chunk=c2, index=0, offset=-overlap, overlap=overlap
        )
        move(pairs, chunks, sequences)
        offsets[c1] = 1
        offsets[c2] = 0
        data = c2[:-overlap] + data
        assert len(sequences) == 1
        assert s.data == data
        assert s.offsets == offsets

        overlap = Overlap.compute_simple(c3, s.data)
        assert overlap == 2
        overlap_max = Overlap.compute(c3, s.data)
        assert overlap_max.overlap == overlap
        move = ChunksCompressor._insert(
            chunk=c3, index=0, offset=overlap - len(c3), overlap=overlap
        )
        move(pairs, chunks, sequences)
        offsets[c1] += 1
        offsets[c2] += 1
        offsets[c3] = 0
        data = c3[:-overlap] + data
        assert len(sequences) == 1
        assert s.data == data
        assert s.offsets == offsets

        overlap_max = Overlap.compute(s.data, c4)
        assert overlap_max.overlap == 2, (s.data, c4, overlap_max)
        assert overlap_max.offset == 4, (s.data, c4, overlap_max)
        move = ChunksCompressor._insert(
            chunk=c4, index=0, offset=overlap_max.offset, overlap=overlap_max.overlap
        )
        move(pairs, chunks, sequences)
        offsets[c4] = overlap_max.offset
        assert len(sequences) == 1
        assert s.data == data
        assert s.offsets == offsets

        overlap_max = Overlap.compute(s.data, c5)
        assert overlap_max.overlap == 1, (s.data, c5, overlap_max)
        assert overlap_max.offset == 6, (s.data, c5, overlap_max)
        move = ChunksCompressor._insert(
            chunk=c5, index=0, offset=overlap_max.offset, overlap=overlap_max.overlap
        )
        move(pairs, chunks, sequences)
        offsets[c5] = overlap_max.offset
        data += c5[overlap_max.overlap :]
        assert len(sequences) == 1
        assert s.data == data, (s.data, data)
        assert s.offsets == offsets

        overlap_max = Overlap.compute(s.data, c6)
        assert overlap_max.overlap == 3, (s.data, c6, overlap_max)
        assert overlap_max.offset == 1, (s.data, c6, overlap_max)
        move = ChunksCompressor._insert(
            chunk=c6, index=0, offset=overlap_max.offset, overlap=overlap_max.overlap
        )
        move(pairs, chunks, sequences)
        offsets[c6] = overlap_max.offset
        assert len(sequences) == 1
        assert s.data == data, (s.data, data)
        assert s.offsets == offsets

        overlap = Overlap.compute_simple(c7, s.data)
        assert overlap == 2
        overlap_max = Overlap.compute(c7, s.data)
        assert overlap_max.overlap == overlap
        move = ChunksCompressor._insert(
            chunk=c7, index=0, offset=overlap - len(c7), overlap=overlap
        )
        move(pairs, chunks, sequences)
        for c in offsets:
            offsets[c] += len(c7) - overlap
        offsets[c7] = 0
        data = c7[:-overlap] + data
        assert len(sequences) == 1
        assert s.data == data
        assert s.offsets == offsets

        for c in chunks0:
            offset = s.offsets[c]
            assert c == s.data[offset : offset + len(c)], (
                c,
                s.data[offset : offset + len(c)],
            )

    @classmethod
    def test_compression(cls) -> None:
        c1 = (1, 2, 3)
        c2 = (-1, 0, 1)
        c3 = (-2, -1, 0)
        c4 = (3, 4, 5)
        c5 = (0, 1, 2)
        c6 = (2, 3, 5)
        chunks = {c1, c2, c3, c4, c5, c6}
        compressor = cls(verbose=True)
        r = compressor.compress(chunks)
        assert set(r.offsets) == {c1, c2, c3, c4, c5, c6}
        for c in chunks:
            offset = r.offsets[c]
            assert c == r.data[offset : offset + len(c)], (
                c,
                r.data[offset : offset + len(c)],
            )


################################################################################
# Stats
################################################################################


@dataclass
class Stats:
    data_length: int
    data_int_size: int
    data_overlap: int
    offsets1_length: int
    offsets1_int_size: int
    offsets2_length: int
    offsets2_int_size: int

    @property
    def data_size(self) -> int:
        return self.data_length * self.data_int_size

    @property
    def offsets1_size(self) -> int:
        return self.offsets1_length * self.offsets1_int_size

    @property
    def offsets2_size(self) -> int:
        return self.offsets2_length * self.offsets2_int_size

    @property
    def total(self) -> int:
        return self.data_size + self.offsets1_size + self.offsets2_size


def _int_size(ts: Sequence[Iterable[int] | int], offset: int = 0) -> int:
    assert ts
    if isinstance(ts[0], int):
        ts = cast(Sequence[int], ts)
        min_delta: int = min(ts)
        max_delta: int = max(ts)
    else:
        ts = cast(Sequence[Iterable[int]], ts)
        min_delta = min(min(t) for t in ts)
        max_delta = max(max(t) for t in ts)
    if offset:
        min_delta <<= offset
        max_delta <<= offset
    for n in range(3, 7):
        size: int = 2**n
        min_int = -(1 << (size - 1))
        max_int = -min_int - 1
        if min_int <= min_delta and max_delta <= max_int:
            return size
    else:
        raise ValueError((min_delta, max_delta))


def uint_size(ts: Sequence[int]) -> int:
    min_delta = min(ts)
    if min_delta < 0:
        raise ValueError(min_delta)
    max_delta = max(ts)
    for n in range(3, 7):
        size: int = 2**n
        max_int = (1 << size) - 1
        if max_delta <= max_int:
            return size
    else:
        raise ValueError((min_delta, max_delta))


################################################################################
# Compressed array
################################################################################

I = TypeVar("I", Entry, int)


@dataclass
class CompressedArray(Generic[I]):
    data: tuple[I, ...]
    offsets: tuple[int, ...]
    chunk_offsets: dict[tuple[I, ...], int]

    @classmethod
    def from_overlapped_sequences(
        cls, s: OverlappedSequences[I], groups: Groups[I]
    ) -> Self:
        offsets = tuple(
            s.offsets[d]
            for _, d in sorted(
                ((g, d0) for d0, gs in groups.items() for g in gs),
                key=lambda x: x[0],
            )
        )
        return cls(data=s.data, offsets=offsets, chunk_offsets=s.offsets)

    def total_overlap(self) -> int:
        return sum(len(d) for d in self.chunk_offsets) - len(self.data)

    def stats(self, int_size: Callable[[Sequence[Iterable[int] | int]], int]) -> Stats:
        return Stats(
            data_length=len(self.data),
            data_int_size=int_size(self.data),
            data_overlap=self.total_overlap(),
            offsets1_length=len(self.offsets),
            offsets1_int_size=_int_size(self.offsets),
            offsets2_length=0,
            offsets2_int_size=0,
        )

    @staticmethod
    def test() -> None:
        c1 = (1, 2, 3, 4)
        c2 = (2, 3)
        c3 = (3, 4, 5)
        c4 = (1, 3)
        s = OverlappedSequences.from_singleton(c1)
        s += c2
        s += c3
        s += c4
        groups: Groups[int] = {c1: [0, 3], c2: [4], c3: [1, 2]}
        a = CompressedArray.from_overlapped_sequences(s, groups)
        assert a == CompressedArray(
            data=s.data, offsets=(0, 2, 2, 0, 1), chunk_offsets=s.offsets
        ), a


@dataclass
class ArrayCompressor:
    compressor: ChunksCompressor
    verbose: bool

    def run(self, groups: Groups[I]) -> CompressedArray[I]:
        s = self.compressor.compress(groups)
        return CompressedArray.from_overlapped_sequences(s, groups)

    @classmethod
    def compress(
        cls,
        compressor: ChunksCompressor,
        block_size: int,
        data: Iterable[I],
        default: I,
        verbose: bool = False,
    ) -> CompressedArray[I]:
        groups = generate_groups(block_size=block_size, data=data)
        array_compressor = cls(compressor=compressor, verbose=verbose)
        return array_compressor.run(groups)

    @classmethod
    def test_compression(cls) -> None:
        c1 = (1, 2, 3)
        c2 = (-1, 0, 1)
        c3 = (-2, -1, 0)
        c4 = (3, 4, 5)
        c5 = (0, 1, 2)
        c6 = (2, 3, 5)
        groups: Groups[int] = {
            c1: [0],
            c2: [1],
            c3: [2],
            c4: [3],
            c5: [4],
            c6: [5],
        }
        compressor = cls(
            compressor=ChunksCompressor(verbose=True),
            verbose=True,
        )
        r = compressor.run(groups)
        assert set(r.chunk_offsets) == {c1, c2, c3, c4, c5, c6}
        for c, gs in groups.items():
            for g in gs:
                offset = r.offsets[g]
                assert c == r.data[offset : offset + len(c)], (
                    c,
                    r.data[offset : offset + len(c)],
                )


################################################################################
# Solutions
################################################################################


@dataclass
class SimpleSolution(Generic[T]):
    data_block_size_log2: int
    data_int_size: int
    data_overlap: int
    data: tuple[T, ...]
    offsets1_block_size_log2: int
    offsets1_int_size: int
    offsets1: tuple[int, ...]
    offsets2_int_size: int
    offsets2: tuple[int, ...]
    max: int
    total: int

    @classmethod
    def zeros(cls) -> Self:
        return cls(
            data_block_size_log2=0,
            data_int_size=0,
            data_overlap=0,
            data=(),
            offsets1_block_size_log2=0,
            offsets1_int_size=0,
            offsets1=(),
            offsets2_int_size=0,
            offsets2=(),
            max=0,
            total=0,
        )

    @property
    def case(self) -> str:
        return "both"

    @property
    def data_size(self) -> int:
        return len(self.data) * self.data_int_size

    def _convert(self, op: Callable[[X, T], X], x: X) -> X:
        mask1 = (1 << self.data_block_size_log2) - 1
        mask2 = (1 << self.offsets1_block_size_log2) - 1
        cpʹ = x >> self.data_block_size_log2
        offset = self.offsets2[cpʹ >> self.offsets1_block_size_log2] + (cpʹ & mask2)
        return op(x, self.data[self.offsets1[offset] + (x & mask1)])


class SimpleSolutionCombinedMappings(SimpleSolution[Entry], metaclass=ABCMeta):
    @property
    @abstractmethod
    def type(self) -> str: ...

    def to_lower(self, x: X) -> X:
        return self._convert(lambda a, e: e.to_lower(a), x)

    def to_upper(self, x: X) -> X:
        return self._convert(lambda a, e: e.to_upper(a), x)


class SimpleSolutionKeysymsCombinedMappings(SimpleSolutionCombinedMappings):
    @property
    def type(self) -> str:
        return "legacy_keysyms"

    def test(self, config: Config) -> bool:
        # Check legacy keysyms
        r = True
        for ks in map(Keysym, range(0, self.max + 1)):
            if not (char := xkbcommon.keysym_to_str(ks)):
                continue
            cp = ord(char)

            # Lower
            if ks <= self.max:
                expected = Entry.to_lower_char(char)
                ksʹ = xkbcommon.keysym_from_char(expected)
                ksʹʹ = self.to_lower(ks)
                got = xkbcommon.keysym_to_str(ksʹʹ)
                ok = got == expected
                data = (
                    hex(ks),
                    hex(cp),
                    char,
                    expected,
                    char.lower(),
                    hex(ksʹ),
                    hex(ksʹʹ),
                    got,
                )
                if config.check_error:
                    assert ok, data
                elif not ok:
                    print("Error:", data)
                    r = False

            # Upper
            if ks <= self.max:
                expected = Entry.to_upper_char(char)
                ksʹ = xkbcommon.keysym_from_char(expected)
                ksʹʹ = self.to_upper(ks)
                got = xkbcommon.keysym_to_str(ksʹʹ)
                ok = got == expected
                data = (
                    hex(ks),
                    hex(cp),
                    char,
                    expected,
                    char.upper(),
                    hex(ksʹ),
                    hex(ksʹʹ),
                    got,
                )
                if config.check_error:
                    assert ok, data
                elif not ok:
                    print("Error:", data)
                    r = False
        return r


class SimpleSolutionUnicodeCombinedMappings(SimpleSolutionCombinedMappings):
    @property
    def type(self) -> str:
        return "unicode"

    def test(self, config: Config) -> bool:
        # Check Unicode keysyms
        unicode_min = (
            xkbcommon.XKB_KEYSYM_UNICODE_MIN - xkbcommon.XKB_KEYSYM_UNICODE_OFFSET
        )
        r = True
        for cp in map(CodePoint, range(unicode_min, self.max + 1)):
            char = chr(cp)
            # Lower
            if cp <= self.max:
                expected = Entry.to_lower_char(char)
                got = chr(self.to_lower(cp))
                ok = got == expected
                dataʹ = (hex(cp), char, expected, char.lower(), got)
                if config.check_error:
                    assert ok, dataʹ
                elif not ok:
                    print("Error:", dataʹ)
                    r = False
            # Upper
            if cp <= self.max:
                expected = Entry.to_upper_char(char)
                got = chr(self.to_upper(cp))
                ok = got == expected
                dataʹ = (hex(cp), char, expected, char.upper(), got)
                if config.check_error:
                    assert ok, dataʹ
                elif not ok:
                    print("Error:", dataʹ)
                    r = False
        return r


S = TypeVar("S", bound=SimpleSolutionCombinedMappings)


@dataclass
class SeparateLegacyKeysymsAndUnicodeCombinedCaseMappings:
    legacy_keysyms: SimpleSolutionKeysymsCombinedMappings
    unicode: SimpleSolutionUnicodeCombinedMappings

    def __iter__(self) -> Generator[SimpleSolutionCombinedMappings, None, None]:
        yield self.legacy_keysyms
        yield self.unicode

    @property
    def total(self) -> int:
        return sum(s.total for s in self)

    def test(self, config: Config) -> bool:
        r = True
        if self.legacy_keysyms.data:
            r &= self.legacy_keysyms.test(config)
        if self.unicode.data:
            r &= self.unicode.test(config)
        return r

    @classmethod
    def optimize_groups(
        cls,
        data: tuple[Entry, ...],
        data_max: int,
        total0: int,
        config: Config,
        cls_: type[S],
    ) -> S:
        chunks_compressor = ChunksCompressor(verbose=config.verbose)
        total = total0
        max_int_size = sys.maxsize
        solution: S | None = None
        for k1 in range(1, 9):
            block_size1 = 2**k1
            if config.verbose:
                print("".center(80, "-"))
                print(f"{block_size1=} Step 1: Generating 1st compression level…")
            ca1 = ArrayCompressor.compress(
                compressor=chunks_compressor,
                block_size=block_size1,
                data=data,
                default=Entry.zeros(),
                verbose=config.verbose,
            )
            stats1 = ca1.stats(int_size=lambda x: _int_size(x, offset=2))
            if config.verbose:
                print("Step 1 done.")
                print(
                    f"{block_size1=} Step 1:",
                    f"data_overlap={stats1.data_overlap} data_length={stats1.data_length} data_size={stats1.data_size}",
                    f"total={stats1.total}",
                )
            current_total = stats1.total
            if config.verbose:
                print(f"{current_total=}")
            if (data_size := stats1.data_size) >= total:
                if config.verbose:
                    print(f"We cannot beat the current solution {data_size=} {total=}")
                continue
            current_int_size = max(stats1.data_int_size, stats1.offsets1_int_size)
            if current_total <= total and (
                current_total != total or current_int_size < max_int_size
            ):
                total = current_total
                max_int_size = current_int_size
                if config.verbose:
                    print(f"✨ New best solution: {block_size1=} {total=}")
                # TODO: 1st level solution
            for k2 in range(7, 1, -1):
                block_size2 = 2**k2
                if config.verbose:
                    print(
                        f"{block_size1=} {block_size2=} Step 2: 2nd level compression… ",
                        flush=True,
                    )
                ca2 = ArrayCompressor.compress(
                    compressor=chunks_compressor,
                    block_size=block_size2,
                    data=ca1.offsets,
                    default=0,
                    verbose=config.verbose,
                )
                stats2 = ca2.stats(int_size=_int_size)
                stats = Stats(
                    data_length=stats1.data_length,
                    data_int_size=stats1.data_int_size,
                    data_overlap=stats1.data_overlap,
                    offsets1_length=stats2.data_length,
                    offsets1_int_size=stats2.data_int_size,
                    offsets2_length=stats2.offsets1_length,
                    offsets2_int_size=stats2.offsets1_int_size,
                )
                current_total = stats.total
                if config.verbose:
                    print(
                        f"{block_size1=} {block_size2=} Step 2:",
                        f"data_overlap={stats.data_overlap} data_length={stats.data_length} data_size={stats.data_size}",
                        f"total={stats.total}",
                    )
                    print("Step 2 done.", flush=True)
                current_int_size = max(
                    stats.data_int_size,
                    stats.offsets1_int_size,
                    stats.offsets2_int_size,
                )
                if current_total < total or (
                    current_total == total and current_int_size < max_int_size
                ):
                    total = current_total
                    max_int_size = current_int_size
                    if config.verbose:
                        print(
                            f"✨ New best solution: {block_size1=} {block_size2=} {total=}"
                        )
                    solution = cls_(
                        data_block_size_log2=k1,
                        data_int_size=stats.data_int_size,
                        data=ca1.data,
                        data_overlap=stats.data_overlap,
                        offsets1_block_size_log2=k2,
                        offsets1=ca2.data,
                        offsets1_int_size=stats.offsets1_int_size,
                        offsets2=ca2.offsets,
                        offsets2_int_size=stats.offsets2_int_size,
                        max=data_max,
                        total=stats.total,
                    )
        assert solution
        if config.verbose:
            print(" Finished ".center(80, "*"))
            print(
                f"Best solution ({solution.case}):",
                f"data_block_size={2**solution.data_block_size_log2}",
                f"data_overlap={solution.data_overlap}",
                f"offsets1_block_size={2**solution.offsets1_block_size_log2}",
                f"total={solution.total}",
            )
            print("Total:", solution.total)
            print("".center(80, "*"))
        return solution

    @classmethod
    def optimize(
        cls,
        config: Config,
        path: Path | None = None,
    ) -> Self:
        print("Computing deltas… ", end="", flush=True)
        entries = Entries.compute(config=config, path=path)
        print("Done.", flush=True)
        keysyms = cls.optimize_groups(
            config=config,
            data=entries.keysyms,
            data_max=entries.keysym_max,
            total0=32 * len(entries.keysyms),
            cls_=SimpleSolutionKeysymsCombinedMappings,
        )
        unicode = cls.optimize_groups(
            config=config,
            data=entries.unicode,
            data_max=entries.unicode_max,
            total0=32 * len(entries.unicode),
            cls_=SimpleSolutionUnicodeCombinedMappings,
        )
        result = cls(legacy_keysyms=keysyms, unicode=unicode)
        print(" Finished ".center(90, "*"))
        for s in result:
            if s.data:
                print(
                    f"✨ {s.type}:",
                    f"max: 0x{s.max:0>4x}",
                    f"data_block_size={2**s.data_block_size_log2}",
                    f"offsets_block_size={2**s.offsets1_block_size_log2}",
                    f"data={len(s.data)} (int size: {s.data_int_size})",
                    f"data_overlap={s.data_overlap}",
                    f"offsets1={len(s.offsets1)} (uint size: {s.offsets1_int_size})",
                    f"offsets2={len(s.offsets2)} (uint size: {s.offsets2_int_size})",
                    f"total={s.total} ({s.total // 8})",
                )
        print(f"Total: {result.total} ({result.total // 8})")
        print("".center(90, "*"))
        return result

    @classmethod
    def generate(cls, root: Path, write: bool, config: Config) -> None:
        s = cls.optimize(
            config=config,
            path=root / "data/keysyms.yaml",
        )
        s.test(config)
        if write:
            s.write(root)

    MAPPING_TEMPLATE = """\
static const struct CaseMappings {prefix}data[{data_length}] = {{
    {data}
}};

static const uint{offsets1_int_size}_t {prefix}offsets1[{offsets1_length}] = {{
    {offsets1}
}};

static const uint{offsets2_int_size}_t {prefix}offsets2[{offsets2_length}] = {{
    {offsets2}
}};

static inline const struct CaseMappings *
get_{prefix}entry(xkb_keysym_t ks)
{{
    return &{prefix}data[{prefix}offsets1[{prefix}offsets2[ks >> {k12}] + ((ks >> {k1}) & 0x{mask2:0>2x})] + (ks & 0x{mask1:0>2x})];
}}\
"""

    TEMPLATE = """\
// NOTE: This file has been generated automatically by “{python_script}”.
//       Do not edit manually!

/*
 * Copyright © 2024 Pierre Le Marre
 * SPDX-License-Identifier: MIT
 */

/* Case mappings for Unicode {unicode_version}
 *
{doc}
 */

#include "config.h"

#include <stdint.h>
#include <stdbool.h>
#include <string.h>
#include "xkbcommon/xkbcommon.h"
#include "utils.h"
#include "keysym.h"

struct CaseMappings{{
    bool lower:1;
    bool upper:1;
    int{data_int_size}_t offset:{data_int_size_with_offset};
}};

{legacy_keysyms_mappings}

{unicode_mappings}

xkb_keysym_t
xkb_keysym_to_lower(xkb_keysym_t ks)
{{
    if (ks <= 0x{max_non_unicode:0>4x}) {{
        const struct CaseMappings *m = get_legacy_keysym_entry(ks);
        return (m->lower) ? ks + m->offset : ks;
    }} else if ({min_unicode} <= ks && ks <= 0x{max_unicode:0>8x}) {{
        const struct CaseMappings *m = get_unicode_entry(ks - XKB_KEYSYM_UNICODE_OFFSET);
        if (m->lower) {{
            ks = ks + m->offset;
            return (ks < {min_unicode}) ? ks - XKB_KEYSYM_UNICODE_OFFSET : ks;
        }} else {{
            return ks;
        }}
    }} else {{
        return ks;
    }}
}}

xkb_keysym_t
xkb_keysym_to_upper(xkb_keysym_t ks)
{{
    if (ks <= 0x{max_non_unicode:0>4x}) {{
        const struct CaseMappings *m = get_legacy_keysym_entry(ks);
        return (m->upper) ? ks - m->offset : ks;
    }} else if ({min_unicode} <= ks && ks <= 0x{max_unicode:0>8x}) {{
        const struct CaseMappings *m = get_unicode_entry(ks - XKB_KEYSYM_UNICODE_OFFSET);
        if (m->upper) {{
            ks = ks - m->offset;
            return (ks < {min_unicode}) ? ks - XKB_KEYSYM_UNICODE_OFFSET : ks;
        }} else {{
            return ks;
        }}
    }} else {{
        return ks;
    }}
}}

bool
xkb_keysym_is_lower(xkb_keysym_t ks)
{{
    /* This predicate matches keysyms with their corresponding Unicode code point
     * having the Unicode property “Lowercase”.
     *
     * Here: a keysym is lower case if it has an upper case and no lower case.
     * Note: title case letters may have both. Example for U+01F2:
     * • U+01F1 DZ: upper case
     * • U+01F2 Dz: title case
     * • U+01F3 dz: lower case
     */
    if (ks <= 0x{max_non_unicode:0>4x}) {{
        const struct CaseMappings *m = get_legacy_keysym_entry(ks);
        return m->upper && !m->lower;
    }} else if ({min_unicode} <= ks && ks <= 0x{max_unicode:0>8x}) {{
        const struct CaseMappings *m = get_unicode_entry(ks - XKB_KEYSYM_UNICODE_OFFSET);
        return m->upper && !m->lower;
    }} else {{
        return false;
    }}
}}

bool
xkb_keysym_is_upper_or_title(xkb_keysym_t ks)
{{
    /* This predicate matches keysyms with their corresponding Unicode code point
     * having the Unicode properties “Uppercase” or General Category “Lt”.
     *
     * Here: a keysym is upper case or title case if it has a lower case. */
    if (ks <= 0x{max_non_unicode:0>4x}) {{
        return get_legacy_keysym_entry(ks)->lower;
    }} else if ({min_unicode} <= ks && ks <= 0x{max_unicode:0>8x}) {{
        return get_unicode_entry(ks - XKB_KEYSYM_UNICODE_OFFSET)->lower;
    }} else {{
        return false;
    }}
}}
"""

    @staticmethod
    def myHex(n: int, max_hex_length: int) -> str:
        return (
            f"""{"-" if n < 0 else " "}0x{hex(abs(n))[2:].rjust(max_hex_length, "0")}"""
        )

    @classmethod
    def make_char_case_mappings(cls, e: Entry, max_hex_length: int) -> str:
        # If the entry has both lower and upper mappings, they must be equal.
        if e.lower and e.upper and e.lower != e.upper:
            raise ValueError(e)
        has_lower = e.is_upper or bool(e.lower)
        has_upper = e.is_lower or bool(e.upper)
        return f"{{{int(has_lower)}, {int(has_upper)},{cls.myHex(e.lower or e.upper, max_hex_length)}}}"

    def generate_mapping(self, prefix: str, sol: SimpleSolutionCombinedMappings) -> str:
        if not sol.offsets1_block_size_log2:
            raise ValueError(f"generate_mapping: {prefix}")
        max_data = max(max(abs(e.lower), abs(e.upper)) for e in sol.data)
        max_hex_length = 1 + (int(math.log2(max_data)) >> 2)
        return self.MAPPING_TEMPLATE.format(
            prefix=prefix,
            data_length=len(sol.data),
            data=",\n    ".join(
                ", ".join(
                    "".join(self.make_char_case_mappings(x, max_hex_length)) for x in xs
                )
                for xs in itertools.batched(sol.data, 4)
            ),
            offsets1_int_size=sol.offsets1_int_size,
            offsets1_length=len(sol.offsets1),
            offsets1=",\n    ".join(
                ", ".join(f"0x{x:0>4x}" for x in xs)
                for xs in itertools.batched(sol.offsets1, 10)
            ),
            offsets2_int_size=sol.offsets2_int_size,
            offsets2_length=len(sol.offsets2),
            offsets2=",\n    ".join(
                ", ".join(f"0x{x:0>4x}" for x in xs)
                for xs in itertools.batched(sol.offsets2, 10)
            ),
            k1=sol.data_block_size_log2,
            k2=sol.offsets1_block_size_log2,
            k12=sol.data_block_size_log2 + sol.offsets1_block_size_log2,
            mask1=(1 << sol.data_block_size_log2) - 1,
            mask2=(1 << sol.offsets1_block_size_log2) - 1,
        )

    def write(self, root: Path) -> None:
        path = root / "src/keysym-case-mappings.c"
        keysyms = self.generate_mapping("legacy_keysym_", self.legacy_keysyms)
        unicode = self.generate_mapping("unicode_", self.unicode)
        assert self.legacy_keysyms.data_int_size == self.unicode.data_int_size
        doc = textwrap.indent(
            textwrap.indent(__doc__.strip(), prefix=" "),
            prefix=" *",
            predicate=lambda _: True,
        )
        content = self.TEMPLATE.format(
            python_script=Path(__file__).name,
            unicode_version=icu.UNICODE_VERSION,
            doc=doc,
            data_int_size=self.legacy_keysyms.data_int_size,
            data_int_size_with_offset=self.legacy_keysyms.data_int_size - 2,
            legacy_keysyms_mappings=keysyms,
            unicode_mappings=unicode,
            max_non_unicode=self.legacy_keysyms.max,
            min_unicode="XKB_KEYSYM_UNICODE_MIN",
            max_unicode=XKBCOMMON.XKB_KEYSYM_UNICODE_OFFSET + self.unicode.max,
            keysym_unicode_offset="XKB_KEYSYM_UNICODE_OFFSET",
        )
        with path.open("wt", encoding="utf-8") as fd:
            fd.write(content)

        unicode_version_array = ", ".join(
            (icu.UNICODE_VERSION + ".0.0.0").split(".")[:4]
        )
        path = root / "src/keysym.h.jinja"
        with path.open("rt", encoding="utf-8") as fd:
            content = fd.read()
        pattern: re.Pattern[str] = re.compile(
            r"^(#define\s+XKB_KEYSYM_UNICODE_VERSION\s+\{\s*)(?:\d+(?:,\s*\d+)*)*(\s*\})",
            re.MULTILINE,
        )

        def replace(m: re.Match[str]) -> str:
            return f"{m.group(1)}{unicode_version_array}{m.group(2)}"

        content = pattern.sub(replace, content)
        with path.open("wt", encoding="utf-8") as fd:
            fd.write(content)


################################################################################
# Strategy
################################################################################


@unique
class Strategy(Enum):
    Default = SeparateLegacyKeysymsAndUnicodeCombinedCaseMappings

    def __str__(self) -> str:
        return self.value.__name__

    @classmethod
    def parse(cls, str: str) -> Self:
        for s in cls:
            if s.name == str:
                return s
        else:
            raise ValueError(str)

    @classmethod
    def run(
        cls, root: Path, config: Config, strategies: list[Self], write: bool
    ) -> None:
        # FIXME: more generic type
        results: list[SeparateLegacyKeysymsAndUnicodeCombinedCaseMappings] = []
        best_total = math.inf
        best_solution: SeparateLegacyKeysymsAndUnicodeCombinedCaseMappings | None = None
        for strategy in strategies:
            print(f" Optimizing using {strategy.name} ".center(90, "="))
            sol = strategy.value.optimize(
                config=config, path=root / "data/keysyms.yaml"
            )
            sol.test(config)
            results.append(sol)
            if sol.total < best_total:
                best_total = sol.total
                best_solution = sol
                assert best_solution
        assert best_solution
        for strategy, sol in zip(strategies, results):
            print(
                f"{strategy.name}: {sol.total} ({sol.total // 8})",
                "✨✨✨" if sol is best_solution else "",
            )
        best_solution.test(config)
        if write:
            best_solution.write(root)
            cls.write_tests(root)

    @classmethod
    def write_tests(cls, root: Path) -> None:
        # Configure Jinja
        template_loader = jinja2.FileSystemLoader(root, encoding="utf-8")
        jinja_env = jinja2.Environment(
            loader=template_loader,
            keep_trailing_newline=True,
            trim_blocks=True,
            lstrip_blocks=True,
        )

        def code_point_name_constant(c: str, padding: int = 0) -> str:
            if not (name := unicodedata.name(c)):
                raise ValueError(f"No Unicode name for code point: U+{ord(c):0>4X}")
            name = name.replace("-", "_").replace(" ", "_").upper()
            return name.ljust(padding)

        jinja_env.filters["code_point"] = lambda c: f"0x{ord(c):0>4x}"
        jinja_env.filters["code_point_name_constant"] = code_point_name_constant
        path = root / "test/keysym-case-mapping.h"
        template_path = path.with_suffix(f"{path.suffix}.jinja")
        template = jinja_env.get_template(str(template_path.relative_to(root)))
        with path.open("wt", encoding="utf-8") as fd:
            fd.writelines(
                template.generate(
                    upper_exceptions=Entry.to_upper_exceptions,
                    script=SCRIPT.relative_to(root),
                )
            )


def import_from_path(module_name: str, file_path: Path):
    spec = importlib.util.spec_from_file_location(module_name, file_path)
    module = importlib.util.module_from_spec(spec)
    sys.modules[module_name] = module
    spec.loader.exec_module(module)
    return module


################################################################################
# Main
################################################################################


if __name__ == "__main__":
    # Root of the project
    ROOT = Path(__file__).parent.parent

    # Parse commands
    parser = argparse.ArgumentParser(description="Generate keysyms case mapping files")
    parser.add_argument(
        "--root",
        type=Path,
        default=ROOT,
        help="Path to the root of the project (default: %(default)s)",
    )
    parser.add_argument(
        "--ucd",
        type=Path,
        help="Path to UCD directory to replace ICU",
        required=icu is None,
    )
    parser.add_argument(
        "--ucd-version",
        type=str,
        help="Version of the UCD",
        required=icu is None,
    )
    parser.add_argument(
        "--strategy",
        type=Strategy.parse,
        default=list(Strategy),
        nargs="+",
        choices=Strategy,
        help="Strategy (default: %(default)s)",
        dest="strategies",
    )
    parser.add_argument(
        "--dry",
        action="store_true",
        help="Do not write (default: %(default)s)",
    )
    parser.add_argument(
        "--verbose",
        action="store_true",
        help="Verbose (default: %(default)s)",
    )
    parser.add_argument(
        "--no-check",
        action="store_true",
        help="Do not check errors (default: %(default)s)",
    )

    args = parser.parse_args()

    if ucd_path := args.ucd:
        # Use a local UCD instead of ICU.
        # Useful when ICU is not available or when it does not support the latest
        # Unicode version.
        # Data are available at: https://www.unicode.org/Public/<UNICODE_VERSION>/ucd/
        icu = import_from_path(
            module_name="icu", file_path=Path(__file__).with_stem("ucd")
        )
        if ucd_version := args.ucd_version:
            icu.UNICODE_VERSION = ucd_version
        icu.Char = icu.DB.parse_ucd(ucd_path)

    config = Config(
        check_error=not args.no_check,
        verbose=args.verbose,
    )
    Strategy.run(
        root=args.root, config=config, write=not args.dry, strategies=args.strategies
    )