Repository navigation
Expand file tree
/
Copy pathgui.py
More file actions
2833 lines (2670 loc) · 150 KB
/
Copy pathgui.py
File metadata and controls
2833 lines (2670 loc) · 150 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
"""gui.py — Local web GUI for the Xenosaga Episode II Python Extractor.
Run me directly:
python gui.py # opens your browser on a free localhost port
python gui.py --no-browser # just print the URL
python gui.py --self-test
Stdlib only. The same design as the Episode I kit's GUI: a small HTTP server
on 127.0.0.1, a page with one card per command, and every command run as a
``cli.py`` subprocess whose output streams back live (Server-Sent Events).
The cards sit in sections by goal (Start here first, developer tools last),
each with a plain title, a one-line summary, what it needs and what it makes;
after a run the card says where its output is and can show it in the file
manager.
Unlike the Episode I GUI, the cards are not written by hand. They are built
from ``cli.py``'s own argparse parser when the GUI starts: every subcommand
becomes a card, every option a field (a checkbox for on/off flags, a list box
for options that repeat, a picker for disc images and folders). A command
added to ``cli.py`` later shows up here with no change to this file, in an
"Other commands" section with its argparse help as the summary. The
hand-written text lives in tables: GROUPS (the sections), COMMAND_CARDS (each
card's title, summary, needs and makes), COMMAND_HELP (the "More detail"
text) and FIELD_HINTS (labels, help and pickers, keyed by "command.option"
first, then by option name, then falling back to argparse's own help).
"""
from __future__ import annotations
import argparse
import http.server
from html import escape as html_escape
import json
import os
import queue
import re
import shlex
import shutil
import socket
import socketserver
import string
import subprocess
import sys
import tempfile
import threading
import time
import uuid
import webbrowser
from pathlib import Path
from typing import Dict, List, Optional
from urllib.parse import parse_qs, unquote, urlparse
ROOT = Path(__file__).resolve().parent
CLI = ROOT / "cli.py"
PY = sys.executable or "python3"
sys.path.insert(0, str(ROOT)) # the kit's modules, also under `python -I`
FROZEN = bool(getattr(sys, "frozen", False))
if FROZEN:
_cli_name = "xeno-cli.exe" if os.name == "nt" else "xeno-cli"
_cli_exe = Path(sys.executable).resolve().parent / _cli_name
CLI_ARGV: List[str] = [str(_cli_exe)]
CLI_TARGET = _cli_exe
RUNTIME_DIR = Path(getattr(sys, "_MEIPASS", Path(sys.executable).resolve().parent))
else:
CLI_ARGV = [PY, str(CLI)]
CLI_TARGET = CLI
RUNTIME_DIR = ROOT
TITLE = "Xenosaga II Extractor"
def _fatal(title: str, body: str) -> None:
msg = f"{title}\n\n{body}"
print(f"[gui] FATAL: {msg}", file=sys.stderr)
if os.name == "nt":
try:
import ctypes
ctypes.windll.user32.MessageBoxW(0, body, f"{TITLE} — {title}", 0x10)
except Exception:
pass
elif sys.platform == "darwin" and FROZEN:
# A double-clicked .app has no console; show the error in a dialog.
try:
esc = body.replace("\\", "\\\\").replace('"', '\\"')
subprocess.run(
["osascript", "-e",
f'display dialog "{esc}" with title "{TITLE} — {title}" '
'buttons {"OK"} default button 1 with icon stop'],
timeout=120, check=False,
)
except Exception:
pass
sys.exit(2)
# ---------------------------------------------------------------------------
# The command list, read from cli.py's own parser
# ---------------------------------------------------------------------------
class _Captured(Exception):
def __init__(self, parser):
super().__init__("parser captured")
self.parser = parser
def cli_parser(module=None) -> argparse.ArgumentParser:
"""cli.py's top-level parser, without running a command.
``cli.main`` builds its parser inline and calls ``parse_args`` once; for
the length of one call, ``parse_args`` is replaced by a hook that raises
with the parser in hand. If cli.py ever grows a ``build_parser()``, that
is used instead.
"""
if module is None:
import cli as module # noqa: F401 (also tells PyInstaller to bundle it)
if hasattr(module, "build_parser"):
return module.build_parser()
original = argparse.ArgumentParser.parse_args
def grab(self, args=None, namespace=None):
raise _Captured(self)
argparse.ArgumentParser.parse_args = grab
saved_argv = sys.argv
try:
try:
module.main([])
except TypeError:
sys.argv = [str(CLI)]
module.main()
except _Captured as c:
return c.parser
finally:
argparse.ArgumentParser.parse_args = original
sys.argv = saved_argv
raise RuntimeError("cli.main() returned without building a parser")
# ---------------------------------------------------------------------------
# Hand-written text. Everything here is optional: a command or option with no
# entry still gets a card or a field, built from its argparse help.
# ---------------------------------------------------------------------------
# The page's sections, in the order they are shown. A command the tables below
# do not know lands in the last one, so nothing cli.py adds is ever lost.
GROUPS = [
("start", "Start here",
"Unpack your discs, then turn the game's files into pictures, 3D models, sound and text your "
"computer can open. Steps 1 and 3 are all most people need; step 2 is an optional check."),
("look", "Look at one thing",
"Read-only tools that go straight to the disc, no unpacking needed. Nothing is changed."),
("pictures", "Change pictures",
"Each card writes a new copy of the disc image; your original is never changed. "
"To combine edits, give one card's output disc as the next card's Disc image."),
("text", "Change text",
"Export the text, edit it in any text editor, then put it back into a new copy of the disc. "
"To combine edits, give one card's output disc as the next card's Disc image. "
"Program text goes back last."),
("fonts", "Fonts and whole files",
"Draw new letters into the game's fonts as pictures, or swap any file on the disc for your own."),
("alphabet", "Translate into a new alphabet",
"For alphabets the game's font never had (Arabic, Hindi, Georgian...). First export and translate "
"the text (Change text), then draw the letters, then prepare the text. Preview a line any time "
"after the letters are drawn."),
("dev", "For developers",
"Lists, script readers and checks for people studying how the game works."),
("other", "Other commands",
"Commands added to the kit after this window's descriptions were written. Their text comes "
"straight from the command line's own help."),
]
OTHER_GROUP = "other"
# One entry per command: section, step number (only in a real sequence), a
# plain title, a one-line summary for the closed card, what it needs, what it
# makes, what to do next, and where its output lands (an option name, and a
# subfolder of it), so the page can offer to show it. HTML is allowed.
COMMAND_CARDS = {
"dump": {
"group": "start", "step": 1, "title": "Unpack the discs",
"summary": "Copies every game file off your disc images into a folder, unpacked, with a list of "
"them all. Start here.",
"needs": "Your disc image(s) (.iso): Disc 1, plus Disc 2 to get everything.",
"makes": "In the Output folder: <code>dump/</code> with one subfolder per data area (<code>chain0</code> "
"is on both discs, <code>chain1</code> is Disc 1's movies and voices, <code>chain2</code> "
"Disc 2's) and <code>manifest.csv</code>, the list of every file.",
"next": "Next: step 3, <b>Convert to files you can open</b>, with the same folder.",
"output": ("out", ""),
},
"verify": {
"group": "start", "step": 2, "title": "Check the unpacked files",
"summary": "Re-checks every unpacked file against the list made while unpacking, so you know "
"nothing was lost or damaged.",
"needs": "The Output folder of step 1.",
"makes": "Nothing on disk: a pass or fail count in the Output panel.",
"next": "Next: step 3, <b>Convert to files you can open</b>.",
"output": None,
},
"browse": {
"group": "start", "step": 3, "title": "Convert to files you can open",
"summary": "Turns the unpacked files into PNG pictures, 3D models for Blender (.glb), WAV sound, "
"MIDI and WAV music, readable text and scripts, and MP4 movies.",
"needs": "The Output folder of step 1 (it reads the <code>dump</code> folder in it). Movies need "
"ffmpeg.",
"makes": "A <code>browse/</code> folder inside it, one subfolder per kind: <code>textures_png</code>, "
"<code>xtx</code> (menu pictures), <code>models</code>, <code>audio</code>, "
"<code>music</code>, <code>movies</code>, <code>text</code>, ...",
"next": "Open the browse folder and look around. To change a picture: copy the browse folder, paint "
"over PNGs in the copy, then use <b>Put edited pictures back</b>.",
"output": ("out", "browse"),
},
"model": {
"group": "look", "title": "Export one 3D model for Blender",
"summary": "Writes one character or map straight from the disc as a .glb file, with its textures, "
"skeleton and animations. (Step 3 does every model at once.)",
"needs": "A disc image and the model's in-game path, e.g. <code>model\\char\\pc\\kosmos00.pxy</code>.",
"makes": "One <code>.glb</code> file (Blender: File > Import > glTF).",
"output": ("out", ""),
},
"dialogue": {
"group": "look", "title": "Read the script in play order",
"summary": "Every spoken and on-screen line in the order the game plays it, with speakers and "
"choices, plus the movie subtitles. Can also cut one voice clip per line.",
"needs": "Your disc image(s): both discs for every scene. Voice clips need ffmpeg.",
"makes": "A folder with one transcript per scene, subtitle files (<code>.srt</code>), "
"<code>dialogue.csv</code>, and WAV clips if <b>Voice clips</b> is ticked.",
"output": ("out", ""),
},
"texture-import": {
"group": "pictures", "title": "Put edited pictures back",
"summary": "Paint over PNGs in a copy of the browse folder, then give that folder here. Only the "
"pictures you changed are written, into every copy of them on the disc.",
"needs": "A disc image, and a copy of the browse folder (step 3, with pictures, menu pictures and "
"3D models ticked) holding your edited PNGs. Run it once per disc.",
"makes": "A new disc image (.iso) and a CSV list of the changed pictures. Tick <b>Dry run</b> first "
"to see what would change without writing anything.",
"next": "Test the new disc image in an emulator such as PCSX2. For more edits, give it as the next "
"card's Disc image.",
"output": ("out", ""),
},
"recolor": {
"group": "pictures", "title": "Recolour textures (quick)",
"summary": "Shifts the colour of named textures everywhere they appear; by default it turns "
"KOS-MOS's hair pink. Colours only: it cannot redraw anything.",
"needs": "A disc image. Tick <b>Dry run</b> and give a Preview folder to look before writing.",
"makes": "A new disc image (.iso); with a Preview folder, before/after PNGs.",
"next": "Test the new disc image in an emulator such as PCSX2.",
"output": ("out", ""),
},
"text-export": {
"group": "text", "title": "Export the game text to edit",
"summary": "Writes the dialogue, menus, battle messages, quest text, subtitles and save title as "
"plain text files you can edit in any text editor.",
"needs": "A disc image.",
"makes": "A text folder, one UTF-8 file per text object. Use an empty folder of its own.",
"next": "To find a line, search this folder for a few of its words (most text editors have "
"<em>Find in Files</em>) and edit it in place (lines starting with # are notes), then use <b>Put edited text back</b> with the same disc and "
"this folder.",
"output": ("out", ""),
},
"text-import": {
"group": "text", "title": "Put edited text back",
"summary": "Writes your edited text folder into a new copy of the disc. A line too long for its "
"space is refused and nothing is written.",
"needs": "The same disc image you exported from, and the folder <b>Export the game text to edit</b> made, "
"after your edits.",
"makes": "A new disc image (.iso). The original is not changed.",
"next": "Test the new disc image in an emulator such as PCSX2. For more edits, give it as the next "
"card's Disc image.",
"output": ("out", ""),
},
"exe-export": {
"group": "text", "title": "Export the text inside the game program",
"summary": "The few messages stored in the game's program files (Saving..., memory-card prompts, "
"Total Exp) as editable text, each with its size limit.",
"needs": "A disc image (USA).",
"makes": "A text folder, one block per message with its byte limit.",
"next": "Edit the messages (each within its limit), then <b>Put program text back</b>, after every "
"other edit.",
"output": ("out", ""),
},
"exe-import": {
"group": "text", "title": "Put program text back (do this last)",
"summary": "Writes the edited program messages back in place, each within its limit. Do it last: "
"afterwards the text, font and alphabet cards refuse that disc image.",
"needs": "Your latest modified disc image (e.g. the one <b>Put edited text back</b> made) and the "
"folder <b>Export the text inside the game program</b> made, after your edits.",
"makes": "A new disc image (.iso).",
"next": "Test the new disc image in an emulator such as PCSX2.",
"output": ("out", ""),
},
"font-extract": {
"group": "fonts", "title": "Export the fonts as pictures",
"summary": "Saves the game's two fonts (font0 for movies and cutscenes, font1 for dialogue and "
"menus) as PNG sheets you can draw on, with each letter's spacing as a spreadsheet.",
"needs": "A disc image.",
"makes": "A folder with the two font files, their sheet PNGs, spacing CSVs and the "
"byte-to-letter table.",
"next": "Draw on the sheet PNGs, then <b>Build a font from edited sheets</b> with this folder.",
"output": ("out", ""),
},
"font-rebuild": {
"group": "fonts", "title": "Build a font from edited sheets",
"summary": "Turns your edited font sheets (and spacing) back into a font file the game reads.",
"needs": "The folder <b>Export the fonts as pictures</b> made, with your edits, and the original "
"font file in it.",
"makes": "One font file (e.g. <code>new_font0.us</code>).",
"next": "Put it on a disc copy with <b>Replace a file on the disc</b>: "
"<code>chain0:font0.us=</code> then this file.",
"output": ("out", ""),
},
"patch": {
"group": "fonts", "title": "Replace a file on the disc",
"summary": "Puts files you supply in place of game files, in a new copy of the disc (e.g. a rebuilt "
"font).",
"needs": "A disc image and one line per file: data area, in-game path, then your file.",
"makes": "A new disc image (.iso).",
"next": "Test the new disc image in an emulator such as PCSX2. For more edits, give it as the next "
"card's Disc image.",
"output": ("out", ""),
},
"lang-scan": {
"group": "alphabet", "title": "Draw the new letters",
"summary": "Reads your translated text and a TrueType font, and draws every letter the "
"translation needs into new game fonts. Once per alphabet.",
"needs": "The USA disc image, your translated copy of the <b>Export the game text to edit</b> folder, and a "
".ttf/.otf font with your alphabet.",
"makes": "A folder with the new <code>font0.us</code> and <code>font1.us</code>, "
"<code>glyphset.json</code> (the map from letters to game codes) and a preview sheet.",
"next": "Next: <b>Prepare the translated text</b> with the <code>glyphset.json</code> in this "
"folder. <b>Preview a translated line</b> works now too.",
"output": ("out", ""),
},
"lang-encode": {
"group": "alphabet", "title": "Prepare the translated text",
"summary": "Rewrites your translation with the new letters' codes, in the order the game draws "
"them, wrapped and checked against every length limit.",
"needs": "Your translated text folder and the <code>glyphset.json</code> from <b>Draw the new "
"letters</b>.",
"makes": "An encoded text folder, ready for <b>Put edited text back</b>.",
"next": "Put the two new fonts on a disc copy with <b>Replace a file on the disc</b> "
"(<code>chain0:font0.us=...</code> and <code>chain0:font1.us=...</code>), then <b>Put edited "
"text back</b> on that copy with this folder.",
"output": ("out", ""),
},
"lang-preview": {
"group": "alphabet", "title": "Preview a translated line",
"summary": "Draws one line with the new font the way the game would, so you can check it without "
"starting the game.",
"needs": "The <code>glyphset.json</code> from <b>Draw the new letters</b> and a line of text.",
"makes": "A PNG picture of the line.",
"output": ("out", ""),
},
"list": {
"group": "dev", "title": "List every file on the disc",
"summary": "Prints the game's own index of its files: data area, position, size and in-game path. "
"Handy for finding paths for other cards.",
"needs": "Your disc image(s).",
"makes": "Nothing on disk: the list appears in the Output panel.",
"output": None,
},
"sb": {
"group": "dev", "title": "Read one scene script",
"summary": "Shows one scene or map script (an .sb file) as readable instructions, each spoken line "
"beside the instruction that uses it.",
"needs": "A disc image and the script's in-game path, e.g. <code>cf\\sc1010.sb</code>.",
"makes": "Nothing on disk: the listing appears in the Output panel.",
"output": None,
},
"natives": {
"group": "dev", "title": "Survey the game functions scripts call",
"summary": "Counts every built-in game function the scripts call (\"natives\", such as "
"bat.msgPut) and the kinds of values passed; can also save every script as a listing.",
"needs": "Your disc image(s).",
"makes": "A report in the Output panel; with a folder given, also <code>natives.tsv</code>, "
"<code>listings/</code> and <code>strings.tsv</code>.",
"output": ("out", ""),
},
"text-coverage": {
"group": "dev", "title": "Report where the game shows text",
"summary": "Counts every place the game shows text and says what the kit can do with each: "
"editable text, program text, or words drawn into pictures and movies.",
"needs": "Your disc image(s).",
"makes": "A report in the Output panel, and a TSV file if you give one.",
"output": ("tsv", ""),
},
"self-test": {
"group": "dev", "title": "Check the kit works",
"summary": "Runs the kit's own built-in checks. No disc needed.",
"needs": "Nothing.",
"makes": "Nothing on disk: a pass or fail report in the Output panel.",
"output": None,
},
}
# The longer explanation behind each card's "More detail". A command without
# an entry simply has no "More detail".
COMMAND_HELP = {
"list": "Print every entry of the game's own index of files (its table of contents): data area, sector, "
"size and in-game path. The game keeps its files in three data areas, called chains: chain 0 is "
"the shared data (on both discs), chain 1 is Disc 1's movies and voices, chain 2 is Disc 2's.",
"dump": "Unpack the disc images into <code>OUT/dump/chain0</code>, <code>chain1</code> and "
"<code>chain2</code> (the three data areas), with <code>OUT/manifest.csv</code> listing every "
"file (position, size, checksum, kind). Give both discs to get all three. Files packed with the "
"game's own compression (ARX) are written unpacked.",
"verify": "Re-checks every unpacked file's checksum against <code>manifest.csv</code>. Files that were "
"compressed on the disc are compressed again with the kit's copy of the game's packer and "
"compared byte for byte, so a clean run proves the unpacking works both ways.",
"browse": "Convert the unpacked files into files your computer opens, under <code>OUT/browse/</code>: "
"textures and menu pictures as PNG, every model as a <code>.glb</code> Blender opens "
"(textured, with its skeleton), sound effects and voices as WAV, songs as MIDI + SoundFont "
"and a WAV rendered the way the PS2 plays it, dialogue as UTF-8 text, scripts as readable "
"listings, movies as MP4 (needs ffmpeg).",
"model": "One model straight from the disc to a <code>.glb</code> for Blender: the mesh with the "
"textures and skeleton of the same name, and its animation files (<code>.xap</code>) as "
"animations, one action per clip at 30 frames per second. Step 3 does every model at once.",
"sb": "Turns one scene or map script (<code>.sb</code>, the game's compiled script files) into a "
"readable listing, with every call into the game program named and every spoken line shown beside "
"the instruction that uses it.",
"text-export": "Write the game's text to an editable UTF-8 folder, one file per text object: dialogue, "
"menus (item, skill and location names, help, the database, the Skill Tutorial), the battle "
"names and messages, the battle banners, the quest, citizen and treasure text, movie "
"subtitles and the save's title in the memory-card browser. Each file is named after the "
"game file it comes from, inside a <code>chain0</code>, <code>chain1</code> or "
"<code>chain2</code> folder (the data area), so the quickest way to find a line is to "
"search the whole folder for a few of its words. In most files each line of text sits under "
"its own <code>###</code> heading; lines starting with <code>#</code> are notes. "
"Text inside the game program is <em>exe-export</em>.",
"text-import": "Writes the edited text folder into a <em>copy</em> of the disc. Each kind of text keeps "
"to the room the game allows for it; anything past a limit is refused and nothing is "
"written. More detail: dialogue and menus must fit their space, a longer battle string "
"moves the rest of its section down within the file, quest texts must fit their fields. "
"The memory-card slot number and the Skill Tutorial's commands are kept; a battle banner "
"edited in one copy but not the others gets a note. An unedited folder imports as no "
"change, and every write is read back to check it.",
"dialogue": "Every spoken and displayed line in the order the game plays it: one transcript per scene, "
"field and battle script, with speakers, choices, battle banners and branches; the movies' "
"and real-time cutscenes' subtitles as SRT; and <code>dialogue.csv</code>. Each line keeps "
"its number, so it maps back to the <em>text-export</em> block you would edit. "
"<em>Voice clips</em> also cuts one WAV per timed line (ffmpeg). Read only: it changes "
"nothing.",
"font-extract": "The two fonts (<code>font0</code> for movies and cutscenes, <code>font1</code> for "
"dialogue and menus) as PNG sheets of 20x24-pixel cells, a CSV of each cell's left and "
"right spacing, and the table of which byte draws which cell. Draw new letters on the "
"sheets, then use <em>font-rebuild</em>.",
"font-rebuild": "Build a font file from edited sheets and spacing, starting from the original font file. "
"A folder without any edited sheet or spacing is refused unless <em>Allow no changes</em> "
"is ticked. Put the new font on a copy of the disc with <em>patch</em> "
"(<code>chain0:font0.us=...</code>).",
"natives": "Natives are the functions inside the game program that scripts call, such as "
"<code>bat.msgPut</code>. This lists every one with how often it is called and the kinds of "
"values passed. With a folder, it also writes a readable listing of every script.",
"recolor": "Shifts the colour of named textures in every copy on a <em>copy</em> of the disc. Textures "
"are found by their name inside the game's texture files (on their own and inside effect "
"files); the default recolours KOS-MOS's hair. <em>One menu sheet instead</em> colourises one "
"full-colour menu picture, such as the title menu words. Colours only: it cannot redraw words.",
"exe-export": "Write the messages stored in the game program (the main program file, SLUS, and its two "
"add-on code files OV01.OVL and OV02.OVL: <em>Saving...</em>, the memory-card prompts, "
"<em>Total Exp</em>) to an editable folder, one <code>### @ADDRESS max N bytes</code> block "
"per message.",
"exe-import": "Writes the edited messages back <em>in place</em> into a copy of the disc: each at most "
"its <code>max N</code> bytes, the rest of its space filled with zeros. Run it <em>last</em>: "
"afterwards the program is no longer the original, and text-import, font-extract and "
"lang-scan refuse the image. For another round, give the original disc as <em>Original "
"disc</em>.",
"text-coverage": "Lists every place the game shows text and what the kit does with it, counted from the "
"disc: the text it edits, the messages in the game program, and the words drawn into "
"pictures and movies (those need picture editing). <em>Also check round trip</em> also "
"checks that unedited exports import as no change.",
"patch": "Replace whole files in a copy of the disc. One replacement per line: the data area "
"(<code>chain0</code> is on both discs, <code>chain1</code>/<code>chain2</code> are Disc 1's and "
"Disc 2's movies and voices), a colon, the in-game path, <code>=</code>, and your file, e.g. "
"<code>chain0:font0.us=/path/to/new_font0.us</code>.",
"lang-scan": "For an alphabet the game never had: shapes the translated text with a TrueType font (joined "
"letters, right-to-left order), gives every letter a code the USA game can draw, and writes "
"<code>font0.us</code>, <code>font1.us</code>, <code>glyphset.json</code> and a preview "
"sheet. Run it once per alphabet; a second alphabet starts from the first one's files "
"(<em>Earlier ...</em> fields). See <code>docs/ALPHABETS.md</code>.",
"lang-encode": "Turns the translated folder into the same folder with the new letters written as codes, "
"in the order the game draws them (right-to-left lines reordered), wrapped and checked "
"against every byte limit. Nothing is written if a letter or a limit is missing. Then put "
"the two fonts on a disc copy and run <code>text-import</code> on it.",
"lang-preview": "Draws one line with the rebuilt font to a PNG, placing the cells the way the game's own "
"print function does, to check a translation without the game.",
"texture-import": "Edit PNGs in a copy of the <code>browse</code> folder (textures, menu pictures, or the "
"images inside a model's <code>.glb</code>) and give that folder here. Only PNGs that "
"differ from the disc are written, into a <em>copy</em> of the disc, and every other copy "
"of the same picture on the disc is updated too. Shared colour tables (palettes) are kept "
"for the other textures that use them. Chain 0 (the shared data) is on both discs: run it "
"once per disc. <em>Dry run</em> shows what would change without writing.",
"self-test": "Runs every module's built-in checks (no disc needed).",
}
# Words the cards use, explained once at the top of the page.
GLOSSARY = [
("Disc image", "a copy of a game disc as one <code>.iso</code> file"),
("Data area (chain)", "the game keeps its files in three areas: chain 0 is the shared data on both discs, "
"chain 1 is Disc 1's movies and voices, chain 2 is Disc 2's"),
("In-game path", "a file's name inside the game, e.g. <code>model\\char\\pc\\kosmos00.pxy</code>; "
"<b>List every file on the disc</b> shows them all"),
("ARX", "the game's own compression"),
("Index of files (TOC)", "the game's own table of contents of its files"),
(".sb script", "a compiled scene or map script"),
("Natives", "functions inside the game program that scripts call"),
("Game program (SLUS, overlays)", "the main program file on the disc and its add-on code files"),
(".glb", "a 3D model file Blender opens"),
("Menu pictures (xtx)", "full-colour pictures used by menus and the title screen"),
("glyphset.json", "the map from your alphabet's letters to the codes the game draws"),
]
# Field text keyed by option name, or by "command.option" for one command
# only (looked up first). Keys: label, help (shown under the field; replaces
# the argparse help), placeholder (an example), pick (file, dir, save), filter,
# suggest (the file name a Save-as picker adds), prefill (the starting value:
# {out} = the suggested output folder, {disc} = the first disc found, {discs} =
# every disc found, "" = start empty), choices (value -> plain text for a list
# box), tri (three plain choices for an on/off pair of flags), advanced (True:
# shown under the card's "More settings", for fields most people leave alone),
# required_unless (marks an optional option REQUIRED, except when one of these
# other fields of the card is filled in or ticked).
FIELD_HINTS = {
"iso": {"label": "Disc image", "pick": "file", "filter": "iso",
"help": "One disc image (.iso): Disc 1 or Disc 2.",
"help_multi": "Your disc images, one per line: Disc 1 and Disc 2 to cover everything."},
"out": {"label": "Output folder", "pick": "dir"},
"text": {"label": "Text folder", "pick": "dir"},
"retail": {"label": "Original disc", "pick": "file", "filter": "iso",
"help": "Only for a second round: the original disc image, whose program files are used as the "
"starting point."},
"dump": {"label": "Unpacked folder", "pick": "dir"},
"path": {"label": "In-game path"},
"glob": {"label": "Only matching paths", "placeholder": "e.g. model\\char\\pc\\*",
"help": "Optional: only in-game paths matching this pattern (* matches anything)."},
"limit": {"label": "At most (per kind)", "placeholder": "e.g. 20",
"help": "Optional: convert only this many files of each kind, for a quick sample."},
"chain": {"label": "Data area",
"help": "The game keeps its files in three areas (chains). Leave on All unless you want one.",
"choices": [["", "All areas"], ["0", "0: shared data (on both discs)"],
["1", "1: Disc 1 movies and voices"], ["2", "2: Disc 2 movies and voices"]]},
"font": {"label": "TrueType font", "pick": "file"},
"glyphset": {"label": "Letter map (glyphset.json)", "pick": "file", "filter": "json",
"prefill": "{out}/lang/glyphset.json",
"help": "The glyphset.json that <b>Draw the new letters</b> wrote."},
"dry_run": {"label": "Dry run"},
"preview": {"label": "Preview folder", "pick": "dir"},
"grow": {"label": "Allow moving"},
"space_px": {"label": "Space width (pixels)"},
"width": {"label": "Wrap width (pixels)",
"help": "Wrap lines at this many pixels for every kind of text; 0 = do not wrap "
"(subtitles wrap at 440)."},
"align": {"label": "Line alignment", "help": "Right alignment suits right-to-left alphabets.",
"choices": {"left": "left", "right": "right (pads right-to-left lines of dialogue and menus)"}},
"rtl": {"label": "Right-to-left order",
"help": "Right-to-left alphabets are stored in reading order; the game draws left to right, so "
"their lines are reordered.",
"tri": ["Automatic: reorder when the alphabet is right to left",
"Always reorder right-to-left paragraphs", "Never reorder"]},
"dump.out": {"label": "Output folder", "prefill": "{out}",
"help": "Where the unpacked files go. Keep it: steps 2 and 3 read this folder."},
"dump.raw": {"label": "Keep compressed",
"help": "Leave files the game keeps compressed (ARX) as they are instead of unpacking them. "
"Most people leave this off."},
"dump.code": {"label": "Program files too",
"help": "Also copy the game's program files: the main program (SLUS), its add-on code files "
"(overlays) and the sound-chip modules (IOP). The music modules that step 3 needs are "
"always copied."},
"verify.out": {"label": "Unpacked folder", "prefill": "{out}",
"help": "The Output folder you gave <b>Unpack the discs</b>."},
"browse.out": {"label": "Unpacked folder", "prefill": "{out}",
"help": "The Output folder you gave <b>Unpack the discs</b>. The converted files go into "
"its browse subfolder."},
"browse.kinds": {"label": "What to convert",
"help": "Untick what you do not need. Movies need ffmpeg; music WAVs need numpy.",
"choices": {"textures": "pictures (textures)", "models": "3D models",
"xtx": "menu pictures (xtx)", "fonts": "fonts", "text": "text",
"scripts": "scripts", "audio": "sound effects and voices", "music": "music",
"images": "photos (JPEG)", "movies": "movies",
"small": "small files (logos, save icon, packs)"}},
"browse.movie_audio": {"label": "Movie sound", "help": "Which sound track the MP4 movies get.",
"choices": {"adx": "the stereo track (ADX, the movies' own sound format), "
"converted to AAC",
"ac3": "the 5.1 surround track (AC-3), copied as is",
"both": "both tracks"}},
"model.path": {"label": "Model's in-game path", "placeholder": "e.g. model\\char\\pc\\kosmos00.pxy",
"help": "Where the model sits on the disc. Find paths with <b>List every file on the disc</b> "
"or in browse/models."},
"model.out": {"label": "Save as (.glb)", "pick": "save", "filter": "glb", "suggest": "model.glb",
"prefill": "{out}/model.glb", "help": "The .glb file to write."},
"model.motion": {"label": "Extra animation files", "placeholder": "e.g. motion\\shion00.xap",
"help": "Optional: animation files on the disc (.xap or .fap) to add, one per line; add "
"#0,1 to pick clips. Empty = the ones with the model's name."},
"model.slots": {"label": "Only these clips", "placeholder": "e.g. 0,1,2",
"help": "Optional: clip numbers to keep from each animation file. Empty = every clip."},
"model.face": {"label": "Face animations",
"help": "Also add the facial expression clips (motion\\face_all.fap) that fit this skeleton."},
"model.no_motion": {"label": "No animations", "help": "Mesh and skeleton only."},
"model.matched_only": {"label": "Only clips that fit",
"help": "Leave out clips made for a different number of bones. By default they are "
"written, with the counts in the animation's name."},
"sb.path": {"label": "Script's in-game path", "placeholder": "e.g. cf\\sc1010.sb",
"help": "A scene or map script (.sb). Find paths with <b>List every file on the disc</b>."},
"natives.glob": {"label": "Only matching scripts", "placeholder": "e.g. yamamoto\\think\\*",
"help": "Optional: only scripts whose in-game path matches this pattern (* matches anything)."},
"natives.out": {"label": "Save listings to", "prefill": "",
"help": "Optional folder: also writes natives.tsv, one readable listing per script "
"(listings/) and strings.tsv."},
"recolor.out": {"label": "Output disc", "suggest": "modded-recolor.iso", "prefill": "{out}/modded-recolor.iso",
"help": "The new disc image to write. Empty = nothing is written (tick Dry run to only "
"look). Your original disc is never changed."},
"recolor.preset": {"label": "Preset", "help": "A ready-made set of textures to recolour.", "choices": {"": "KOS-MOS's hair (when no rules are given)",
"kosmos-hair": "KOS-MOS's hair"}},
"recolor.rule": {"label": "Rules", "placeholder": "e.g. kosmos*_hair_col=all",
"help": "Optional: which textures to recolour, one per line: a texture-name pattern, then "
"=all (every colour) or =blue (only the blue tones). Rules without a preset replace "
"the KOS-MOS preset."},
"recolor.hue": {"label": "New colour (hue)",
"help": "0 to 1 around the colour wheel: 0 red, 0.33 green, 0.66 blue, 0.92 pink."},
"recolor.preview": {"help": "Optional: writes before/after PNGs of every changed texture here."},
"recolor.dry_run": {"help": "Show what would change; write no disc."},
"recolor.xtx": {"label": "One menu picture instead", "placeholder": "e.g. yajima\\titleobj.xtx",
"help": "Optional: colourise the full-colour menu picture (.xtx) at this in-game path instead "
"of the named textures. Needs an Output disc."},
"texture-import.out": {"label": "Output disc", "suggest": "modded-textures.iso",
"prefill": "{out}/modded-textures.iso",
"required_unless": ["dry_run", "verify_roundtrip"],
"help": "The new disc image to write. Can stay empty only when Dry run or Self-check only "
"is ticked."},
"texture-import.tree": {"label": "Edited browse folder", "pick": "dir", "prefill": "",
"required_unless": ["textures", "xtx", "models", "verify_roundtrip"],
"placeholder": "a copy of your browse folder, with edited PNGs",
"help": "Run step 3 (pictures, menu pictures, 3D models), copy its browse folder, "
"paint over PNGs in the copy and give the copy here. Only pictures that "
"differ from the disc are written. (Under More settings you can give "
"single folders instead.)"},
"texture-import.textures": {"label": "Pictures folder", "pick": "dir", "advanced": True,
"help": "Use this textures_png folder instead of the one in the edited browse folder."},
"texture-import.xtx": {"label": "Menu pictures folder", "pick": "dir", "advanced": True,
"help": "Use this xtx folder instead of the one in the edited browse folder."},
"texture-import.models": {"label": "Models folder", "pick": "dir", "advanced": True,
"help": "Use this folder of .glb models (their images) instead of the one in the "
"edited browse folder."},
"texture-import.palette": {"label": "Shared colours", "advanced": True,
"help": "Many textures share one colour table (palette).",
"choices": {"auto": "keep the colours of the other textures that share it",
"keep": "never change a colour table",
"joint": "recompute the table for every texture that shares it"}},
"texture-import.dither": {"label": "Dithering", "advanced": True,
"help": "How colours are reduced when a texture has only a few to choose from.",
"choices": {"none": "none", "fs": "Floyd-Steinberg (mixes pixels to fake more colours)"}},
"texture-import.sweep": {"label": "Other copies", "advanced": True,
"help": "The disc holds several copies of many pictures.",
"choices": {"pixels": "update every copy with the same pixels",
"name": "only copies with the same texture name",
"none": "only the picture you edited"}},
"texture-import.mips": {"label": "Smaller versions", "advanced": True,
"help": "Textures carry smaller copies of themselves (mip levels) for distant objects.",
"choices": {"rebuild": "rebuild them from your edit", "keep": "leave them as they are"}},
"texture-import.grow": {"advanced": True,
"help": "Only if a run says an edited file no longer fits its space: let that file "
"move to the end of the disc image. The kit checks the moved file, but such "
"a disc has not yet been tried in the game itself."},
"texture-import.dry_run": {"help": "List what would change and write nothing. A safe first try."},
"texture-import.preview": {"help": "Optional: writes before/after PNGs of every changed picture here."},
"texture-import.report": {"label": "Change list", "pick": "save", "filter": "csv", "advanced": True,
"suggest": "textures.csv", "prefill": "",
"help": "Where to save the CSV of changed pictures. Empty = next to the output disc."},
"texture-import.verify_roundtrip": {"label": "Self-check only", "advanced": True,
"help": "Write nothing: re-encode every texture on the disc from its own "
"picture and check the bytes come back identical. This checks "
"the kit, not your edits."},
"text-export.out": {"label": "Text folder to create", "prefill": "{out}/text",
"help": "An empty folder of its own; one text file per text object is written here."},
"dialogue.out": {"prefill": "{out}/dialogue", "help": "Where the transcripts and subtitles go."},
"dialogue.voice": {"label": "Voice clips",
"help": "Also cut one WAV per timed line from the movies and cutscene voice tracks "
"(needs ffmpeg)."},
"dialogue.only": {"label": "Only scenes", "placeholder": "e.g. 1001",
"help": "Optional: only scenes or movies whose name contains this, one per line."},
"text-import.iso": {"help": "The same disc image you exported the text from."},
"text-import.text": {"label": "Edited text folder", "prefill": "{out}/text",
"help": "The folder <b>Export the game text to edit</b> made, after your edits."},
"text-import.out": {"suggest": "modded-text.iso", "prefill": "{out}/modded-text.iso",
"help": "The new disc image to write. Your original disc is never changed."},
"text-import.grow": {"help": "Let a text file that outgrows its space move to the end of the disc image, "
"within the room the game's loader has (read from the code; not yet seen in the "
"running game)."},
"text-import.rebase": {"label": "Apply to another disc",
"help": "Apply the text even though this is not the disc it was exported from (another "
"revision, or an already modified copy). The check against the export is "
"skipped."},
"exe-export.out": {"label": "Text folder to create", "prefill": "{out}/exe",
"help": "An empty folder of its own; the editable messages are written here."},
"exe-import.iso": {"prefill": "", "placeholder": "your latest modified disc image, or the original",
"help": "Start from your latest modified disc image, so your earlier edits are kept."},
"exe-import.text": {"label": "Edited program-text folder", "prefill": "{out}/exe",
"help": "The folder <b>Export the text inside the game program</b> made, after your edits."},
"exe-import.out": {"suggest": "modded-exe.iso", "prefill": "{out}/modded-exe.iso",
"help": "The new disc image to write."},
"text-coverage.verify": {"label": "Also check round trip",
"help": "Also export everything and check that unedited exports import as no change "
"(slower)."},
"text-coverage.tsv": {"label": "Save report as", "pick": "save", "filter": "tsv",
"suggest": "coverage.tsv", "prefill": "", "help": "Optional: also save the report as a TSV file."},
"text-coverage.tex_words": {"label": "Words in pictures",
"help": "Also list textures with words a player reads (they need picture editing)."},
"font-extract.out": {"label": "Folder to create", "prefill": "{out}/fonts",
"help": "Where the font files, sheet PNGs and spacing CSVs go."},
"font-rebuild.ref": {"label": "Original font file", "pick": "file", "prefill": "{out}/fonts/font0.us",
"help": "The font file <b>Export the fonts as pictures</b> saved (font0.us or font1.us); "
"the new font starts from it."},
"font-rebuild.sheets": {"label": "Edited sheets folder", "pick": "dir", "prefill": "{out}/fonts",
"help": "The folder with your edited sheet PNGs (font0_sheet0.png to _sheet3.png)."},
"font-rebuild.metrics": {"label": "Edited spacing", "pick": "file", "filter": "csv",
"help": "Optional: the edited spacing CSV, e.g. font0_metrics.csv."},
"font-rebuild.allow_unchanged": {"label": "Allow no changes",
"help": "Write a plain copy of the original when no edited sheet or spacing "
"is found (otherwise refused)."},
"font-rebuild.out": {"label": "Save as", "pick": "save", "suggest": "new_font0.us",
"prefill": "{out}/new_font0.us", "help": "The new font file to write."},
"patch.out": {"suggest": "modded-patch.iso", "prefill": "{out}/modded-patch.iso",
"help": "The new disc image to write."},
"patch.set": {"label": "Replacements", "placeholder": "chain0:font0.us=/path/to/new_font0.us",
"help": "One per line: the data area (chain0 = shared data on both discs; chain1, chain2 = "
"Disc 1's, Disc 2's movies and voices), a colon, the in-game path, =, then your file."},
"patch.grow": {"help": "Let a file bigger than its space move to the end of the disc image."},
"patch.relocate": {"advanced": True, "label": "Always move (test)",
"help": "Put every replacement at the end of the image even if it fits (to test moving)."},
"lang-scan.iso": {"help": "The USA disc image the translation is for."},
"lang-scan.text": {"label": "Translated text folder", "prefill": "",
"placeholder": "your translated copy of the text folder",
"help": "Your translated copy of the <b>Export the game text to edit</b> folder (one per line for "
"more than one)."},
"lang-scan.font": {"filter": "", "help": "A .ttf, .otf or .ttc font that has your alphabet; the letters are "
"drawn from it."},
"lang-scan.face": {"advanced": True, "label": "Font number in a .ttc",
"help": "Only for .ttc collections: which font inside it (0 = the first)."},
"lang-scan.px": {"label": "Letter size (pixels)",
"help": "Font size in pixels; 18 puts Latin capitals where the game's own are."},
"lang-scan.baseline": {"advanced": True, "label": "Baseline row",
"help": "The pixel row the letters stand on in the 24-pixel-high cell."},
"lang-scan.script": {"label": "Alphabet code", "placeholder": "e.g. Arab, Deva, Geor",
"help": "Optional: a four-letter ISO 15924 alphabet code; only words in this alphabet "
"are scanned."},
"lang-scan.language": {"label": "Language code", "placeholder": "e.g. ar, hi, ka",
"help": "Optional: a language code (BCP-47), so letters join the way that language "
"writes them."},
"lang-scan.rtl": {"label": "Right to left", "help": "The alphabet is written right to left (Arabic, Hebrew...)."},
"lang-scan.cells": {"advanced": True, "label": "Hand-drawn letters (PNG)", "pick": "file", "filter": "png",
"help": "Optional, instead of a font: a PNG sheet of hand-drawn 20x24-pixel letter cells."},
"lang-scan.keys": {"advanced": True, "label": "Letters in that sheet", "pick": "file",
"help": "With hand-drawn letters: a text file naming the letter in each cell, one per line."},
"lang-scan.prefer": {"advanced": True, "label": "Codes to fill first",
"help": "Text with tight byte limits takes one-byte codes first anyway.",
"choices": {"single": "one-byte codes", "pair": "two-byte codes",
"fixed": "fixed-width two-byte cells (for wide letters)"}},
"lang-scan.keep": {"advanced": True, "label": "Letters to keep", "placeholder": "e.g. éèàç",
"help": "Optional: accented Latin letters whose cells must stay as they are."},
"lang-scan.reclaim": {"advanced": True, "label": "Free reserved codes", "placeholder": "e.g. FC",
"help": "Optional: reserved one-byte codes to free up, in hex, comma-separated."},
"lang-scan.prop_only": {"advanced": True, "label": "Narrow cells only",
"help": "Refuse letters too wide for the narrow (proportional) cells."},
"lang-scan.tight": {"advanced": True, "label": "Touching letters",
"help": "Draw ink to the cell edge so joining letters touch (worked out from the code, not "
"yet seen in the game)."},
"lang-scan.space_px": {"advanced": True, "help": "Width of a space, for the line-width report."},
"lang-scan.font0": {"advanced": True, "label": "Earlier font0.us", "pick": "file",
"help": "For a second alphabet: the font0.us an earlier scan wrote (give font1.us too)."},
"lang-scan.font1": {"advanced": True, "label": "Earlier font1.us", "pick": "file",
"help": "For a second alphabet: the font1.us an earlier scan wrote (give font0.us too)."},
"lang-scan.extend": {"advanced": True, "label": "Earlier glyphset.json", "pick": "file", "filter": "json",
"help": "For a second alphabet: the glyphset.json an earlier scan wrote; its codes are kept."},
"lang-scan.out": {"label": "Folder to create", "prefill": "{out}/lang",
"help": "Where the new fonts, glyphset.json and the preview sheet go."},
"lang-encode.text": {"label": "Translated text folder", "prefill": "", "pick": "dir",
"placeholder": "your translated copy of the text folder",
"help": "Your translated copy of the <b>Export the game text to edit</b> folder."},
"lang-encode.out": {"label": "Folder to create", "prefill": "{out}/text-encoded",
"help": "The encoded text folder; <b>Put edited text back</b> reads it."},
"lang-encode.space_px": {"help": "Width of a space; the game's is 9."},
"lang-encode.width_kind": {"label": "Wrap width per kind", "placeholder": "e.g. subtitle=440",
"help": "Optional, one per line: a kind of text (bank = dialogue, menu, subtitle, "
"battle, exe = program text), =, then a width in pixels."},
"lang-encode.iso": {"label": "Disc copy with new fonts, to check", "prefill": "",
"help": "Optional: a disc copy with the two new fonts already put in. The encoded text is "
"then test-imported into it (nothing written) to catch problems early."},
"lang-preview.line": {"label": "Line of text", "placeholder": "the line as you would write it in the text file",
"help": "Written the way you would type it in the translated text file."},
"lang-preview.out": {"label": "Save as (PNG)", "pick": "save", "filter": "png", "suggest": "line.png",
"prefill": "{out}/lang/line.png",
"help": "The PNG to write (several lines: NAME_0.png, NAME_1.png, ...)."},
"lang-preview.space_px": {"help": "Width of a space; the game's is 9."},
"lang-preview.scale": {"label": "Zoom", "help": "Enlarge the picture this many times."},
"lang-preview.face": {"label": "Which font", "help": "The game draws with two fonts.",
"choices": {"font1": "font1: dialogue, menus and battle",
"font0": "font0: movies and real-time cutscenes"}},
"lang-preview.kind": {"label": "Kind of text",
"help": "Where the line would appear; subtitles wrap at 440 pixels by default.",
"choices": {"bank": "dialogue", "menu": "menu", "subtitle": "movie subtitle",
"battle": "battle", "exe": "program text"}},
}
def field_hint(command: str, dest: str) -> dict:
"""The hint for one option of one command: "command.option" over "option"."""
hint = dict(FIELD_HINTS.get(dest, {}))
hint.update(FIELD_HINTS.get(f"{command}.{dest}", {}))
return hint
def card_info(command: str, short: str) -> dict:
"""A command's card text, with the fallback for a command the table lacks."""
info = COMMAND_CARDS.get(command)
if info is None:
return {"group": OTHER_GROUP, "step": None, "title": command, "summary": short or command,
"needs": "", "makes": "", "next": "", "output": ("out", "")}
return {"group": info.get("group", OTHER_GROUP), "step": info.get("step"),
"title": info.get("title") or command, "summary": info.get("summary") or short or command,
"needs": info.get("needs", ""), "makes": info.get("makes", ""), "next": info.get("next", ""),
"output": info.get("output", ("out", ""))}
# Commands whose --out is a disc image they write, not a folder.
_WRITES_ISO = re.compile(r"\b(copy of the disc|disc copy|modded|\.iso)\b", re.I)
def _help_of(sub_action, name) -> str:
for ca in getattr(sub_action, "_choices_actions", []):
if ca.dest == name or getattr(ca, "metavar", None) == name:
return ca.help or ""
return ""
def _kinds_choices() -> Optional[List[str]]:
try:
from browse import ALL_KINDS
return list(ALL_KINDS)
except Exception:
return None
def _field(name: str, a: argparse.Action, writes_iso: bool) -> dict:
"""One option of one command as a form field, hints applied."""
flag = next((s for s in a.option_strings if s.startswith("--")),
a.option_strings[0] if a.option_strings else None)
if isinstance(a, argparse._StoreTrueAction):
kind = "flag"
elif isinstance(a, argparse._StoreFalseAction):
kind = "flag-off"
elif isinstance(a, argparse._AppendAction) or a.nargs in ("+", "*"):
kind = "multi"
else:
kind = "value"
hint = field_hint(name, a.dest)
help_text = hint.get("help_multi") if kind == "multi" and hint.get("help_multi") else hint.get("help")
f = {
"dest": a.dest,
"flag": flag,
"positional": not a.option_strings,
"kind": kind,
"required": bool(a.required) if a.option_strings else (a.nargs not in ("?", "*")),
"help": help_text or html_escape(a.help or ""),
"default": None if a.default is None or a.default is False or a.default is argparse.SUPPRESS
else a.default,
"type": getattr(a.type, "__name__", None) if a.type else None,
"choices": [str(c) for c in a.choices] if a.choices else None,
"label": hint.get("label") or a.dest.replace("_", " ").capitalize(),
"placeholder": hint.get("placeholder", ""),
"advanced": bool(hint.get("advanced")),
}
if hint.get("required_unless"):
# Needed for a real run, but the command accepts it missing when one
# of these other fields is set (a dry run, a self-check, an override).
f["required"] = True
f["required_unless"] = list(hint["required_unless"])
labels = hint.get("choices")
if a.dest == "kinds" and name == "browse":
f["kind"] = "kinds"
f["choices"] = _kinds_choices()
if not f["choices"]:
f["kind"] = "value"
elif isinstance(labels, dict):
f["choice_labels"] = labels
elif isinstance(labels, list) and not f["choices"]:
f["select"] = labels # a fixed list of values for a free field
elif isinstance(labels, dict) and f["choices"]:
f["choice_labels"] = labels
pick = hint.get("pick")
suggest = hint.get("suggest")
if a.dest == "out" and writes_iso:
# The shared "out" hint says "Output folder"; a disc-writing card's
# --out is a file, so only its own command.out label may replace this.
pick = "save"
f["label"] = FIELD_HINTS.get(f"{name}.out", {}).get("label") or "Output disc"
suggest = suggest or "modded.iso"
f["filter"] = "iso"
elif a.dest == "out" and re.search(r"\bPNG to write\b", a.help or "") and not pick:
pick = "save"
f["label"] = hint.get("label") or "Output PNG"
suggest = suggest or "line.png"
if pick:
f["pick"] = pick
if hint.get("filter") and "filter" not in f:
f["filter"] = hint["filter"]
if suggest:
f["suggest"] = suggest
elif kind in ("value", "multi") and not f.get("select") and not f["choices"] and \
re.search(r"\b(file|png|wav|sf2|json|csv|folder|dir)\b", a.help or "", re.I):
f["pick"] = "any"
# The starting value: a hint's prefill, else the argparse default, else (for a
# required disc image or output only) a suggestion; optional fields start empty.
if "prefill" in hint:
f["prefill"] = hint["prefill"]
elif f["default"] is not None and kind == "value":
f["prefill"] = str(f["default"])
elif f["required"] and a.dest == "iso":
f["prefill"] = "{discs}" if kind == "multi" else "{disc}"
elif f["required"] and a.dest == "out":
f["prefill"] = "{out}/" + suggest if pick == "save" and suggest else "{out}"
else:
f["prefill"] = ""
return f
def _merge_flag_pairs(name: str, fields: List[dict]) -> List[dict]:
"""An on flag and an off flag that write one option (--rtl / --ltr) become a
single three-way choice: leave it to the command, on, or off. Two checkboxes
would share one form name, and an unticked off-flag would always be sent."""
out: List[dict] = []
for f in fields:
if f["kind"] in ("flag", "flag-off"):
other = next((g for g in out if g["dest"] == f["dest"] and g["kind"] in ("flag", "flag-off")
and g["kind"] != f["kind"]), None)
if other is not None:
on, off = (other, f) if other["kind"] == "flag" else (f, other)
tri = field_hint(name, f["dest"]).get("tri") or [
"Default", f"{on['flag']}: {on['help']}", f"{off['flag']}: {off['help']}"]
other.update({"kind": "tristate", "flag_on": on["flag"], "flag_off": off["flag"],
"flag": None, "select": [["", tri[0]], ["on", tri[1]], ["off", tri[2]]],
"help": field_hint(name, f["dest"]).get("help") or ""})
continue
out.append(f)
return out
def command_schema(parser: Optional[argparse.ArgumentParser] = None) -> List[dict]:
"""One dict per subcommand: name, card text, aliases and its fields."""
parser = parser or cli_parser()
sub = next(a for a in parser._actions if isinstance(a, argparse._SubParsersAction))
commands: List[dict] = []
by_signature: Dict[tuple, dict] = {}
for name, p in sub.choices.items():
short = _help_of(sub, name)
writes_iso = bool(_WRITES_ISO.search(short)) or name in ("patch", "text-import", "exe-import")
fields = [_field(name, a, writes_iso) for a in p._actions if not isinstance(a, argparse._HelpAction)]
fields = _merge_flag_pairs(name, fields)
signature = (short, tuple((f["dest"], f["kind"]) for f in fields))
if short and signature in by_signature: # dump / extract: one card, two names
by_signature[signature]["aliases"].append(name)
continue
info = card_info(name, short)
out_field, out_sub = info["output"] or (None, "")
cmd = {"name": name, "short": short, "help": COMMAND_HELP.get(name, ""),
"aliases": [], "fields": fields, "writes_iso": writes_iso,
"group": info["group"], "step": info["step"], "title": info["title"],
"summary": info["summary"] if name in COMMAND_CARDS else html_escape(info["summary"]),
"needs": info["needs"], "makes": info["makes"], "next": info["next"],
"output_field": out_field if any(f["dest"] == out_field for f in fields) else None,
"output_sub": out_sub}
by_signature[signature] = cmd
commands.append(cmd)
return commands
def grouped(commands: List[dict]) -> List[dict]:
"""The page's sections in GROUPS order, each with its commands: table order
for the known ones, parser order for the rest. Empty sections are left out."""
order = {n: i for i, n in enumerate(COMMAND_CARDS)}
known = {g for g, _, _ in GROUPS}
sections = []
for gid, title, blurb in GROUPS:
members = [c for c in commands if (c["group"] if c["group"] in known else OTHER_GROUP) == gid]
members.sort(key=lambda c: order.get(c["name"], len(order)))
if members:
sections.append({"id": gid, "title": title, "blurb": blurb, "commands": [c["name"] for c in members]})
return sections
def _truthy(v: str) -> bool:
return v.lower() in ("1", "on", "true", "yes")
def build_argv(cmd: dict, form: dict) -> List[str]:
"""Turn a submitted card into the argv the CLI gets. Raises ValueError
with a readable message when something required is missing."""
def val(key):
v = form.get(key)
if isinstance(v, list):
v = v[0] if v else ""
return (v or "").strip()