Repository navigation
Expand file tree
/
Copy pathtxserver.py
More file actions
1727 lines (1545 loc) · 78.3 KB
/
Copy pathtxserver.py
File metadata and controls
1727 lines (1545 loc) · 78.3 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
"""txserver.py — server side of the translation editor page (/editor, /tx/*).
gui.Handler delegates here before its own routes:
if txserver.handle_get(self, url.path, url.query): return
if txserver.handle_post(self, url.path, body_bytes, content_type): return
Both return False for any path that is not ``/editor`` or under ``/tx/``.
They answer through the handler's own ``_send`` / ``_send_json``.
Reads (catalog, checks, previews) run in-process because they are fast
and read-only. Writes go to two places only: the project JSON the
translator picked (atomic temp + rename) and, for Build, gui's existing
``/run/tx-build`` Job which shells out to ``cli.py tx-build`` like every
other card, so the CLI and the GUI keep one code path for ISO writes.
Safety: a per-launch token (``TOKEN``) is baked into the served page and
every POST must carry it in ``X-TX-Token``; requests whose Host header is
not the loopback address are refused, so another web page in the same
browser cannot drive the editor (or overwrite a project) by guessing the
port. Game text is never interpolated into HTML here; the page inserts
it with textContent.
Development: with ``TX_FAKE=1`` in the environment, ``/tx/catalog``
serves a tiny built-in catalog (and ``/tx/check`` / ``/tx/preview`` fall
back to a minimal token checker and plain textpack encoding when txcodec
is not importable), so the page can be exercised before the family
readers exist. Never set it for real work.
python3 txserver.py selftest [--iso RETAIL] # headless route test
PORT=8932 python3 txserver.py serve # page alone, no gui.py
"""
from __future__ import annotations
import base64
import json
import os
import re
import secrets
import sys
import threading
from collections import Counter
from pathlib import Path
from typing import Dict, List, Optional
from urllib.parse import parse_qs, quote
ROOT = Path(__file__).resolve().parent
if str(ROOT) not in sys.path:
sys.path.insert(0, str(ROOT))
import txproject # noqa: E402
import txbackup # noqa: E402
TOKEN = secrets.token_hex(16)
FAKE = os.environ.get("TX_FAKE") == "1"
MAX_BODY = 64 * 1024 * 1024
_LOCK = threading.Lock()
_CATALOGS: Dict[tuple, dict] = {} # (iso path, mtime) -> catalog + index
_CURRENT: Dict[str, object] = {"iso": None, "key": None}
# ---------------------------------------------------------------------------
# catalog
# ---------------------------------------------------------------------------
FAKE_ROWS = [
{"id": "evt:fake:0:1", "fam": "evt", "cat": "Dialogue — field maps", "grp": "ST0210", "ord": 1,
"src": "/[label(Shion)]Allen, have you seen\nKOS-MOS anywhere?", "ctx": "Shion",
"font": "field", "ctl": "evt", "measure": "font0", "px": 480, "lim": None, "lock": None, "hide": None},
{"id": "evt:fake:0:2", "fam": "evt", "cat": "Dialogue — field maps", "grp": "ST0210", "ord": 2,
"src": "/[label(Allen)]Er... no, Chief.", "ctx": "Allen",
"font": "field", "ctl": "evt", "measure": "font0", "px": 480, "lim": None, "lock": None, "hide": None},
{"id": "evt:fake:0:3", "fam": "evt", "cat": "Dialogue — field maps", "grp": "ST0219", "ord": 1,
"src": "/[label(Allen)]Er... no, Chief.", "ctx": "Allen",
"font": "field", "ctl": "evt", "measure": "font0", "px": 480, "lim": None, "lock": None, "hide": None},
{"id": "evt:fake:0:4", "fam": "evt", "cat": "Dialogue — field maps", "grp": "ST0219", "ord": 2,
"src": "debug: room init", "ctx": "", "font": "ascii", "ctl": "evt", "measure": None, "px": None,
"lim": None, "lock": None, "hide": "debug print"},
{"id": "umn:fake:0003:0", "fam": "umn", "cat": "U.M.N. mail", "grp": "umn/0003", "ord": 0,
"src": "⟦15⟧⟦02⟧Subject: Test mail\nBody text, 100% genuine.", "ctx": "body",
"font": "field", "ctl": "c0", "measure": "font1", "px": None, "lim": None, "lock": None, "hide": None},
{"id": "umn:fake:chat:1", "fam": "umn", "cat": "U.M.N. chat", "grp": "umn/chat01", "ord": 0,
"src": "\\15\\2Hey, %s! You have %d new items.", "ctx": "<char>",
"font": "field", "ctl": "chat", "measure": "font1", "px": None, "lim": None, "lock": None, "hide": None},
{"id": "ovl:fake:SLUS_204.69:362720", "fam": "ovl", "cat": "Field menu & system", "grp": "SLUS_204.69",
"ord": 0, "src": "⟦0D⟧PAUSE", "ctx": "", "font": "field", "ctl": "c0", "measure": "font1",
"px": None, "lim": 12, "lock": None, "hide": None},
{"id": "ovl:fake:OV01:1", "fam": "ovl", "cat": "Battle HUD", "grp": "OV01 accNameTbl", "ord": 0,
"src": "Boost", "ctx": "accNameTbl", "font": "battle", "ctl": "c0", "measure": None, "px": None,
"lim": 8, "lock": None, "hide": None},
{"id": "ovl:fake:OV01:2", "fam": "ovl", "cat": "Battle HUD", "grp": "OV01 accNameTbl", "ord": 1,
"src": "Reserve", "ctx": "PrintTagFont ribbon", "font": "ascii", "ctl": "c0", "measure": None,
"px": None, "lim": 8, "lock": "shared descriptor (referenced 313 times)", "hide": None},
] + [
{"id": f"evt:fake:1:{i}", "fam": "evt", "cat": "Dialogue — cutscenes", "grp": "SCE01001 / playSCENE5",
"ord": i, "src": f"/[label(KOS-MOS)]Line {i}: target acquired.", "ctx": "KOS-MOS", "font": "field",
"ctl": "evt", "measure": "font0", "px": 480, "lim": None, "lock": None, "hide": None}
for i in range(240)
]
def _fake_catalog() -> dict:
from txcatalog import aggregate, build_tree
rows = aggregate([[dict(r) for r in FAKE_ROWS]], log=lambda m: None)
return {"rows": rows, "cats": build_tree(rows), "retail_id": "fake",
"notes": ["TX_FAKE=1: built-in sample catalog, not the disc"]}
def get_catalog(iso: str) -> dict:
"""Catalog for ``iso``, cached in memory per (path, mtime)."""
if FAKE:
key = ("<fake>", 0)
else:
p = Path(iso).expanduser()
if not p.is_file():
raise FileNotFoundError(f"no such ISO: {iso}")
key = (str(p.resolve()), p.stat().st_mtime_ns)
with _LOCK:
cat = _CATALOGS.get(key)
if cat is None:
if FAKE:
cat = _fake_catalog()
else:
import txcatalog
cat = txcatalog.build_catalog(key[0])
cat["_index"] = {r["id"]: r for r in cat["rows"]}
cat["_iso"] = key[0] if not FAKE else iso
_CATALOGS[key] = cat
if not FAKE:
threading.Thread(target=_warm_families, args=(key[0],), daemon=True).start()
_CURRENT["iso"] = key[0] if not FAKE else iso
_CURRENT["key"] = key
return cat
def _warm_families(iso: str) -> None:
"""Load the family readers' rows in the background (the catalog may come
from the disk cache), so the first per-row family check is instant."""
import importlib
for name in ("txfam_umn", "txfam_fix", "txfam_ovl", "txfam_evt"):
try:
importlib.import_module(name).validate({}, iso)
except Exception:
pass
def catalog_part_bytes(cat: dict, part: str, gz: bool) -> bytes:
"""JSON bytes of one compact part ("main" = visible rows plus the tree and
notes, "hidden" = rows hidden by default), built once per catalog and kept
with it, raw and gzipped."""
import gzip
import txcatalog
with _LOCK:
cache = cat.setdefault("_wire", {})
key = (part, gz)
if key not in cache:
raw = cache.get((part, False))
if raw is None:
payload = txcatalog.compact(cat["rows"], part)
if part == "main":
payload.update({"cats": cat["cats"], "retail_id": cat.get("retail_id", ""),
"notes": cat.get("notes", []), "fake": FAKE,
"total": len(cat["rows"])})
raw = json.dumps(payload, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
cache[(part, False)] = raw
if gz:
cache[key] = gzip.compress(raw, 6)
return cache[key]
def _current() -> Optional[dict]:
with _LOCK:
return _CATALOGS.get(_CURRENT["key"]) if _CURRENT["key"] else None
def _rows_for(body: dict) -> dict:
"""Catalog of the request's ``iso`` (the page always sends it), else the
last one loaded. The catalog carries its own image path in ``_iso``, so a
check never mixes one image's rows with another's fonts."""
iso = body.get("iso")
if iso:
return get_catalog(iso)
cat = _current()
if cat is None:
raise LookupError("no catalog loaded yet; open a retail ISO first")
return cat
# ---------------------------------------------------------------------------
# disc detection (the editor's step 1 picker)
# ---------------------------------------------------------------------------
# txproject.retail_id of the untouched Xenosaga Episode I (USA) image
KNOWN_RETAIL_IDS = {"834146435111e58c2a8495065d9cf4e4a2bb0b82"}
_DISC_INFO: Dict[tuple, dict] = {}
def _disc_info(path: str) -> dict:
"""{"xs1": bool, "rid": str} for one .iso, cached per (path, size, mtime)."""
st = os.stat(path)
key = (path, st.st_size, st.st_mtime_ns)
info = _DISC_INFO.get(key)
if info is None:
info = {"xs1": False, "rid": ""}
try:
from iso9660 import IsoImage
iso = IsoImage(path)
try:
elf = iso.boot_elf_name() or ""
finally:
iso.close()
if elf.upper() == txproject.BOOT_ELF:
info["xs1"] = True
info["rid"] = txproject.retail_id(path)
except Exception:
pass
_DISC_INFO[key] = info
return info
def detect_discs() -> List[dict]:
"""Xenosaga Episode I (USA) images in the usual places, the untouched
retail image(s) first: [{"path", "retail": bool}]. Other games and
discs are left out (gui.detect_isos keeps the first ten .iso of any
kind, which can push the right disc off its list)."""
import gui
cands: list = []
for root, depth in ((gui.ROOT.parent, 2), (Path.home() / "Downloads", 2),
(Path.home() / "Desktop", 3), (Path.home() / "Documents", 3)):
try:
if root.is_dir():
gui._walk_for_isos(root, depth, 400, cands)
except OSError:
continue
out, seen = [], set()
for p in cands:
s = str(p)
if s in seen:
continue
seen.add(s)
try:
info = _disc_info(s)
except OSError:
continue
if info["xs1"]:
out.append({"path": s, "retail": info["rid"] in KNOWN_RETAIL_IDS})
out.sort(key=lambda d: not d["retail"])
return out
# ---------------------------------------------------------------------------
# checks and previews
# ---------------------------------------------------------------------------
_FONTS: Dict[str, dict] = {}
def _txcodec():
try:
import txcodec
return txcodec
except ImportError:
if FAKE:
return None
raise
def _fonts(iso: str) -> dict:
tc = _txcodec()
if tc is not None:
return tc.load_fonts(iso)
if iso not in _FONTS:
from langpack import _load_disc_fonts
f0, f1 = _load_disc_fonts(iso, None, None)
_FONTS[iso] = {"font0": f0, "font1": f1}
return _FONTS[iso]
_FAKE_TOK = re.compile(r"(?:⟦[0-9A-Fa-f]{2}⟧)+|/\[[^\]]*\]|\\\d+|%[-+0-9.]*[dsxXc]")
def _fake_check(text: str, row: dict) -> dict:
errors, warnings = [], []
a, b = Counter(_FAKE_TOK.findall(row["src"])), Counter(_FAKE_TOK.findall(text))
if a != b:
missing = list((a - b).elements())
extra = list((b - a).elements())
hard = any(t.startswith(("⟦", "/[")) for t in missing + extra)
msg = f"protected tokens differ (missing {missing}, extra {extra})"
(errors if hard else warnings).append(msg)
nbytes = len(text.encode("utf-8"))
if row.get("lim") is not None and nbytes > row["lim"]:
errors.append(f"{nbytes} bytes > limit {row['lim']}")
return {"ok": not errors, "errors": errors, "warnings": warnings + ["(TX_FAKE check)"],
"nbytes": nbytes, "px": None}
def _face(row: dict) -> str:
"""Face the row's text is encoded for: evt rows carry ``face`` (font0 and
font1 swap grave/acute), otherwise the width face, otherwise font1."""
f = row.get("face") or row.get("measure")
return f if f in ("font0", "font1") else "font1"
def check_one(row: dict, text: str, iso: Optional[str], target: Optional[dict] = None) -> dict:
"""One row's checks. ``target`` is the resolved project target
(``resolve_target_body``); for a target that draws new letters the text
goes through ``_target_row_check`` first, so the editor refuses what the
build's glyph plan refuses and the codec sees ordinary glyph codes."""
if row.get("lock"):
return {"ok": False, "errors": [f"locked: {row['lock']}"], "warnings": [],
"nbytes": None, "px": None}
tc = _txcodec()
if tc is None:
return _fake_check(text, row)
pre_errors: List[str] = []
pre_warnings: List[str] = []
checked = text
glyphs = ""
if target and target.get("kind", "builtin") != "builtin":
pre_errors, checked, glyphs, pre_warnings = _target_row_check(row, text, target)
if checked is None:
return {"ok": False, "errors": pre_errors, "warnings": pre_warnings,
"nbytes": None, "px": None, "glyphs": glyphs}
measure = None
if row.get("measure") and iso and not glyphs:
# new letters have no retail width: the width is known after the build
try:
measure = _fonts(iso).get(row["measure"])
except Exception:
measure = None
try:
with tc.glyph_codes() if glyphs else _nullctx():
res = tc.check(checked, row["src"], row["font"], row["ctl"], limit_bytes=row.get("lim"),
measure=measure, width_px=row.get("px"), face=_face(row))
except Exception as exc:
return {"ok": False, "errors": [f"checker failed: {type(exc).__name__}: {exc}"],
"warnings": [], "nbytes": None, "px": None}
errors = pre_errors + [e for e in res.get("errors", []) if e not in pre_errors]
warnings = pre_warnings + [w for w in res.get("warnings", []) if w not in pre_warnings]
if iso and not FAKE and text != row["src"]:
with tc.glyph_codes() if glyphs else _nullctx():
fe, fw = _family_rules(row, checked, iso)
errors += [e for e in fe if e not in errors]
warnings += [w for w in fw if w not in warnings]
out = {"ok": not errors, "errors": errors, "warnings": warnings,
"nbytes": res.get("nbytes"), "px": res.get("px")}
if glyphs:
out["glyphs"] = glyphs
if iso and not FAKE and text != row["src"] and res.get("px_lines"):
_length_warnings(row, res["px_lines"], iso, out)
return out
# ---------------------------------------------------------------------------
# length guides: how long the original game's own text of each kind ever gets
# ---------------------------------------------------------------------------
# Most rows have no hard limit (dialogue grows freely on the disc), so nothing
# stops a translation from running past its text box on screen. What can be
# known without booting the game is what retail itself does: per category,
# the widest line and the largest number of lines any original string has.
# A translation past both is flagged (a warning: the box sizes themselves are
# not decoded, so this is a guide, like the px guides).
_LENGTH_GUIDES: Dict[str, Dict[str, dict]] = {}
def _est_lines(px_lines: List[int], width: int) -> int:
"""Lines on screen when each line wider than ``width`` is wrapped."""
return sum(max(1, -(-w // width)) for w in px_lines)
def _length_guides(iso: str) -> Dict[str, dict]:
"""Per category, over the visible, unlocked field-font rows of ``iso``:
``total`` = the longest original string (px of all its lines added up),
``lines`` = the most line breaks + 1 in one original string, ``est`` = the
most lines on screen of one original string once lines wider than the
row's own px guide are wrapped (rows that have a guide)."""
key = str(iso)
got = _LENGTH_GUIDES.get(key)
if got is not None:
return got
tc = _txcodec()
src_px: Dict[str, List[int]] = {}
out: Dict[str, dict] = {"": src_px} # "" = each row's own original, by id
try:
fonts = _fonts(iso)
rows = get_catalog(iso)["rows"]
except Exception:
return {}
for r in rows:
if r.get("hide") or r.get("lock") or not r.get("measure") or r.get("font") != tc.FIELD:
continue
m = fonts.get(r["measure"])
if m is None:
continue
try:
data = tc.from_display(r["src"], r["font"], r["ctl"], _face(r))[0]
except Exception:
continue
pxl = src_px[r["id"]] = _px_lines(tc, m, r, data)
g = out.setdefault(r["cat"], {"total": 0, "lines": 0, "est": 0})
g["total"] = max(g["total"], sum(pxl))
g["lines"] = max(g["lines"], len(pxl))
if r.get("px"):
g["est"] = max(g["est"], _est_lines(pxl, int(r["px"])))
_LENGTH_GUIDES[key] = out
return out
def _px_lines(tc, m, row: dict, data: bytes) -> List[int]:
if row["ctl"] == "evt":
data = tc._TAG_RAW_RE.sub(b"", data)
return [m.width_of_bytes(x) for x in data.split(b"\n")]
def _length_warnings(row: dict, px_lines: List[int], iso: str, out: dict) -> None:
"""Adds to a check result: ``len_pct`` (drawn length against the original,
100 = the same), ``wide`` (a line is past the row's px guide and can be
wrapped), and a warning when the text is longer than anything the original
game shows in this category."""
guides = _length_guides(iso)
g = guides.get(row.get("cat"))
if not g:
return
src_pxl = guides[""].get(row["id"]) or []
total, src = sum(px_lines), sum(src_pxl)
if src:
out["len_pct"] = round(100 * total / src)
if row.get("px"):
width = int(row["px"])
if max(px_lines) > width and g["lines"] > 1:
out["wide"] = True
est = _est_lines(px_lines, width)
if est > g["est"] and est > _est_lines(src_pxl or [0], width):
out["warnings"].append(f"about {est} lines on screen; no original text of this kind takes "
f"more than {g['est']}. It may not fit its box: shorten it, then "
f"look at this screen in the emulator")
elif total > g["total"] and total > src:
out["warnings"].append(f"longer than any original text of this kind ({total} px of letters; "
f"the longest original has {g['total']}). It may not fit its box: "
f"shorten it, then look at this screen in the emulator")
def _wrap_width(row: dict, iso: str) -> Optional[int]:
return int(row["px"]) if row.get("px") else None
_GLUE_BEFORE = set("?!:;»”)") # French spacing: never start a line with these
_WORD_RE = re.compile(r"(?:/\[[^\]\n]*\]|[^ ])+")
def wrap_text(row: dict, text: str, iso: str) -> str:
"""Break the lines of ``text`` that are wider than the row's width (see
``_wrap_width``) at spaces. Lines that fit, and line breaks already there,
are kept. ``/[...]`` tags are never split."""
tc = _txcodec()
width = _wrap_width(row, iso)
m = _fonts(iso).get(row.get("measure")) if row.get("measure") else None
if not width or m is None:
return text
def px(line: str) -> int:
data = tc.from_display(line, row["font"], row["ctl"], _face(row))[0]
if row["ctl"] == "evt":
data = tc._TAG_RAW_RE.sub(b"", data)
return m.width_of_bytes(data)
res = []
for line in text.split("\n"):
try:
if px(line) <= width:
res.append(line)
continue
words = []
for w in _WORD_RE.findall(line):
if words and w and all(c in _GLUE_BEFORE for c in w):
words[-1] += " " + w
elif words and words[-1] in ("«", "“", "("):
words[-1] += " " + w
else:
words.append(w)
cur = ""
for w in words:
cand = w if not cur else cur + " " + w
if cur and px(cand) > width:
res.append(cur)
cur = w
else:
cur = cand
if cur:
res.append(cur)
except ValueError: # a letter the font lacks: leave the line alone
res.append(line)
return "\n".join(res)
class _nullctx:
def __enter__(self):
return self
def __exit__(self, *exc):
return False
# ---------------------------------------------------------------------------
# per-row checks for targets that draw new letters (txtarget)
# ---------------------------------------------------------------------------
_CMAPS: Dict[tuple, Optional[frozenset]] = {}
_CMAP_LOCK = threading.Lock()
def _cmap(path: str, face: int = 0) -> Optional[frozenset]:
"""Code points of one font face (cached per path, face, mtime); None when
the font cannot be read or fonttools is missing."""
try:
st = os.stat(path)
except OSError:
return None
key = (path, int(face), st.st_mtime_ns)
with _CMAP_LOCK:
if key in _CMAPS:
return _CMAPS[key]
try:
import txtarget
cm = txtarget.font_cmap(path, int(face))
val = frozenset(cm) if cm is not None else None
except Exception:
val = None
with _CMAP_LOCK:
_CMAPS[key] = val
return val
def _drawn(c: str) -> bool:
"""A character that needs its own glyph in a font (not a combining mark,
which the shaper places from its base letter, and not a space)."""
import unicodedata
return not c.isspace() and unicodedata.category(c) not in ("Mn", "Me")
def _char_list(chars: str, n: int = 12) -> str:
import txcodec as tc
shown = " ".join(chars[:n]) + (" …" if len(chars) > n else "")
names = ", ".join(tc.char_name(c) for c in chars[:2])
return f"{shown} ({names}{', ...' if len(chars) > 2 else ''})"
def _target_row_check(row: dict, text: str, t: dict):
"""What the build's glyph plan (txtarget.plan_glyphs / _plan_field /
_check_font / _encode_with) would refuse for this row, before the codec
runs. -> (errors, text for the codec with every new letter replaced by a
glyph code, or None when the codec need not run; the new letters;
warnings)."""
import unicodedata
import txcodec as tc
import txtarget as tt
font = row.get("font") or tc.FIELD
face = _face(row)
errors: List[str] = []
warnings: List[str] = []
cov = tt.coverage(text, t, font, face)
if font == tc.ASCII:
if cov["impossible"]:
errors.append(f"drawn by the tag font (window title ribbons), which has only A-Z a-z 0-9 "
f": / . - and space and no room for new letters; {_char_list(cov['impossible'])} "
f"cannot be drawn there. Keep this row in Latin letters (transliterate it) "
f"or leave it untranslated")
return errors, None, "", warnings
return errors, text, "", warnings
if cov["impossible"]:
errors.append(f"cannot draw {_char_list(cov['impossible'])}")
glyph = cov["glyph"]
if not glyph:
return errors, text, "", warnings
battle = font == tc.BATTLE
fpath = t.get("battle_font") if battle else t.get("font")
fface = int((t.get("battle_face") if battle else t.get("face")) or 0)
where = "battle labels" if battle else "dialogue and menus"
need = "".join(c for c in glyph if _drawn(c))
if not fpath:
errors.append(f"{_char_list(need or glyph)} must be drawn from a font file for {where}, and "
f"none is chosen: pick one in step 2 (Language setup)")
elif not Path(fpath).is_file():
errors.append(f"the font file {fpath} does not exist (step 2, Language setup)")
else:
cmap = _cmap(fpath, fface)
if cmap is not None:
miss = "".join(c for c in need if ord(c) not in cmap)
if miss:
errors.append(f"the font {_font_label(fpath, fface)} has no letter for "
f"{_char_list(miss)}; pick a font that covers them (step 2)")
if t.get("rtl") and not battle and hasattr(tt, "_protect") and hasattr(tt, "_rtl_mid_controls"):
body, saved = tt._protect(unicodedata.normalize("NFC", text), row.get("ctl", "c0"))
for para in body.split("\n"):
m = tt._EDGE_RE.match(para)
bad = tt._rtl_mid_controls(m.group(2), saved) if m else []
if bad:
errors.append(f"right-to-left text cannot carry {', '.join(repr(b) for b in bad[:4])} in "
f"the middle of a line: the line is reordered word by word for display, "
f"so a colour or control code there would end up on other words. Put it "
f"at the start or end of the line, or leave it out")
break
# every new letter becomes a glyph code, as in a build, so the codec and
# the family rules see ordinary text (bytes: 2 a letter in the field font,
# 1 in the battle grid; the build may differ where letters join)
subs = {}
for i, c in enumerate(sorted(set(glyph))):
subs[c] = tc.glyph_char((0x80 + i % 0x60) if battle else (0xB0A1 + (i // 94) * 0x100 + i % 94))
checked = "".join(subs.get(c, c) for c in unicodedata.normalize("NFC", text))
if row.get("lim") is not None:
warnings.append(f"{len(set(glyph))} new letter(s): the byte count is an estimate until the "
f"build places them")
return errors, checked, glyph, warnings
_FAMILY_MODULES = {"umn": "txfam_umn", "evt": "txfam_evt", "ovl": "txfam_ovl", "fix": "txfam_fix"}
def _family_rules(row: dict, text: str, iso: str):
"""The build's own per-row rules (speaker names, message buffers, choice
counts, field sizes, shared budgets) plus txfam_ovl's notes on strings
two printers draw, so the editor says what the build will say.
-> (errors, warnings)."""
name = _FAMILY_MODULES.get(row.get("fam") or row["id"].split(":", 1)[0])
if name is None:
return [], []
try:
import importlib
mod = importlib.import_module(name)
errors = list(mod.validate({row["id"]: text}, iso).get(row["id"], []))
warnings: List[str] = []
if hasattr(mod, "warnings") and row.get("font") in ("battle", "ascii"):
warnings = [w for w in mod.warnings({row["id"]: text}, iso).get(row["id"], [])
if "two printers" in w or "tag label" in w]
except Exception as exc:
return [f"family check failed: {type(exc).__name__}: {exc}"], []
return errors, warnings
_EVT_TAG = re.compile(rb"/\[[^\]]*\]")
_CHAT_ESC = re.compile(rb"\\\d+")
def _png_urls(pngs) -> List[str]:
return ["data:image/png;base64," + base64.b64encode(p).decode("ascii") for p in pngs]
def preview_png(row: dict, text: str, iso: str, target: Optional[dict] = None) -> dict:
"""{"pngs": [data URL per line], "png": first, "face": "font0"|"font1"}
(+ "font_label" when new letters were drawn from the target's font)"""
if target and target.get("kind", "builtin") != "builtin" and row["font"] == "field":
import txtarget as tt
face = _face(row) if (row.get("face") or row.get("measure")) else \
("font0" if row.get("ctl") == "evt" else "font1")
if tt.coverage(text, target, "field", face)["glyph"]:
if not target.get("font"):
raise ValueError("these letters are drawn from a font file: choose one in step 2 "
"(Language setup) to see them")
ctl = row.get("ctl") or "c0"
shown = text
if ctl == "evt":
shown = re.sub(r"/\[[^\]\n]*\]", "", text)
elif ctl == "chat":
shown, ctl = re.sub(r"\\\d+", "", text), "c0"
try:
pngs, _enc = tt.preview(iso, target, shown, "field", face, ctl)
except tt.TargetError as exc:
raise ValueError(str(exc)) from None
urls = _png_urls(pngs)
return {"pngs": urls, "png": urls[0] if urls else None, "face": face, "warnings": [],
"font_label": "preview with " + _font_label(target["font"], target.get("face", 0))}
if row["font"] == "battle":
raise ValueError("battle HUD strings are drawn from the stat.xtx grid, not font0/font1; "
"no preview here")
if row["font"] == "ascii":
raise ValueError("this string is drawn by the ASCII-only ribbon font; no preview here")
face = _face(row) if (row.get("face") or row.get("measure")) else \
("font0" if row.get("ctl") == "evt" else "font1")
tc = _txcodec()
warnings: List[str] = []
if tc is not None:
data, warnings = tc.from_display(text, row["font"], row["ctl"], face)
else:
from textpack import encode_text
data = encode_text(text)
if row.get("ctl") == "evt":
data = _EVT_TAG.sub(b"", data)
elif row.get("ctl") == "chat":
data = _CHAT_ESC.sub(b"", data)
from langpack import render_line
font = _fonts(iso)[face]
if tc is not None and tc.missing_capital_accents(font, face):
# the build redraws these capitals (txcodec.fix_capital_accents); show that
key = f"{iso}|{face}|fixed"
if key not in _FONTS:
_FONTS[key] = tc.fix_capital_accents(font, face)
font = _FONTS[key]
if tc is not None and tc.needs_metric_fix(text, font, face):
# the build gives — ‾ _ real metrics when a translation uses them
font = tc.fix_unmeasured(font, face)
pngs = []
for line in data.split(b"\n"):
png = render_line(font, line, 2)
pngs.append("data:image/png;base64," + base64.b64encode(png).decode("ascii"))
return {"pngs": pngs, "png": pngs[0] if pngs else None, "face": face,
"warnings": list(warnings)}
# ---------------------------------------------------------------------------
# step 2, Language setup: source text, target language, font, try-it preview
# ---------------------------------------------------------------------------
# Everything here reads; nothing writes. The page keeps the choice in the
# project (project["target"], project["source"], project["language_name"]).
# txtarget is being extended with a language registry (languages(query),
# detect_scripts(text), profile_for_custom(name, sample), capacity(...));
# each is used when present and replaced by a smaller local answer when not.
_PROFILE_KEYS = ("code", "name", "endonym", "kind", "script", "rtl", "alphabet", "lacking",
"sample", "fonts", "registry")
def _clean_profile(p: dict) -> dict:
out = {k: p.get(k) for k in _PROFILE_KEYS if k in p}
out.setdefault("code", "")
out.setdefault("name", out["code"])
out.setdefault("endonym", "")
out.setdefault("kind", "builtin")
out.setdefault("script", "")
out["rtl"] = bool(out.get("rtl"))
for k in ("alphabet", "lacking", "sample"):
out[k] = str(out.get(k) or "")
out["fonts"] = list(out.get("fonts") or [])
for k in ("script_name", "aliases", "region", "regions", "speakers", "notes"):
if p.get(k):
out[k] = p[k]
if not out.get("script_name"):
out["script_name"] = _script_display(out["script"], out["sample"] + out["alphabet"])
return out
def _script_display(code: str, sample: str = "") -> str:
"""A script's name for people: the registry's when it has one, else the
Unicode name of the sample's letters (Cherokee, Devanagari, Nko...)."""
import txtarget as tt
names = getattr(tt, "SCRIPT_NAMES", None)
if isinstance(names, dict) and names.get(code):
return str(names[code])
found = _scripts_in(sample)
if found:
return found[0]["name"]
return code
_UNAME_RE = re.compile(r"^(.*?) (?:CAPITAL |SMALL )?(?:LETTER|SYLLABLE|CHARACTER|DIGIT|VOWEL|SIGN|"
r"MARK|LIGATURE|IDEOGRAPH|NUMBER|CONSONANT|TONE|ABBREVIATION|MEDIAL|COMBINING|"
r"FINAL|INITIAL|PUNCTUATION|SUBJOINED|INDEPENDENT|DEPENDENT)\b")
def _scripts_in(text: str) -> List[dict]:
"""[{"name", "count", "letters"}] of the scripts of ``text``'s letters, by
the Unicode character names (no table): most letters first, Latin last
unless it is the only one."""
import unicodedata
counts: Counter = Counter()
letters: Dict[str, str] = {}
for c in dict.fromkeys(text or ""):
cat = unicodedata.category(c)
if not (cat.startswith("L") or cat in ("Mn", "Mc", "Nd")) or ord(c) < 0x80 and cat == "Nd":
continue
try:
nm = unicodedata.name(c)
except ValueError:
continue
if nm.startswith("CJK "):
key = "Han"
else:
m = _UNAME_RE.match(nm)
key = (m.group(1) if m else nm.split()[0]).title()
n = sum(1 for x in text if x == c)
counts[key] += n
letters[key] = letters.get(key, "") + c
# a name cut short by an unusual character name ("OL CHIKI MU TTUDDAG" -> "Ol")
# joins the longer name it starts ("Ol Chiki")
for k in list(counts):
longer = [o for o in counts if o != k and o.startswith(k + " ")]
if longer:
counts[longer[0]] += counts.pop(k)
letters[longer[0]] += letters.pop(k)
out = [{"name": k, "count": n, "letters": letters[k]} for k, n in counts.most_common()]
out.sort(key=lambda d: (d["name"] == "Latin" and len(out) > 1, -d["count"]))
return out
def list_languages(query: str = "") -> List[dict]:
"""Target languages for the setup list (txtarget.languages when present,
else TARGETS filtered by English name, endonym or code)."""
import txtarget as tt
q = (query or "").strip().lower()
if hasattr(tt, "languages"):
try:
got = tt.languages(query or "")
return [_clean_profile(p) for p in got if isinstance(p, dict) and p.get("code") != "other"]
except Exception:
pass
out = []
for p in tt.TARGETS:
if p["code"] == "other":
continue
hay = " ".join((p["code"], p["name"], p.get("endonym", ""))).lower()
if not q or q in hay:
out.append(_clean_profile(p))
return out
def custom_language(name: str, sample: str, code: str = "") -> dict:
"""The kind, scripts and direction of a language the list lacks, from a
sample sentence (txtarget.profile_for_custom when present)."""
import unicodedata
import txcodec as tc
import txtarget as tt
sample = unicodedata.normalize("NFC", sample or "")
scripts = _scripts_in(sample)
prof = None
if hasattr(tt, "profile_for_custom"):
try:
prof = tt.profile_for_custom(name, sample)
except Exception:
prof = None
if not isinstance(prof, dict):
iso_script = ""
if hasattr(tt, "detect_scripts"):
try:
ds = tt.detect_scripts(sample)
if isinstance(ds, dict):
ds = sorted(ds.items(), key=lambda kv: -(kv[1] if isinstance(kv[1], (int, float)) else 0))
for it in ds or []:
sc = it.get("script") if isinstance(it, dict) else (it[0] if isinstance(it, (list, tuple)) else it)
if sc and sc not in ("Zyyy", "Zinh", "Latn"):
iso_script = str(sc)
break
if sc == "Latn" and not iso_script:
iso_script = "Latn"
except Exception:
iso_script = ""
letters = "".join(c for c in dict.fromkeys(sample) if not c.isspace())
blt = tt.coverage(letters, "builtin")
scr = tt.coverage(letters, "script")
names = {d["name"] for d in scripts}
if names & {"Hiragana", "Katakana"}:
kind = "japanese" # kana: the retail fonts' own Japanese, rare kanji drawn
elif names - {"Latin"}:
kind = "script" # any other script: every letter drawn from a font
elif not blt["impossible"]:
kind = "builtin" # Latin letters the accent block already has
else:
kind = "script-hybrid" # Latin with a few letters drawn from a font
rtl_n = sum(1 for c in sample if unicodedata.bidirectional(c) in ("R", "AL"))
ltr_n = sum(1 for c in sample if unicodedata.bidirectional(c) == "L")
prof = {"code": code or "other", "name": name or "My language", "endonym": "", "kind": kind,
"script": iso_script if iso_script and (iso_script != "Latn" or kind != "script") else "",
"rtl": rtl_n > ltr_n, "alphabet": "", "sample": sample,
"lacking": scr["glyph"] if kind != "builtin" else ""}
prof = _clean_profile(prof)
if code:
prof["code"] = code
if name:
prof["name"] = name
prof["sample"] = prof["sample"] or sample
prof["scripts"] = scripts
prof["custom"] = True
if not prof.get("script_name"):
prof["script_name"] = scripts[0]["name"] if scripts else ""
elif scripts and prof["script_name"] == prof.get("script"):
prof["script_name"] = scripts[0]["name"] if scripts[0]["name"] != "Latin" or len(scripts) == 1 \
else prof["script_name"]
return prof
def resolve_target_body(t: Optional[dict], language: str = "") -> dict:
"""project["target"] as the page sends it -> txtarget.resolve_target."""
import txtarget as tt
t = dict(t or {})
proj = {"target": {k: v for k, v in t.items() if k in tt._TARGET_KEYS}, "language": language or t.get("code", "")}
return tt.resolve_target(proj)
def needed_letters(target: dict, extra: str = "") -> str:
"""Letters of the target language (alphabet, sample, the script's probe
letters, plus ``extra``: the project's own text) that need a glyph."""
import txtarget as tt
prof = tt.profile(target.get("code", "")) or {}
probe = getattr(tt, "_PROBE", {}).get(target.get("script") or prof.get("script") or "", "")
text = (prof.get("alphabet") or "") + (prof.get("sample") or "") + probe + (target.get("sample") or "") + (extra or "")
cov = tt.coverage(text, target)
return "".join(c for c in cov["glyph"] if _drawn(c))
_FONT_ALL: Dict[str, object] = {"ready": False, "faces": None, "thread": None}
def _all_faces() -> List[dict]:
"""Every installed outline face with its cmap (built once, ~3 s)."""
import txtarget as tt
with _CMAP_LOCK:
if _FONT_ALL["faces"] is not None:
return _FONT_ALL["faces"]
faces = []
for f in tt._font_index():
cm = _cmap(f["path"], f["face"])
if cm:
faces.append(dict(f, _cmap=cm))
with _CMAP_LOCK:
_FONT_ALL["faces"] = faces
return faces
def _warm_fonts() -> None:
"""Read every installed font's cmap in the background (once), so the
font list of the Language setup answers at once."""
with _CMAP_LOCK:
if _FONT_ALL["thread"] is not None or FAKE:
return
_FONT_ALL["thread"] = threading.Thread(target=lambda: _safe(_all_faces), daemon=True)
_FONT_ALL["thread"].start()
def _safe(fn):
try:
return fn()
except Exception:
return None
def _font_label(path: str, face: int = 0) -> str:
"""The font's own family (and style unless Regular), from the installed
index or the file's name table; the file name as a last resort."""
try:
import txtarget as tt
for f in tt._font_index():
if f["path"] == path and f["face"] == int(face or 0):
st = f.get("style") or ""
return f["family"] + ("" if st.lower() in ("regular", "") else " " + st)
faces = tt._open_faces(path)
ft = faces[int(face or 0)]
fam, st = tt._name(ft, 1), tt._name(ft, 2)
if fam:
return fam + ("" if st.lower() in ("regular", "") else " " + st)
except Exception:
pass
return Path(path).name
# Ties between fonts that draw every letter go to plain, widely installed
# sans faces (they stay readable at the game's 20-odd pixel size), and away
# from monospace, typewriter, display and condensed families.
_CLEAR_FAMILIES = ("noto sans", "helvetica neue", "helvetica", "arial", "pt sans", "segoe ui", "dejavu sans",
"liberation sans", "open sans", "lucida grande", "verdana", "tahoma", "geneva", "apple sd gothic",
"hiragino sans", "pingfang", "kohinoor", "geeza pro", "sf arabic", "arial hebrew", "thonburi",
"kefa", "mshtakan", "kailasa")
_ODD_WORDS = ("mono", "typewriter", "courier", "black", "narrow", "condensed", "comic", "chalk", "marker",
"papyrus", "script", "brush", "stencil", "impact", "trattatello", "herculanum", "zapfino",
"unicode ms", "symbol", "dings", "webdings", "bodoni", "didot", "rounded")
def rank_fonts(chars: str, prefer: List[str], limit: int = 14) -> List[dict]:
"""Installed faces ranked by how many of ``chars`` they draw; ties go to a
family named after the language or script (``prefer``), then Noto, then
Regular styles. -> [{path, face, family, style, label, covers, missing}]"""
need = [c for c in dict.fromkeys(chars) if _drawn(c)]
if not need:
return []
words = [w.lower() for w in prefer if w and len(w) > 2]
rows = []
for f in _all_faces():
cm = f["_cmap"]
have = sum(1 for c in need if ord(c) in cm)
if not have:
continue
fam = f["family"] or Path(f["path"]).stem
named = any(w in (fam + " " + Path(f["path"]).stem).lower().replace(" ", "")
or w in fam.lower() for w in [x.replace(" ", "") for x in words] + words)
low = fam.lower()
clear = next((i for i, c in enumerate(_CLEAR_FAMILIES) if low.startswith(c)), len(_CLEAR_FAMILIES))
odd = any(w in low for w in _ODD_WORDS)
rows.append((-(have / len(need)), "nastaliq" in low,
fam.startswith(".") or "lastresort" in low, not named,
not f.get("noto"), odd, (f.get("style") or "").lower() not in ("regular", "w3", "book", "roman", ""),
clear, low, f["path"], f["face"], f, have))
rows.sort(key=lambda r: r[:11])
out, seen = [], set()
for r in rows:
f, have = r[11], r[12]
key = (f["family"], f.get("style"))
if key in seen:
continue
seen.add(key)
out.append({"path": f["path"], "face": f["face"], "family": f["family"], "style": f.get("style", ""),