Repository navigation
Expand file tree
/
Copy pathtxtarget.py
More file actions
1748 lines (1583 loc) · 82.8 KB
/
Copy pathtxtarget.py
File metadata and controls
1748 lines (1583 loc) · 82.8 KB
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
"""txtarget.py — the language a translation goes INTO, and how a build draws it.
The translation editor's source text is the English of the USA disc (or the
Japanese of a Japanese disc); its target can be any language. What a build
has to do depends on what the retail fonts can already draw:
* **builtin** — every letter of the language is in the retail fonts: ASCII
plus the USA proportional accent block (``txcodec.LATIN_MAP``: French,
Spanish, German, Italian, Portuguese, Dutch, Catalan, the Nordic
languages...). ``txcodec`` writes the retail codes; nothing is drawn.
* **script-hybrid** — a Latin alphabet with a few letters the block lacks
(Polish ł ś ż ć ń ą ę ź, Czech č ř ě ů, Turkish ğ ı ş, Romanian ș ț, ...):
the letters the block has stay retail, the others are drawn from a
TrueType font into free font cells.
* **japanese** — the retail fonts draw JIS X 0208 natively (kana,
punctuation, full-width forms, level-1 kanji, rows A1-CF) EXCEPT level-2
kanji: EUC rows D0 and up are the USA proportional block on this disc
(``txcodec`` refuses those codes), so every level-2 kanji a translation
uses is drawn from a Japanese TrueType font into a kanji cell the
translation does not use (handed out from the last row backwards).
* **script** — a script the disc never had (Cyrillic, Greek, Arabic,
Hebrew, Devanagari, Hangul, Han, Thai, Georgian, Ethiopic, Armenian, or
any other with a font that covers it): every letter is shaped with
HarfBuzz and drawn from a TrueType font. Right-to-left scripts are
ordered, wrapped and (optionally) right-aligned at build time.
Kinds are decided from the language's alphabet against the retail fonts
(``_kind_of``), never by hand; ``TARGETS`` is the table the editor offers,
``profile(code)`` one entry, ``coverage()`` the per-character answer for a
set of strings. The build path (``plan_glyphs``) is used by ``txbuild``
whenever a project's translations need any new glyph; a builtin or
Japanese project whose text needs none is built exactly as before.
What a new-script build does (one pass, every family, deterministic):
1. Every translated string of the project is NFC-normalised and split into
runs: characters the retail face draws natively (ASCII, the accent block,
JIS) and characters that need a glyph. Protected tokens (``⟦XX⟧`` runs,
evt ``/[...]`` tags, chat ``\\NN`` escapes, printf formats, U.M.N. ``@x``
codes) ride along as control placeholders, never shaped or mirrored.
2. ``langpack.Encoder(collect=True)`` collects the glyph keys of every
field-font string (both faces: font0 for "ev" cutscenes, font1 for the
rest, each row with its own face). ONE ``glyphs.GlyphSet.allocate`` over
all of them, most used first, keys sorted for ties: free proportional
slots, then kanji cells. Never taken: the ASCII slots, the block cells
and kanji cells ANY retail string still draws (``retail_usage``: every
row of the four families, so untranslated English keeps its ä — ™ ® ç
and ・), and the cells of every native character the translation uses
(in EVERY edited row, also the rows that need no new glyph).
3. Each edited string is encoded on its own with ``Encoder.string`` (never
a whole tree: that re-wraps untranslated lines). New glyphs come out as
``txcodec.glyph_char(code)`` characters, which the family modules
validate and write like any text inside ``txcodec.glyph_codes()``.
Right-to-left rows get the Unicode bidi run order, mirrored brackets, a
wrap width (the row's guide, 370 px for dialogue, or the project's
``wrap``) and, with ``align: right``, right alignment. Tokens at a
line's edges stay there; a state token (``/[...]``, chat ``\\NNN``,
``⟦XX⟧``) in the middle of a right-to-left line is refused with the row
id (word reordering would move it onto other words).
4. Battle-font rows (OV01 ``menuFontPut``) get their letters drawn into the
battle grid's free cells (``statfont``; cells 125+ first, then 63-123;
cells the retail strings or any edited battle row's accent escapes use
are kept; one cell per HarfBuzz cluster, marks placed from their own
base, ``statfont.cell_clusters``) and one byte each from the
bytes the 230-byte table does not use (bytes any battle string still
writes are kept); the new table is written in the same OV01 apply as the
strings (``txfam_ovl.apply(raw_overrides=...)``); letters beyond the 56
spare bytes use the ``#XX`` cell escape.
5. Tag-font rows (title ribbons, ``PrintTagFont``) have only A-Z a-z 0-9
``: / . -``: a non-Latin letter there is refused with the row id.
Nothing derived is stored: the project holds only ``target`` (code, kind,
script, rtl, font path, face, sizes, align, wrap); the glyph set is
regenerated from the logical text on every build, so a build is
reproducible from the project and the font.
Rendering: the retail Latin is condensed (H = 7 x 15 px on a baseline at
row 20 of the 20x24 cell), so each script has default ``px`` / ``baseline``
/ ``xscale`` (horizontal squeeze) values that match it (``RENDER``); a
project can override them.
Public API (for txserver / txcatalog / txbuild):
TARGETS list of profile dicts (see profile())
profile(code) -> dict|None one profile: code, name, endonym, kind, script,
rtl, sample, alphabet, fonts (Noto names),
render {px, baseline, xscale}
normalise_target(d) -> dict clean project["target"] (raises TargetError)
resolve_target(project) profile defaults + project["target"] (+ language)
coverage(texts, target, font="field", face="font1", ttf=None, ttf_face=0)
-> {native, glyph, folded, impossible,
missing_in_font, counts}
system_fonts(script=None, chars=None) -> [{path, face, family, style,
noto, scripts}] fonts installed on this machine
suggest_fonts(target, chars=None) -> {"noto": [family], "installed": system_fonts()[:12]}
shaping_available() -> (bool, message)
needs_glyphs(target, rows, edits) -> bool
plan_glyphs(retail, target, rows, edits, log) -> GlyphPlan
retail_usage(retail) -> Usage
preview(retail, target, text, font="field", face="font1", ctl="c0") -> ([png per line], encoded)
python3 txtarget.py list
python3 txtarget.py fonts --script Cyrl
python3 txtarget.py coverage --code pl --text "Zażółć gęślą jaźń"
python3 txtarget.py selftest --iso RETAIL [--out DIR]
"""
from __future__ import annotations
import argparse
import json
import os
import re
import sys
import time
import unicodedata
from collections import Counter
from pathlib import Path
from typing import Callable, Dict, Iterable, List, Optional, Sequence, Set, Tuple
ROOT = Path(__file__).resolve().parent
if str(ROOT) not in sys.path:
sys.path.insert(0, str(ROOT))
import font as fontmod # noqa: E402
import txcodec as tc # noqa: E402
KINDS = ("builtin", "script-hybrid", "japanese", "script")
DIALOGUE_WRAP = 370 # px: the engine re-wraps dialogue a little under 400
CACHE_DIR = Path.home() / ".cache" / "xs1-txeditor"
class TargetError(tc.TxBuildError):
"""A target the build cannot draw; the message says why (per row id)."""
# ---------------------------------------------------------------------------
# rendering defaults per script
# ---------------------------------------------------------------------------
# px = em size, baseline = cell row of the baseline (retail: ink ends on row
# 19, so 20), xscale = horizontal squeeze to the retail Latin's proportions.
# battle_* = the same for the 10x18 battle grid. The retail battle letters
# are 8 px wide with a 15 px cap height on a baseline at row 17 (measured from
# stat.xtx: H rows 2-16, x rows 6-16), so 20 px squeezed to 0.55 matches them
# (statfont's own default, 13 px on row 13, draws letters half that size).
RENDER: Dict[str, dict] = {
"Latn": {"px": 21.0, "baseline": 20, "xscale": 0.62},
"Cyrl": {"px": 21.0, "baseline": 20, "xscale": 0.62},
"Grek": {"px": 21.0, "baseline": 20, "xscale": 0.62},
"Armn": {"px": 21.0, "baseline": 20, "xscale": 0.62},
"Geor": {"px": 20.0, "baseline": 19, "xscale": 0.66},
"Hebr": {"px": 21.0, "baseline": 20, "xscale": 0.68},
"Arab": {"px": 20.0, "baseline": 18, "xscale": 0.80},
"Deva": {"px": 18.0, "baseline": 16, "xscale": 0.80},
"Thai": {"px": 19.0, "baseline": 17, "xscale": 0.75},
"Ethi": {"px": 19.0, "baseline": 19, "xscale": 0.75},
"Hang": {"px": 19.0, "baseline": 17, "xscale": 1.0},
"Hani": {"px": 19.0, "baseline": 17, "xscale": 1.0},
"Jpan": {"px": 19.0, "baseline": 17, "xscale": 1.0},
}
BATTLE_RENDER = {"battle_px": 20.0, "battle_baseline": 17, "battle_xscale": 0.55}
_DEFAULT_RENDER = {"px": 20.0, "baseline": 18, "xscale": 0.8}
# Noto families that cover each script (free, SIL OFL)
NOTO: Dict[str, List[str]] = {
"Latn": ["Noto Sans", "Noto Serif"], "Cyrl": ["Noto Sans", "Noto Serif"],
"Grek": ["Noto Sans", "Noto Serif"], "Armn": ["Noto Sans Armenian"],
"Geor": ["Noto Sans Georgian"], "Hebr": ["Noto Sans Hebrew"],
"Arab": ["Noto Sans Arabic", "Noto Naskh Arabic"], "Deva": ["Noto Sans Devanagari"],
"Thai": ["Noto Sans Thai"], "Ethi": ["Noto Sans Ethiopic"],
"Hang": ["Noto Sans KR"], "Hani": ["Noto Sans SC", "Noto Sans TC"],
"Jpan": ["Noto Sans JP"],
}
# Characters a font must have to count as covering a script (system_fonts).
_PROBE: Dict[str, str] = {
"Latn": "ąćęłńśźżčďěňřšťůžőűășțğışđĉĝĥĵŝŭ",
"Cyrl": "абвгдеёжзийклмнопрстуфхцчшщъыьэюяАБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯіїєґ",
"Grek": "αβγδεζηθικλμνξοπρστυφχψωςάέήίόύώΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩ",
"Armn": "ԱԲԳԴԵԶԷԸԹԺԻԼԽԾԿՀՁՂՃՄՅՆՇՈՉՊՋՌՍՎՏՐՑՒՓՔՕՖաբգդեզէըթժիլխծկհձղճմյնշոչպջռսվտրցւփքօֆ",
"Geor": "აბგდევზთიკლმნოპჟრსტუფქღყშჩცძწჭხჯჰ",
"Hebr": "אבגדהוזחטיכךלמםנןסעפףצץקרשת",
"Arab": "ءآأؤإئابةتثجحخدذرزسشصضطظعغفقكلمنهوىيپچژگکی،؟",
"Deva": "अआइईउऊएऐओऔकखगघङचछजझञटठडढणतथदधनपफबभमयरलवशषसहािीुूेैोौंः्।",
"Thai": "กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรลวศษสหฬอฮะาำิีึืุูเแโใไ่้๊๋",
"Ethi": "ሀለሐመሠረሰሸቀበተቸኀነኘአከኸወዐዘዠየደጀገጠጨጰጸፀፈፐ።",
"Hang": "가나다라마바사아자차카타파하한국어안녕세요",
"Hani": "的一是不了人我在有他这中大来上国个到说们为子和你地出道也时年",
"Jpan": "あいうえおかきくけこアイウエオカキクケコ日本語漢字",
}
# ---------------------------------------------------------------------------
# profiles
# ---------------------------------------------------------------------------
# (code, English name, endonym, script, rtl, alphabet beyond ASCII, sample,
# kind for non-Latin scripts). Latin kinds are computed from the alphabet.
_RAW = [
("fr", "French", "Français", "Latn", False, "àâæçéèêëîïôœùûüÿÀÂÆÇÉÈÊËÎÏÔŒÙÛÜŸ«»",
"Portez ce vieux whisky au juge blond qui fume. « Où est KOS-MOS ? »"),
("es", "Spanish", "Español", "Latn", False, "áéíñóúüÁÉÍÑÓÚÜ¿¡«»",
"El veloz murciélago hindú comía feliz cardillo y kiwi. ¿Dónde está?"),
("de", "German", "Deutsch", "Latn", False, "äöüßÄÖÜ„“",
"Victor jagt zwölf Boxkämpfer quer über den großen Sylter Deich."),
("it", "Italian", "Italiano", "Latn", False, "àèéìíîòóùúÀÈÉÌÍÎÒÓÙÚ",
"Ma la volpe col suo balzo ha raggiunto il quieto Fido. Perché è così?"),
("pt", "Portuguese", "Português", "Latn", False, "áâãàçéêíóôõúÁÂÃÀÇÉÊÍÓÔÕÚ",
"Luís argüia à Júlia que «brações, fé, chá, óxido, pôr, zângão» eram palavras."),
("pt-BR", "Portuguese (Brazil)", "Português (Brasil)", "Latn", False,
"áâãàçéêíóôõúÁÂÃÀÇÉÊÍÓÔÕÚ", "À noite, vovô Kowalsky vê o ímã cair no pé do pinguim."),
("nl", "Dutch", "Nederlands", "Latn", False, "éëïöüèáóúÉËÏÖÜ",
"Pa's wijze lynx bezag vroom het fikse aquaduct. Één, twee, drieëntwintig."),
("ca", "Catalan", "Català", "Latn", False, "àçéèíïòóúüÀÇÉÈÍÏÒÓÚÜ·",
"Jove xef, porti whisky amb quinze glaçons d'hidrogen, coi! Col·lega."),
("sv", "Swedish", "Svenska", "Latn", False, "åäöÅÄÖ",
"Flygande bäckasiner söka hwila på mjuka tuvor."),
("da", "Danish", "Dansk", "Latn", False, "æøåÆØÅ",
"Høj bly gom vandt fræk sexquiz på wc."),
("no", "Norwegian", "Norsk", "Latn", False, "æøåÆØÅ",
"Vår sære Zulu fra badeøya spilte jo whist og quickstep i min taxi."),
("fi", "Finnish", "Suomi", "Latn", False, "äöåšžÄÖÅŠŽ",
"Törkylempijävongahdus. Šakki ja žirafi."),
("is", "Icelandic", "Íslenska", "Latn", False, "áðéíóúýþæöÁÐÉÍÓÚÝÞÆÖ",
"Kæmi ný öxi hér, ykist þjófum nú bæði víl og ádrepa."),
("ga", "Irish", "Gaeilge", "Latn", False, "áéíóúÁÉÍÓÚ",
"D'fhuascail Íosa Úrmhac na hÓighe Beannaithe pór Éava agus Ádhaimh."),
("af", "Afrikaans", "Afrikaans", "Latn", False, "êëéèîïôûÊËÉÈÎÏÔÛ",
"Sê vir die mense: môre is ’n nuwe dag."),
("sq", "Albanian", "Shqip", "Latn", False, "çëÇË",
"Unë jam KOS-MOS. Çfarë dëshironi?"),
("id", "Indonesian", "Bahasa Indonesia", "Latn", False, "",
"Saya KOS-MOS. Apa yang bisa saya bantu?"),
("eo", "Esperanto", "Esperanto", "Latn", False, "ĉĝĥĵŝŭĈĜĤĴŜŬ",
"Eĥoŝanĝo ĉiuĵaŭde. Laŭ Ludoviko Zamenhof bongustas freŝa ĉeĥa manĝaĵo."),
("pl", "Polish", "Polski", "Latn", False, "ąćęłńóśźżĄĆĘŁŃÓŚŹŻ",
"Zażółć gęślą jaźń. Pchnąć w tę łódź jeża lub ośm skrzyń fig."),
("cs", "Czech", "Čeština", "Latn", False, "áčďéěíňóřšťúůýžÁČĎÉĚÍŇÓŘŠŤÚŮÝŽ",
"Příliš žluťoučký kůň úpěl ďábelské ódy."),
("sk", "Slovak", "Slovenčina", "Latn", False, "áäčďéíĺľňóôŕšťúýžÁÄČĎÉÍĹĽŇÓÔŔŠŤÚÝŽ",
"Kŕdeľ šťastných ďatľov učí pri ústí Váhu mĺkveho koňa obhrýzať kôru."),
("sl", "Slovenian", "Slovenščina", "Latn", False, "蚞ȊŽ",
"Hišničin bratec vzgaja polžke še čez zimo."),
("hr", "Croatian", "Hrvatski", "Latn", False, "čćđšžČĆĐŠŽ",
"Gojazni đačić s biciklom drži hmelj i finu vatu u džepu nošnje."),
("hu", "Hungarian", "Magyar", "Latn", False, "áéíóöőúüűÁÉÍÓÖŐÚÜŰ",
"Árvíztűrő tükörfúrógép."),
("ro", "Romanian", "Română", "Latn", False, "ăâîșțĂÂÎȘȚ",
"Înjurând pițigăiat, zoofobul comandă vexat whisky și tequila."),
("tr", "Turkish", "Türkçe", "Latn", False, "çğıİöşüÇĞÖŞÜ",
"Pijamalı hasta yağız şoföre çabucak güvendi."),
("et", "Estonian", "Eesti", "Latn", False, "äöõüšžÄÖÕÜŠŽ",
"Põdur Zagrebi tšellomängija-följetonist Ciqo külmetas kehvas garaažis."),
("lt", "Lithuanian", "Lietuvių", "Latn", False, "ąčęėįšųūžĄČĘĖĮŠŲŪŽ",
"Įlinkdama fechtuotojo špaga sublykčiojusi pragręžė apvalų arbūzą."),
("lv", "Latvian", "Latviešu", "Latn", False, "āčēģīķļņšūžĀČĒĢĪĶĻŅŠŪŽ",
"Glāžšķūņa rūķīši dzērumā čiepj Baha koncertflīģeļu vākus."),
("vi", "Vietnamese", "Tiếng Việt", "Latn", False,
"àáảãạăằắẳẵặâầấẩẫậèéẻẽẹêềếểễệìíỉĩịòóỏõọôồốổỗộơờớởỡợùúủũụưừứửữựỳýỷỹỵđĐ",
"Tôi là KOS-MOS. Bạn cần giúp gì không?"),
("ja", "Japanese", "日本語", "Jpan", False, "", "こんにちは、シオン。漢字と仮名、そして叡智。",
"japanese"),
("ru", "Russian", "Русский", "Cyrl", False, _PROBE["Cyrl"][:66],
"Съешь же ещё этих мягких французских булок, да выпей чаю.", "script"),
("uk", "Ukrainian", "Українська", "Cyrl", False,
"абвгґдеєжзиіїйклмнопрстуфхцчшщьюяАБВГҐДЕЄЖЗИІЇЙКЛМНОПРСТУФХЦЧШЩЬЮЯ’",
"Чуєш їх, доцю, га? Кумедна ж ти, прощайся без ґольфів!", "script"),
("bg", "Bulgarian", "Български", "Cyrl", False,
"абвгдежзийклмнопрстуфхцчшщъьюяАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЬЮЯ",
"Жълтата дюля беше щастлива, че пухът, който цъфна, замръзна като гьон.", "script"),
("sr", "Serbian (Cyrillic)", "Српски", "Cyrl", False,
"абвгдђежзијклљмнњопрстћуфхцчџшАБВГДЂЕЖЗИЈКЛЉМНЊОПРСТЋУФХЦЧЏШ",
"Фијуче ветар у шибљу, леди пасаже и куће иза њих и гунђа у оџацима.", "script"),
("el", "Greek", "Ελληνικά", "Grek", False, _PROBE["Grek"],
"Ξεσκεπάζω την ψυχοφθόρα βδελυγμία.", "script"),
("hy", "Armenian", "Հայերեն", "Armn", False, _PROBE["Armn"],
"Բարեւ, աշխարհ։", "script"),
("ka", "Georgian", "ქართული", "Geor", False, _PROBE["Geor"],
"გამარჯობა, სამყარო!", "script"),
("ar", "Arabic", "العربية", "Arab", True, _PROBE["Arab"][:44],
"مرحبا بالعالم! أنا KOS-MOS (3).", "script"),
("fa", "Persian", "فارسی", "Arab", True, _PROBE["Arab"],
"سلام دنیا! من KOS-MOS هستم.", "script"),
("he", "Hebrew", "עברית", "Hebr", True, _PROBE["Hebr"],
"שלום עולם! אני KOS-MOS.", "script"),
("hi", "Hindi", "हिन्दी", "Deva", False, _PROBE["Deva"],
"नमस्ते दुनिया! मैं KOS-MOS हूँ।", "script"),
("th", "Thai", "ไทย", "Thai", False, _PROBE["Thai"],
"สวัสดีชาวโลก", "script"),
("am", "Amharic", "አማርኛ", "Ethi", False, _PROBE["Ethi"],
"ሰላም ዓለም።", "script"),
("ko", "Korean", "한국어", "Hang", False, "", "안녕하세요, 세계! 저는 KOS-MOS입니다.", "script"),
("zh-Hans", "Chinese (Simplified)", "简体中文", "Hani", False, "",
"你好,世界!我是KOS-MOS。", "script"),
("zh-Hant", "Chinese (Traditional)", "繁體中文", "Hani", False, "",
"你好,世界!我是KOS-MOS。", "script"),
]
# right-to-left scripts (used for custom "other" targets too)
RTL_SCRIPTS = {"Arab", "Hebr", "Syrc", "Thaa", "Nkoo", "Adlm", "Mand", "Samr", "Rohg"}
def _native_both(ch: str) -> bool:
return tc.draws_natively(ch, tc.FIELD, tc.FONT1) and tc.draws_natively(ch, tc.FIELD, tc.FONT0)
def _kind_of(script: str, alphabet: str, given: Optional[str]) -> Tuple[str, str]:
"""(kind, letters the retail fonts lack) for a profile."""
if script != "Latn":
return given or "script", ""
lacking = "".join(c for c in dict.fromkeys(alphabet) if not _native_both(c))
return ("builtin" if not lacking else "script-hybrid"), lacking
def _make_targets() -> List[dict]:
out = []
for rec in _RAW:
code, name, endo, script, rtl, alphabet, sample = rec[:7]
given = rec[7] if len(rec) > 7 else None
kind, lacking = _kind_of(script, alphabet, given)
out.append({
"code": code, "name": name, "endonym": endo, "kind": kind, "script": script,
"rtl": rtl, "alphabet": alphabet, "lacking": lacking, "sample": sample,
"fonts": list(NOTO.get(script, ["Noto Sans"])),
"render": dict(RENDER.get(script, _DEFAULT_RENDER)),
})
out.append({
"code": "other", "name": "Other (custom script)", "endonym": "", "kind": "script",
"script": "", "rtl": False, "alphabet": "", "lacking": "", "sample": "",
"fonts": [], "render": dict(_DEFAULT_RENDER),
})
return out
# ---------------------------------------------------------------------------
# the language registry (txlangs.py): every other language and written form
# ---------------------------------------------------------------------------
# The 47 profiles above are the long-tested ones; txlangs adds the rest (382
# lines: Cherokee, Inuktitut, Navajo, Hawaiian, Yoruba, Tifinagh, N'Ko, Adlam,
# ...). Each registry line becomes a profile of the same shape; its kind is
# computed from its letters exactly as above. A registry line for a language
# that already has a profile only adds its regions and note.
SCRIPT_NAMES: Dict[str, str] = {
"Latn": "Latin", "Cyrl": "Cyrillic", "Grek": "Greek", "Armn": "Armenian", "Geor": "Georgian",
"Hebr": "Hebrew", "Arab": "Arabic", "Syrc": "Syriac", "Thaa": "Thaana", "Nkoo": "N'Ko",
"Deva": "Devanagari", "Beng": "Bengali", "Guru": "Gurmukhi", "Gujr": "Gujarati", "Orya": "Odia",
"Taml": "Tamil", "Telu": "Telugu", "Knda": "Kannada", "Mlym": "Malayalam", "Sinh": "Sinhala",
"Thai": "Thai", "Laoo": "Lao", "Tibt": "Tibetan", "Mymr": "Myanmar", "Ethi": "Ethiopic",
"Cher": "Cherokee", "Cans": "Canadian syllabics", "Khmr": "Khmer", "Mong": "Mongolian",
"Tglg": "Baybayin", "Bugi": "Lontara", "Bali": "Balinese", "Sund": "Sundanese", "Java": "Javanese",
"Olck": "Ol Chiki", "Mtei": "Meitei Mayek", "Vaii": "Vai", "Tfng": "Tifinagh", "Adlm": "Adlam",
"Yiii": "Yi", "Bamu": "Bamum", "Osge": "Osage", "Hmnp": "Nyiakeng Puachue Hmong", "Lisu": "Lisu",
"Cakm": "Chakma", "Lana": "Tai Tham", "Tavt": "Tai Viet", "Sylo": "Syloti Nagri", "Limb": "Limbu",
"Copt": "Coptic", "Osma": "Osmanya", "Rohg": "Hanifi Rohingya", "Hang": "Hangul", "Hani": "Han",
"Jpan": "Japanese", "Kana": "Katakana",
}
for _sc, _nm in SCRIPT_NAMES.items():
NOTO.setdefault(_sc, ["Noto Sans " + _nm.replace("'", "").replace(" syllabics", " Canadian Aboriginal")
if _sc != "Cans" else "Noto Sans Canadian Aboriginal"])
def _generated(name: str) -> str:
"""Letter sets too big to type: '@ko' (KS X 1001 Hangul), '@zh-Hans'
(GB 2312 level 1), '@zh-Hant' (Big5 frequent), '@ja' (JIS level 1 kanji +
kana), '@iu' / '@cr' / '@oj' (Canadian syllabics by Unicode name)."""
import unicodedata
def rows(codec, hi, lo=(0xA1, 0xFE)):
out = []
for a in range(hi[0], hi[1] + 1):
for b in range(lo[0], lo[1] + 1):
try:
out.append(bytes((a, b)).decode(codec))
except UnicodeDecodeError:
pass
return "".join(out)
if name == "ko":
return rows("euc_kr", (0xB0, 0xC8))
if name == "zh-Hans":
return rows("gb2312", (0xB0, 0xD7))
if name == "zh-Hant":
return rows("big5", (0xA4, 0xC6), (0x40, 0xFE))
if name == "ja":
kana = "".join(chr(c) for c in range(0x3041, 0x3097)) + "".join(chr(c) for c in range(0x30A1, 0x30FB))
return kana + rows("euc_jp", (0xB0, 0xCF))
sets = getattr(_txlangs(), "CANS_SETS", {}).get(name)
if sets:
out = []
for c in sets["consonants"]:
for v in sets["vowels"]:
for nm in (f"CANADIAN SYLLABICS {c}{v}",):
try:
out.append(unicodedata.lookup(nm))
except KeyError:
pass
for f in sets["finals"]:
for nm in (f"CANADIAN SYLLABICS FINAL {f}", f"CANADIAN SYLLABICS {f}"):
try:
out.append(unicodedata.lookup(nm))
break
except KeyError:
pass
return "".join(dict.fromkeys(out))
return ""
def _txlangs():
try:
import txlangs
return txlangs
except ImportError:
return None
def _core(script: str) -> str:
import unicodedata
core = getattr(_txlangs(), "SCRIPT_CORE", {}).get(script, "")
if isinstance(core, str):
return _generated(core[1:]) if core.startswith("@") else core
out = []
for lo, hi in core:
for cp in range(lo, hi + 1):
ch = chr(cp)
if unicodedata.category(ch)[0] in "LM":
out.append(ch)
return "".join(out)
def _letters(script: str, field: str) -> str:
"""The registry's letters field -> the alphabet (see txlangs' docstring)."""
field = field.strip()
base = ""
extra = []
for tok in field.split(" ") if field else []:
if tok.startswith("@"):
base += _generated(tok[1:])
elif tok.startswith("="):
base += tok[1:]
else:
extra.append(tok)
explicit = base != ""
extra_s = "".join(extra)
if script == "Latn":
ups = "".join(c.upper() for c in extra_s if len(c.upper()) == 1 and c.upper() != c)
return "".join(dict.fromkeys(extra_s + ups))
if not explicit:
base = _core(script)
letters = base + extra_s
ups = "".join(c.upper() for c in letters if len(c.upper()) == 1 and c.upper() != c)
return "".join(dict.fromkeys(letters + ups))
def _registry_targets(have: Dict[str, dict]) -> List[dict]:
L = _txlangs()
if L is None:
return []
samples = getattr(L, "SAMPLES", {})
vertical = getattr(L, "VERTICAL", {})
out = []
for line in L.DATA.splitlines():
line = line.strip()
if not line or line.startswith("#"):
continue
f = (line.split("|", 6) + [""] * 7)[:7]
code, name, endo, scripts, letters, regions, note = (x.strip() for x in f)
sc = (scripts.split() or ["Latn"])[0]
extra = {"regions": regions.split(), "scripts": scripts.split()}
notes = " ".join(x for x in (note, vertical.get(sc, "")) if x)
if notes:
extra["notes"] = notes
if code.lower() in have:
have[code.lower()].update(extra)
continue
alphabet = _letters(sc, letters)
if sc == "Latn":
# letters of the language's own name belong to its alphabet too (Kɪsukuma)
own = "".join(c for c in endo if c.isalpha() and ord(c) > 0x7F)
alphabet = "".join(dict.fromkeys(alphabet + own + "".join(
c.upper() for c in own if len(c.upper()) == 1)))
given = "japanese" if sc == "Jpan" else None
kind, lacking = _kind_of(sc, alphabet, given)
sample = samples.get(code, "")
if not sample:
# no sample sentence on file: the language's own name and some of its letters
show = "".join(c for c in alphabet if c.islower() or not c.isupper())[:24]
sample = (endo + " · KOS-MOS · " + show).strip(" ·")
out.append(dict({
"code": code, "name": name, "endonym": endo, "kind": kind, "script": sc,
"rtl": sc in RTL_SCRIPTS, "alphabet": alphabet, "lacking": lacking, "sample": sample,
"fonts": list(NOTO.get(sc, ["Noto Sans"])),
"render": dict(RENDER.get(sc, _DEFAULT_RENDER)), "registry": True,
}, **extra))
return out
def _all_targets() -> List[dict]:
base = _make_targets()
other = base.pop() # "other" stays last
have = {t["code"].lower(): t for t in base}
for t in base:
t.setdefault("script_name", SCRIPT_NAMES.get(t["script"], t["script"]))
reg = _registry_targets(have)
for t in reg:
t["script_name"] = SCRIPT_NAMES.get(t["script"], t["script"])
reg.sort(key=lambda t: t["name"].lower())
return base + reg + [other]
TARGETS: List[dict] = _all_targets()
_BY_CODE = {t["code"].lower(): t for t in TARGETS}
def languages(query: str = "") -> List[dict]:
"""Every target language (the 47 tested profiles first, then the registry
A-Z), filtered by code, English name, own name, script or region."""
q = (query or "").strip().lower()
out = []
for t in TARGETS:
if t["code"] == "other":
continue
hay = " ".join([t["code"], t["name"], t.get("endonym", ""), t.get("script_name", ""),
" ".join(t.get("regions", []))]).lower()
if not q or q in hay or t["code"].lower() == q:
out.append(t)
return out
def profile(code: str) -> Optional[dict]:
"""The TARGETS entry for a language code (case-insensitive; "pt_BR" and
"pt-br" both find pt-BR; a region falls back to the base language)."""
if not code:
return None
c = code.replace("_", "-").lower()
return _BY_CODE.get(c) or _BY_CODE.get(c.split("-", 1)[0])
# ---------------------------------------------------------------------------
# project target
# ---------------------------------------------------------------------------
_TARGET_KEYS = {
"code": str, "kind": str, "script": str, "language": str, "rtl": bool, "font": str,
"face": int, "px": float, "baseline": int, "xscale": float, "align": str, "wrap": int,
"battle_font": str, "battle_face": int, "battle_px": float, "battle_baseline": int,
"battle_xscale": float,
}
def normalise_target(t: dict) -> dict:
"""Validate ``project["target"]``; returns a clean copy with only known keys:
code language code ("ru", "ar", "ja", "pl", "other", ...)
kind builtin | script-hybrid | japanese | script (default: the profile's)
script ISO 15924 code ("Cyrl"); required for kind script with code "other"
language BCP-47 tag for shaping (default: code)
rtl right-to-left paragraphs (default: the profile's)
font path of the TrueType/OpenType font new glyphs are drawn from
face face index inside a .ttc (default 0)
px, baseline, xscale glyph size, baseline row, horizontal squeeze
(defaults: RENDER[script])
align "left" | "right" (right needs a wrap width; RTL dialogue)
wrap px to wrap translated lines at (0 = leave wrapping to the game;
default: 0 for left-to-right, the row's guide / 370 px for RTL)
battle_font, battle_face, battle_px, battle_baseline, battle_xscale
the same for the battle HUD grid (default: font/face, 13 px)
"""
if not isinstance(t, dict):
raise TargetError("target must be an object")
out: dict = {}
for k, typ in _TARGET_KEYS.items():
if k not in t or t[k] is None or t[k] == "":
continue
v = t[k]
try:
if typ is bool:
if not isinstance(v, bool):
raise ValueError
elif typ is int:
if isinstance(v, bool) or int(v) != float(v):
raise ValueError
v = int(v)
elif typ is float:
if isinstance(v, bool):
raise ValueError
v = float(v)
else:
v = str(v)
except (TypeError, ValueError):
raise TargetError(f"{k}: expected {typ.__name__}, got {v!r}") from None
out[k] = v
if "kind" in out and out["kind"] not in KINDS:
raise TargetError(f"kind must be one of {', '.join(KINDS)}, not {out['kind']!r}")
if "align" in out and out["align"] not in ("left", "right"):
raise TargetError("align must be 'left' or 'right'")
for k in ("face", "battle_face", "wrap"):
if out.get(k, 0) < 0:
raise TargetError(f"{k} must not be negative")
for k in ("px", "battle_px"):
if k in out and not (6.0 <= out[k] <= 40.0):
raise TargetError(f"{k} must be between 6 and 40")
for k in ("xscale", "battle_xscale"):
if k in out and not (0.3 <= out[k] <= 1.5):
raise TargetError(f"{k} must be between 0.3 and 1.5")
if "baseline" in out and not (8 <= out["baseline"] <= 23):
raise TargetError("baseline must be a cell row 8..23")
if "battle_baseline" in out and not (6 <= out["battle_baseline"] <= 17):
raise TargetError("battle_baseline must be a cell row 6..17")
return out
def resolve_target(project: dict) -> dict:
"""The full target a build uses: the profile of ``target.code`` (or of
``project["language"]``) with the project's own settings on top. An
unknown language code with no target is "builtin" (the editor's
original behaviour: the codec decides what can be written)."""
given = normalise_target(project.get("target") or {})
code = given.get("code") or project.get("language") or ""
prof = profile(code) or {}
script = given.get("script") or prof.get("script") or ""
kind = given.get("kind") or prof.get("kind") or ("script" if script and script != "Latn"
else "builtin")
render = dict(RENDER.get(script, _DEFAULT_RENDER))
t = {"code": code, "kind": kind, "script": script,
"language": given.get("language") or (code if code and code != "other" else ""),
"rtl": given.get("rtl", prof.get("rtl", script in RTL_SCRIPTS)),
"font": given.get("font", ""), "face": given.get("face", 0),
"px": given.get("px", render["px"]), "baseline": given.get("baseline", render["baseline"]),
"xscale": given.get("xscale", render["xscale"]),
"align": given.get("align", "left"), "wrap": given.get("wrap"),
"name": prof.get("name") or code or "?"}
t["battle_font"] = given.get("battle_font", t["font"])
t["battle_face"] = given.get("battle_face", t["face"] if "battle_font" not in given else 0)
for k, v in BATTLE_RENDER.items():
t[k] = given.get(k, v)
return t
# ---------------------------------------------------------------------------
# what the retail fonts draw
# ---------------------------------------------------------------------------
def _jis_row(ch: str) -> int:
try:
b = ch.encode("euc_jp")
except UnicodeEncodeError:
return 0
return b[0] if len(b) == 2 else 0
def native_predicate(kind: str, font: str = tc.FIELD, face: str = tc.FONT1) -> Callable[[str], bool]:
"""``ch -> bool``: does the build leave ``ch`` to the retail font?
builtin / japanese: everything ``txcodec.draws_natively`` accepts.
script / script-hybrid: the same minus JIS rows A6/A7 (Greek, Cyrillic:
the retail font has them as fixed 20 px full-width kanji-path cells, so
a Greek or Russian translation gets proportional glyphs drawn instead)."""
def native(ch: str) -> bool:
if not tc.draws_natively(ch, font, face):
return False
if kind in ("script", "script-hybrid") and font == tc.FIELD and ord(ch) >= 0x80 \
and ch not in tc.FACE_MAPS[face] and _jis_row(ch) in (0xA6, 0xA7):
return False
return True
return native
def coverage(texts, target, font: str = tc.FIELD, face: str = tc.FONT1,
ttf: Optional[str] = None, ttf_face: int = 0) -> dict:
"""Which characters of ``texts`` (a string or an iterable of strings) the
retail font draws, and which a build must draw from a TrueType font.
``target`` is a profile, a resolved target or just a kind string.
-> {"native": str, "glyph": str, "folded": str, "impossible": str,
"missing_in_font": str|None, "counts": {ch: n}}
native drawn by the retail font as is
glyph need a new glyph (kinds other than builtin; field and battle font)
folded builtin battle/tag text: written as the nearest ASCII (warning)
impossible no build can draw them here (builtin kind; the tag font;
raw control characters)
missing_in_font glyph characters ``ttf`` has no glyph for (None
without a ttf); needs fonttools
Protected tokens (⟦XX⟧, /[..] tags) are not counted."""
kind = target if isinstance(target, str) else (target or {}).get("kind", "builtin")
if isinstance(texts, str):
texts = [texts]
native = native_predicate(kind, font, face)
counts: Counter = Counter()
for t in texts:
t = unicodedata.normalize("NFC", tc._TOKRUN_RE.sub("", tc._TAG_RE.sub("", t or "")))
counts.update(c for c in t if c != "\n")
out = {"native": [], "glyph": [], "folded": [], "impossible": []}
for ch in sorted(counts):
if native(ch):
out["native"].append(ch)
elif ord(ch) < 0x20 or 0x7F <= ord(ch) < 0xA0 or tc.glyph_code(ch) is not None:
out["impossible"].append(ch)
elif font == tc.ASCII:
f = tc.fold_ascii(ch)
ok = f is not None and all(c in tc.TAG_GLYPHS for c in f)
out["folded" if ok else "impossible"].append(ch)
elif kind == "builtin":
if font == tc.BATTLE and tc.fold_ascii(ch) is not None:
out["folded"].append(ch)
else:
out["impossible"].append(ch)
elif unicodedata.category(ch) in ("Zl", "Zp", "Cf", "Cc", "Co", "Cs", "Cn"):
out["impossible"].append(ch)
else:
out["glyph"].append(ch)
res = {k: "".join(v) for k, v in out.items()}
res["counts"] = dict(counts)
res["missing_in_font"] = None
if ttf and res["glyph"]:
cmap = font_cmap(ttf, ttf_face)
if cmap is not None:
res["missing_in_font"] = "".join(
c for c in res["glyph"] if ord(c) not in cmap
and unicodedata.category(c) not in ("Mn", "Me"))
return res
# ---------------------------------------------------------------------------
# fonts on this machine
# ---------------------------------------------------------------------------
def shaping_available() -> Tuple[bool, str]:
"""(True, versions) when fonttools and uharfbuzz import, else (False, how to fix)."""
try:
import fontTools
import uharfbuzz
except ImportError as e:
return False, (f"the kit's font packages are missing ({e.name}): new scripts are drawn "
f"from TrueType fonts with fonttools and uharfbuzz, which the kit "
f"requires (requirements.txt). The launcher installs them; or run "
f"python3 -m pip install --user -r requirements.txt")
return True, f"fonttools {fontTools.version}, uharfbuzz {uharfbuzz.__version__}"
def font_dirs() -> List[Path]:
"""System and user font folders of this platform (existing ones)."""
home = Path.home()
if sys.platform == "darwin":
c = [Path("/System/Library/Fonts"), Path("/System/Library/Fonts/Supplemental"),
Path("/Library/Fonts"), home / "Library/Fonts"]
elif sys.platform == "win32":
win = Path(os.environ.get("WINDIR", r"C:\Windows"))
c = [win / "Fonts"]
if os.environ.get("LOCALAPPDATA"):
c.append(Path(os.environ["LOCALAPPDATA"]) / "Microsoft/Windows/Fonts")
else:
c = [Path("/usr/share/fonts"), Path("/usr/local/share/fonts"),
home / ".fonts", home / ".local/share/fonts"]
return [d for d in c if d.is_dir()]
_FONT_EXT = (".ttf", ".otf", ".ttc", ".otc")
# fonts whose cmap claims everything but whose glyphs are placeholders
_FONT_SKIP = re.compile(r"lastresort|braille|emoji", re.I)
def _quiet_fonttools() -> None:
import logging
logging.getLogger("fontTools").setLevel(logging.ERROR)
def _open_faces(path: str):
from fontTools.ttLib import TTCollection, TTFont
_quiet_fonttools()
if path.lower().endswith((".ttc", ".otc")):
return list(TTCollection(path, lazy=True).fonts)
return [TTFont(path, lazy=True)]
def font_cmap(path: str, face: int = 0) -> Optional[Set[int]]:
"""Code points ``path`` (face ``face``) maps, or None without fonttools."""
try:
faces = _open_faces(str(path))
except ImportError:
return None
except Exception as e:
raise TargetError(f"cannot read the font {path}: {e}") from None
if face >= len(faces):
raise TargetError(f"{path} has {len(faces)} face(s); face {face} does not exist")
return set((faces[face].getBestCmap() or {}).keys())
def _name(ft, nid: int) -> str:
try:
n = ft["name"].getDebugName(nid)
return n or ""
except Exception:
return ""
_FONT_INDEX: Optional[List[dict]] = None
def _font_index() -> List[dict]:
"""Every outline font face installed here, with the scripts it covers
(cached in ~/.cache/xs1-txeditor/fonts.json by path, size and mtime)."""
global _FONT_INDEX
if _FONT_INDEX is not None:
return _FONT_INDEX
cache_path = CACHE_DIR / "fonts-v1.json"
try:
cache = json.loads(cache_path.read_text(encoding="utf-8"))
except (OSError, ValueError):
cache = {}
files = []
for d in font_dirs():
for root, _dirs, names in os.walk(d):
for n in sorted(names):
if n.lower().endswith(_FONT_EXT) and not _FONT_SKIP.search(n):
files.append(os.path.join(root, n))
out: List[dict] = []
fresh = {}
for p in sorted(set(files)):
try:
st = os.stat(p)
except OSError:
continue
stamp = f"{st.st_size}:{int(st.st_mtime)}"
hit = cache.get(p)
if hit and hit.get("stamp") == stamp:
faces = hit["faces"]
else:
faces = []
try:
for i, ft in enumerate(_open_faces(p)):
if not any(t in ft for t in ("glyf", "CFF ", "CFF2")):
continue
cmap = ft.getBestCmap() or {}
scripts = [s for s, probe in _PROBE.items()
if all(ord(c) in cmap for c in probe)]
faces.append({"face": i, "family": _name(ft, 1), "style": _name(ft, 2),
"scripts": scripts})
except ImportError:
return []
except Exception:
faces = []
fresh[p] = {"stamp": stamp, "faces": faces}
for f in faces:
out.append({"path": p, **f, "noto": "noto" in (f["family"] + p).lower()})
try:
CACHE_DIR.mkdir(parents=True, exist_ok=True)
if fresh != cache:
cache_path.write_text(json.dumps(fresh, ensure_ascii=False), encoding="utf-8")
except OSError:
pass
_FONT_INDEX = out
return out
def system_fonts(script: Optional[str] = None, chars: Optional[str] = None) -> List[dict]:
"""Installed outline fonts: [{path, face, family, style, noto, scripts}],
Noto first, then by family. ``script`` keeps faces covering that script's
probe letters (``_PROBE``); ``chars`` keeps faces that map every one of
those characters (opens the candidate fonts again). Empty without
fonttools."""
fonts = _font_index()
if script:
fonts = [f for f in fonts if script in f["scripts"]]
if chars:
need = {ord(c) for c in chars if unicodedata.category(c) not in ("Mn", "Me")}
keep = []
for f in fonts:
try:
cmap = font_cmap(f["path"], f["face"])
except TargetError:
continue
if cmap is not None and need <= cmap:
keep.append(f)
fonts = keep
# system-internal faces (".SF ...") and calligraphic Nastaliq are poor
# first choices for 20 px cells: list them last
return sorted(fonts, key=lambda f: (f["family"].startswith(".") or "nastaliq" in f["family"].lower(),
not f["noto"], f["style"].lower() not in ("regular", "w3"),
f["family"].lower(), f["style"].lower(),
f["path"], f["face"]))
def suggest_fonts(target: dict, chars: Optional[str] = None) -> dict:
"""{"noto": [family names to download], "installed": system_fonts(...)[:12]}."""
script = target.get("script") or ""
return {"noto": list(NOTO.get(script, ["Noto Sans"])),
"installed": system_fonts(script or None, chars)[:12]}
# ---------------------------------------------------------------------------
# retail usage: cells no new glyph may take
# ---------------------------------------------------------------------------
class Usage:
"""Cells retail text draws. prop: proportional slots; wide: kanji-area
cells (752..3743); battle_cells / battle_bytes: battle-grid cells and
table bytes the retail battle strings use."""
def __init__(self):
self.prop: Set[int] = set()
self.wide: Set[int] = set()
self.battle_cells: Set[int] = set()
self.battle_bytes: Set[int] = set()
self.rows = 0
def _field_cells(data: bytes, usage: Usage) -> None:
i, n = 0, len(data)
while i < n:
b = data[i]
if b < 0x20:
i += max(1, fontmod.control_length(data, i))
continue
if b == 0x23 and i + 2 < n: # engine escape #xx / ##
if data[i + 1] == 0x23:
code = fontmod.ascii_to_code(0x23)
i += 2
else:
xx = 0
for c in data[i + 1:i + 3]:
xx = xx * 16 + (int(chr(c), 16) if chr(c) in "0123456789abcdefABCDEF" else 0)
code = tc.block_code(xx)
i += 3
elif b < 0x80:
code = fontmod.ascii_to_code(b) if b < 0x7F else fontmod.ascii_to_code(0x20)
i += 1
else:
if i + 1 >= n:
break
code = (b << 8) | data[i + 1]
i += 2
p = fontmod.prop_index(code)
if p >= 0:
usage.prop.add(p)
else:
c = fontmod.cell_of_code(code)
if 752 <= c <= 3743:
usage.wide.add(c)
def _battle_cells(data: bytes, cells: Set[int], raw_bytes: Set[int]) -> None:
import statfont
i = 0
while i < len(data):
b = data[i]
if b == 0x23:
m = re.match(rb"[0-9A-Fa-f]{1,2}", data[i + 1:i + 3])
if m:
cells.add(int(m.group(0), 16))
i += 3
continue
if b & 0x80:
i += 2
continue
raw_bytes.add(b)
k = statfont.TABLE.find(chr(b))
if k >= 0:
cells.add(k)
i += 1
_USAGE: Dict[str, Usage] = {}
def retail_usage(retail: str, log: Callable[[str], None] = lambda m: None) -> Usage:
"""Measure what the retail text the game shows draws: every row of the
four families that is not hidden (locked rows too; evt ``/[...]`` tags
are control language and are not measured). Hidden rows are debug prints,
Java code, Japanese developer pages (one is a font test page that walks
the whole block) and binary that only looks like text: never drawn, so
their cells are free for a translation."""
key = str(Path(retail).resolve())
if key in _USAGE:
return _USAGE[key]
import importlib
t = time.time()
u = Usage()
for mod in ("txfam_umn", "txfam_evt", "txfam_ovl", "txfam_fix"):
m = importlib.import_module(mod)
for r in m.rows(retail):
if r.get("hide"):
continue
u.rows += 1
font = r.get("font", tc.FIELD)
face = r.get("face") or r.get("measure")
face = face if face in (tc.FONT0, tc.FONT1) else tc.FONT1
try:
data, _ = tc.from_display(r["src"], font, r.get("ctl", "c0"), face)
except tc.TxEncodeError:
continue
if font == tc.FIELD:
if r.get("ctl") == "evt":
data = tc._TAG_RAW_RE.sub(b"", data)
_field_cells(data, u)
elif font == tc.BATTLE:
_battle_cells(data, u.battle_cells, u.battle_bytes)
log(f"retail usage: {u.rows} rows, {len(u.prop)} proportional slots, "
f"{len(u.wide)} kanji cells, {len(u.battle_cells)} battle cells "
f"({time.time() - t:.1f} s)")
_USAGE[key] = u
return u
# ---------------------------------------------------------------------------