Repository navigation
Expand file tree
/
Copy pathtxserver.py
More file actions
2229 lines (2018 loc) · 107 KB
/
Copy pathtxserver.py
File metadata and controls
2229 lines (2018 loc) · 107 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 hashlib
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": "sb:cf/us/fake.sb#0001", "fam": "sb", "cat": "Dialogue — scenes", "grp": "1210", "ord": 1,
"src": "[Shion]<l2>Allen, have you seen\nKOS-MOS anywhere?<f>", "ctx": "Shion",
"font": "field", "ctl": "us", "measure": "font0", "px": None, "lim": None, "lock": None, "hide": None},
{"id": "sb:cf/us/fake.sb#0002", "fam": "sb", "cat": "Dialogue — scenes", "grp": "1210", "ord": 2,
"src": "[Allen]Er... no, Chief.<f>", "ctx": "Allen",
"font": "field", "ctl": "us", "measure": "font0", "px": None, "lim": None, "lock": None, "hide": None},
{"id": "sb:cf/us/fake2.sb#0001", "fam": "sb", "cat": "Dialogue — scenes", "grp": "1220", "ord": 1,
"src": "[Allen]Er... no, Chief.<f>", "ctx": "Allen",
"font": "field", "ctl": "us", "measure": "font0", "px": None, "lim": None, "lock": None, "hide": None},
{"id": "sb:cf/us/fake2.sb#0002", "fam": "sb", "cat": "Script identifiers", "grp": "1220", "ord": 2,
"src": "ce100_045", "ctx": "", "font": "field", "ctl": "us", "measure": None, "px": None,
"lim": None, "lock": None, "hide": "identifier (a label or voice id the scripts look up by name)"},
{"id": "mnu:mnu/us/fake.txd#0003", "fam": "mnu", "cat": "Menu text", "grp": "Menus", "ord": 0,
"src": "⟦0D⟧⟦0A⟧Save data: %d block(s).\nContinue?", "ctx": "",
"font": "field", "ctl": "us", "measure": "font0", "px": None, "lim": None, "lock": None, "hide": None},
{"id": "mnu:mnu/us/fake.bin#00.0001", "fam": "mnu", "cat": "Database & menu tables", "grp": "DBC / 00",
"ord": 0, "src": "$col707070;Zohar", "ctx": "",
"font": "field", "ctl": "us", "measure": "font0", "px": None, "lim": None, "lock": None, "hide": None},
{"id": "bat:bat/us/fake.bin#00.0000", "fam": "bat", "cat": "Battle names & descriptions", "grp": "table 00",
"ord": 0, "src": "Boost", "ctx": "", "font": "field", "ctl": "us", "measure": "font0",
"px": None, "lim": 12, "lock": None, "hide": None},
{"id": "mnu:mnu/us/fake.bin#00.0002", "fam": "mnu", "cat": "Database & menu tables", "grp": "DBC / 00",
"ord": 1, "src": "Reserve", "ctx": "", "font": "field", "ctl": "us", "measure": None,
"px": None, "lim": 8, "lock": "holds a value pointing into its middle (meaning unknown): it cannot change",
"hide": None},
{"id": "sub:mov/us/fake.txt#L3", "fam": "sub", "cat": "Movie subtitles", "grp": "s000300", "ord": 0,
"src": "KOS-MOS, surrender and become part of me!", "ctx": "00:00:02",
"font": "field", "ctl": "us", "measure": "font0", "px": None, "lim": None, "lock": None, "hide": None},
] + [
{"id": f"sb:cf/us/fake3.sb#{i:04d}", "fam": "sb", "cat": "Dialogue — scenes", "grp": "2940",
"ord": i, "src": f"[KOS-MOS]Line {i}: target acquired.<f>", "ctx": "KOS-MOS", "font": "field",
"ctl": "us", "measure": "font0", "px": None, "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"]}
_BUILDING: Dict[tuple, threading.Event] = {} # catalogs being read: key -> set when done
def _set_stamp(iso: str) -> tuple:
"""(path, size, mtime_ns) of every disc of the set ``iso`` belongs to, Disc 1
first: what every per-set cache is keyed on, so a partner disc put next to
it, replaced or taken away is another set (not only a changed ``iso``)."""
p = str(Path(iso).expanduser().resolve())
try:
import txdiscs
members = txdiscs.pair(p)
except Exception: # noqa: BLE001 - not a disc: the image alone
members = [p]
out = []
for q in members:
try:
st = os.stat(q)
out.append((q, st.st_size, st.st_mtime_ns))
except OSError:
out.append((q, -1, -1))
return tuple(out)
def get_catalog(iso: str) -> dict:
"""Catalog for ``iso``'s disc set, cached in memory per (path, mtime) of
every disc of the set."""
if FAKE:
key = ("<fake>", 0)
else:
p = Path(iso).expanduser()
if not p.is_file():
raise FileNotFoundError(f"no such ISO: {iso}")
me = str(p.resolve())
try: # the set: a second disc put next to it, or replaced, is another catalog
import txdiscs
members = [str(q) for q in txdiscs.pair(me)] or [me]
except Exception: # noqa: BLE001 - not a disc: build_catalog says so below
members = [me]
# keyed by Disc 1 of the set whichever disc was picked: the rows and the
# retail id cover the whole set, so Disc 1 and Disc 2 are one catalog
first = members[0] if me in members else me
key = (first, os.stat(first).st_mtime_ns)
key += tuple((q, os.stat(q).st_mtime_ns) for q in members if q != first)
# A cold read takes ~30 s: it runs OUTSIDE _LOCK, so requests about other
# (cached) sets go on meanwhile; a second request for the same set waits for
# the first read instead of starting another.
owner = False
with _LOCK:
for old in [k for k in _CATALOGS if k[0] == key[0] and k != key]:
del _CATALOGS[old] # the same image as part of another set: superseded
cat = _CATALOGS.get(key)
if cat is None:
ev = _BUILDING.get(key)
if ev is None:
ev = _BUILDING[key] = threading.Event()
owner = True
if cat is None and not owner:
# the reader hands its result over on the event itself: the entry may already
# be gone from _CATALOGS (superseded by another set of the same image)
if not ev.wait(900):
raise TimeoutError(f"reading {iso} is taking more than 15 minutes; try again")
cat, err = getattr(ev, "result", None), getattr(ev, "error", None)
if cat is None:
raise err or RuntimeError(f"reading {iso} failed")
elif cat is None:
try:
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
cat["_rev"] = hashlib.sha1(repr(key).encode("utf-8")).hexdigest()[:16]
with _LOCK:
_CATALOGS[key] = cat
ev.result = cat
except Exception as exc:
ev.error = exc
raise
finally:
with _LOCK:
_BUILDING.pop(key, None)
ev.set()
if not FAKE:
threading.Thread(target=_warm_families, args=(key[0],), daemon=True).start()
with _LOCK:
_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_sb", "txfam_mnu", "txfam_bat", "txfam_sub"):
try:
importlib.import_module(name).validate({}, iso)
except Exception:
pass
try: # and the length guides (a few seconds over Episode III's 23,000 offered rows)
_length_guides(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)
got = cache.get(key)
raw = cache.get((part, False))
if got is not None:
return got
# built outside _LOCK (JSON + gzip of ~100k rows takes a while); two requests
# racing build the same bytes, and the first one stored is kept
if raw is None:
payload = txcatalog.compact(cat["rows"], part)
payload["rev"] = cat.get("_rev", "") # both parts carry it: the page refuses hidden rows of another read
if part == "main":
display = ""
if cat.get("_iso") and not FAKE:
try: # "us" = English text, "jp" = Japanese text: the page names the source after it
display = _txcodec().context(str(cat["_iso"])).display
except Exception:
display = ""
lone = []
if cat.get("_iso") and not FAKE:
try: # a project made while one disc was alone carries that disc's id: it may move to the set
import txdiscs
lone = txdiscs.lone_ids(str(cat["_iso"]))
except Exception:
lone = []
payload.update({"cats": cat["cats"], "retail_id": cat.get("retail_id", ""), "retail_lone": lone,
"notes": cat.get("notes", []), "fake": FAKE,
"total": len(cat["rows"]), "display": display})
raw = json.dumps(payload, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
with _LOCK:
raw = cache.setdefault((part, False), raw)
if not gz:
return raw
data = gzip.compress(raw, 6)
with _LOCK:
return cache.setdefault(key, data)
def _current() -> Optional[dict]:
"""The catalog of a request that names no disc: the ONE catalog this
server has loaded. With two disc sets open (two tabs on different builds)
there is no "current" one: the request must name its disc, and is refused
(LookupError -> 404) rather than answered from the other tab's disc."""
with _LOCK:
cats = list(_CATALOGS.values())
if len(cats) > 1:
raise LookupError("two disc sets are open in this editor; the request must name its disc (iso)")
return cats[0] if cats else None
def _rows_for(body: dict) -> dict:
"""Catalog of the request's ``iso`` (the page always sends it), else the
only one loaded (``_current``). 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
def _was_lone_of(rid: str, cat: dict) -> bool:
"""``rid`` is one disc's own id within ``cat``'s set (a project made while that
disc was found alone): the same lines, so reading or exporting it is fine."""
try:
import txdiscs
return bool(cat.get("_iso")) and rid in txdiscs.lone_ids(str(cat["_iso"]))
except Exception: # noqa: BLE001
return False
def _sole_iso() -> Optional[str]:
"""The image of the ONE catalog this server has loaded (None with none or
several): what a request that names no disc is about."""
with _LOCK:
cats = list(_CATALOGS.values())
return str(cats[0].get("_iso") or "") or None if len(cats) == 1 else None
def _scope(iso):
"""``with _scope(iso):`` the request's disc for everything that is not
handed one explicitly (which letters a language lacks, what the codec may
write). Per thread (txcodec.disc), so requests for different builds never
see each other's disc; no disc named = no disc (the USA codec rules); a
named disc that does not exist is refused (FileNotFoundError: a 404)."""
tc = _txcodec()
if tc is None or FAKE or not iso or not hasattr(tc, "disc"):
return _nullctx()
try:
found = Path(str(iso)).expanduser().is_file()
except OSError:
found = False
if not found: # a disc that was named but is gone: say so, not answer with the USA rules
raise FileNotFoundError(f"no such disc image: {iso} (moved or deleted? choose the disc again)")
return tc.disc(str(Path(str(iso)).expanduser()))
# ---------------------------------------------------------------------------
# disc detection (the editor's step 1 picker)
# ---------------------------------------------------------------------------
# txproject.retail_id of the untouched Xenosaga Episode III sets: USA Disc 1 + 2 (and
# each disc alone), Japan Disc 1 + 2 (and each alone), the May 2006 prototype
KNOWN_RETAIL_IDS = {"048d1bde644abb4b13b446808083f2f66734302e", "e22e583c46000ff652c2f3fcb4b3fa615fdfcfb2",
"bfb5226046c295dfecbe9b831194d25b0668715c", "fa155bdcdf1ab4a2fe7e2e7cda360e5e91ea4818",
"e9c8e91e48efc3026d816d5ffddd966f547eb362", "cc23b4a484221f9336eb5cd9f80b225e2962ec9a",
"3b106662e2b225755ee3ef242b89bc79e105e108"}
_DISC_INFO: Dict[tuple, dict] = {}
def _disc_info(path: str) -> dict:
"""{"xs1": bool, "rid": str, "build": str} for one .iso, cached per its set's
(path, size, mtime) stamps: the retail id covers both discs of a pair."""
os.stat(path) # (OSError for a vanished file, as before)
key = (path,) + _set_stamp(path)
info = _DISC_INFO.get(key)
if info is None:
info = {"xs1": False, "rid": "", "build": ""} # "xs1": the key name is the Episode I editor's; here = a known Episode III build
try:
import txdiscs
di = txdiscs.info(path)
if di["ok"]:
info["xs1"] = True
info["rid"] = txproject.retail_id(path)
info["build"] = di.get("build") or ""
except Exception:
pass
_DISC_INFO[key] = info
return info
def detect_discs() -> List[dict]:
"""Xenosaga Episode III images (any known build, either disc) 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,
"build": {"us": "USA", "jp": "Japan", "proto_2006_05": "May 2006 prototype"}.get(info.get("build"), "")})
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}⟧)+|<[^<>\n]{1,40}>|\$[a-z]+[0-9A-Fa-f,+\-]*;|\\(?:\d{1,3}|[A-Za-z])|%[-+0-9.]*[dsxXcb]")
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: the row's ``face`` (every drawn
Episode III row says font0), otherwise its 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)
ctx = tc.context(iso) if (iso and not FAKE and hasattr(tc, "context")) else None
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():
with (tc.disc(ctx) if ctx is not None else _nullctx()): # this row's disc, whatever the thread had
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]
if any("-byte limit (" in e for e in errors): # the family says why; drop the codec's bare line
errors = [e for e in errors if not e.endswith("-byte limit")]
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),) + _set_stamp(iso) # the guides span both discs: either one changing makes new ones
got = _LENGTH_GUIDES.get(key)
if got is not None:
return got
tc = _txcodec()
ctx = tc.context(iso) if hasattr(tc, "context") else None
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), keep=r["src"], ctx=ctx)[0] \
if ctx is not None else 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 hasattr(tc, "px_lines"): # Episode III: the game's line break is not a 0x0A byte
return tc.px_lines(m, row, 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 and _wrap_width(row, iso):
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]:
if row.get("use") == "choice": # each line of a choice is an option: never broken by the editor
return None
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]*\]|<[^<>\n]{1,40}>|[^ ])+") # a <k two words> tag is one word
def wrap_text(row: dict, text: str, iso: str, stand_in: 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. Letters in ``stand_in`` (the few a
script-hybrid target adds to the game font) are measured as "m"."""
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
ctx = tc.context(iso) if hasattr(tc, "context") else None
def px(line: str) -> int:
if stand_in:
line = "".join("m" if c in stand_in else c for c in line)
data = (tc.from_display(line, row["font"], row["ctl"], _face(row), keep=line, ctx=ctx)[0] if ctx is not None
else tc.from_display(line, row["font"], row["ctl"], _face(row))[0])
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 and not battle and hasattr(tt, "with_font"):
try: # a few missing Latin letters: the build takes a font itself
t2 = tt.with_font(t, glyph + (t.get("lacking") or ""))
fpath, fface = t2.get("font"), int(t2.get("face") or 0)
except tt.TargetError as exc:
errors.append(str(exc))
return errors, None, glyph, warnings
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))):
# stand-in codes B0B0.. with low bytes B0-FD: on the USA build a low byte
# A1-A4, A6 or AD would pair with the character typed after it
# (textcodec.us_pair) and the codec would refuse a line the build accepts
# (seen with a Cherokee caption, 2026-11-21: "A4 20 form a pair")
subs[c] = tc.glyph_char((0x80 + i % 0x60) if battle else (0xB0B0 + (i // 78) * 0x100 + i % 78))
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 = {"sb": "txfam_sb", "mnu": "txfam_mnu", "bat": "txfam_bat", "sub": "txfam_sub"}
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)
warnings: List[str] = []
if hasattr(mod, "check_row"): # Episode III: one row on its own (keyword links are a warning)
errors, warnings = mod.check_row(row["id"], text, iso)
return list(errors), list(warnings)
errors = list(mod.validate({row["id"]: text}, iso).get(row["id"], []))
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
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 tt.coverage(text, target, "field", face)["glyph"]:
if not target.get("font") and hasattr(tt, "with_font"):
try:
target = tt.with_font(target, tt.coverage(text, target, "field", face)["glyph"]
+ (target.get("lacking") or ""))
except tt.TargetError as exc:
raise ValueError(str(exc)) from None
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
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"] == "note":
raise ValueError("this string is never drawn by the game (a developers' note or a script "
"command); no preview")
face = _face(row)
tc = _txcodec()
warnings: List[str] = []
if tc is not None and hasattr(tc, "context"):
data, warnings = tc.from_display(text, row["font"], row["ctl"], face, ctx=tc.context(iso))
elif 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)
render_line = getattr(tc, "render_line", None)
if render_line is None:
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 (tc.preview_lines(data, row.get("ctl") or "") if hasattr(tc, "preview_lines") else 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", "ready", "font_auto")
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)