Repository navigation
Expand file tree
/
Copy pathgui.py
More file actions
2028 lines (1863 loc) · 85.3 KB
/
Copy pathgui.py
File metadata and controls
2028 lines (1863 loc) · 85.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""gui.py — Local web GUI for the Xenosaga III 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
PORT=8080 python gui.py # pin the port
python gui.py --self-test
or double-click one of the launchers (launch.bat / launch.command / launch.sh),
which first make sure numpy, Pillow, capstone, fonttools and uharfbuzz are
installed (into .venv/ when the Python they find lacks any of them).
Stdlib only. A small HTTP server on 127.0.0.1 (never any other interface), a
page with one card per command, and every command run as a ``cli.py``
subprocess whose output streams back live (Server-Sent Events).
Schema-driven architecture borrowed from Xenosaga2PythonExtractor/gui.py
(2026-11-20): ``cli_parser`` / ``command_schema`` / ``build_argv``, the Job
runner, the picker and the page script. The cards are not written by hand:
they are built from ``cli.build_parser()`` when the GUI starts, so a command
added to cli.py (or to any module's ``add_commands``) shows up here with no
change to this file. What changed for XS3:
* cards are grouped into sections (Disc, Browse, Models, Text & translation,
Fonts & scripts, Modding, Diagnostics) by ``SECTION_OF`` / ``SECTION_PREFIXES``,
with an "Other" section for any command neither names;
* a command with its own sub-commands (``lang scan`` / ``lang encode`` / ...)
becomes one card per leaf, run as ``cli.py lang scan ...``;
* ``detect_isos`` / ``xs3_builds`` find the USA pair, the Japanese pair and the
May 2006 prototype, confirmed by ``region.region_of`` (serial + exe hash), and
the page lets you pick which build fills the disc fields;
* an ``--iso`` whose help says "COPY" (commands that write the image in place)
is never pre-filled with a detected original;
* ``detect_deps`` reports the five required Python packages, the CLI's own
import errors, ffmpeg, Blender and 7-Zip;
* the stylesheet is the earlier XS3 GUI's, plus section headers.
"""
from __future__ import annotations
import argparse
import glob
import http.server
import json
import os
import queue
import re
import shlex
import shutil
import socket
import socketserver
import string
import subprocess
import sys
import threading
import time
import uuid
import webbrowser
from pathlib import Path
from typing import Dict, List, Optional, Tuple
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`
# When frozen by PyInstaller, sys.executable is gui.exe — it can't run cli.py.
# We ship a sibling CLI binary built from the same spec; invoke it directly.
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 III Extractor"
HOST = "127.0.0.1" # loopback only; never bind anything else
def _fatal(title: str, body: str) -> None:
"""Surface a startup error the user can actually see (windowed builds have
no console: a MessageBox on Windows, a dialog on a macOS app bundle)."""
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:
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
# ---------------------------------------------------------------------------
def cli_parser(module=None) -> argparse.ArgumentParser:
"""cli.py's top-level parser, without running a command."""
if module is None:
import cli as module # noqa: F401 (also tells PyInstaller to bundle it)
return module.build_parser()
def cli_import_errors(module=None) -> Dict[str, str]:
"""Modules cli.py could not import while building its parser (name -> error).
cli.py refuses every command but ``self-test`` while this is non-empty."""
if module is None:
import cli as module
return dict(getattr(module, "IMPORT_ERRORS", {}) or {})
# Commands that are not cards (the GUI itself).
HIDDEN = {"gui"}
SECTIONS = ("Disc", "Browse", "Models", "Text & translation", "Fonts & scripts",
"Modding", "Diagnostics", "Other")
# Exact names first; a command not listed falls to the first matching prefix
# in SECTION_PREFIXES, then to "Other". A sub-command card ("lang scan") is
# looked up by its full name, then by its parent ("lang").
SECTION_OF = {
# Disc: read the image, its index and chains; the 7-Zip pipeline
"region": "Disc", "iso-ls": "Disc", "toc-check": "Disc", "list": "Disc",
"dump": "Disc", "prep": "Disc", "lba-from-iso": "Disc", "container-map": "Disc",
"map-regions": "Disc", "toc": "Disc", "scan": "Disc", "extract": "Disc",
"verify": "Disc", "code-extract": "Disc", "xc-unpack": "Disc", "resolve": "Disc",
# Browse: viewable / playable files
"browse": "Browse", "chr-decode": "Browse", "chr-palettes": "Browse",
# Models
"model": "Models", "models": "Models", "glb-info": "Models", "blend": "Models",
"motion": "Models",
# Text & translation
"text-export": "Text & translation", "text-import": "Text & translation",
"text-roundtrip": "Text & translation", "text-decode": "Text & translation",
"sb-strings": "Text & translation", "txd-strings": "Text & translation",
"nj-strings": "Text & translation", "subtitle-text": "Text & translation",
"align-export": "Text & translation", "lang": "Text & translation",
"evt-import": "Text & translation", "ovl-import": "Text & translation",
"subs": "Text & translation", "msgdat-strings": "Text & translation",
"batdat-strings": "Text & translation",
# Fonts & scripts
"statfont": "Fonts & scripts", "statfont-export": "Fonts & scripts",
"statfont-import": "Fonts & scripts",
# Modding: anything that writes a disc image
"patch": "Modding", "chr-import-palettes": "Modding", "chr-import-entry": "Modding",
"chr-recolor": "Modding", "chr-iso-extract": "Modding", "chr-iso-patch": "Modding",
"chr-iso-sweep": "Modding",
# Diagnostics
"self-test": "Diagnostics", "doctor": "Diagnostics", "disasm": "Diagnostics",
}
SECTION_PREFIXES: Tuple[Tuple[str, str], ...] = (
("font", "Fonts & scripts"), ("glyph", "Fonts & scripts"), ("statfont", "Fonts & scripts"),
("text", "Text & translation"), ("lang", "Text & translation"),
("align", "Text & translation"), ("subs", "Text & translation"),
("evt", "Text & translation"), ("ovl", "Text & translation"),
("model", "Models"), ("glb", "Models"), ("blend", "Models"),
("image", "Browse"), ("img", "Browse"), ("tex", "Browse"), ("xtx", "Browse"),
("txy", "Browse"), ("png", "Browse"),
("repack", "Modding"), ("chr-iso", "Modding"), ("patch", "Modding"),
("iso", "Disc"), ("toc", "Disc"), ("chain", "Disc"),
)
def section_of(name: str) -> str:
"""The section a card goes in (see SECTION_OF / SECTION_PREFIXES)."""
for key in (name, name.split(" ")[0]):
if key in SECTION_OF:
return SECTION_OF[key]
for key in (name, name.split(" ")[0]):
for prefix, sec in SECTION_PREFIXES:
if key.startswith(prefix):
return sec
return "Other"
# Friendlier text for some commands. A command without an entry here gets
# its argparse help line, so new commands still read fine.
COMMAND_HELP = {
"region": "Which build each image is (USA retail, Japanese retail or the May 2006 "
"prototype), its language folder and the executable's hash. Harmless: reads only.",
"list": "Print every entry of the disc's own index: chain, sector, size and in-game path. "
"Chain 0 (X3.0x) is shared by both discs, chain 1 (X3.1x) is Disc 1 only, "
"chain 2 (X3.2x) Disc 2 only.",
"dump": "Unpack the disc images straight from their index into <code>OUT/</code>, "
"no 7-Zip needed. Give both discs to get all three chains.",
"browse": "Convert a dump into files your computer opens: textures as PNG, audio and "
"movies through ffmpeg, text as UTF-8. Untick the kinds you do not want.",
"model": "One model straight from the disc to a <code>.glb</code> Blender opens.",
"models": "Every model at once, as <code>.glb</code> files (see docs/BLENDER.md).",
"text-export": "Write the dialogue, menu and subtitle banks to an editable UTF-8 tree.",
"self-test": "Run every module's built-in checks. Disc checks read the XS3_D1 / XS3_D2 / "
"XS3_PROTO environment variables and are skipped without them.",
"prep": "The older 7-Zip pipeline, step 1: list the ISO and extract the X3.* parts. "
"The direct-from-ISO commands above do not need it.",
}
# Field hints keyed by option dest: label, picker, placeholder.
FIELD_HINTS = {
"iso": {"label": "Disc image", "pick": "file", "filter": "iso"},
"out": {"label": "Output", "pick": "dir"},
"work": {"label": "Work folder", "pick": "dir"},
"stage": {"label": "Stage folder", "pick": "dir"},
"dump": {"label": "Dump folder", "pick": "dir"},
"text": {"label": "Text folder", "pick": "dir"},
"code_dir": {"label": "Code folder", "pick": "dir"},
"mod": {"label": "Mod folder", "pick": "dir"},
"chr": {"label": ".chr file", "pick": "any"},
"png": {"label": "PNG", "pick": "any"},
"file": {"label": "File", "pick": "any"},
"elf": {"label": "Executable", "pick": "any"},
"ffmpeg": {"label": "ffmpeg", "pick": "any"},
"sevenzip": {"label": "7-Zip", "pick": "any"},
"path": {"label": "In-game path", "placeholder": "e.g. mnu\\us\\font0.bin"},
"set": {"label": "Replacements", "placeholder": "chain0:mnu\\us\\font0.bin=/path/to/new.bin"},
"limit": {"label": "At most", "placeholder": "N objects (optional, for a quick sample)"},
"chain": {"label": "Chain", "choices": [["", "All chains"], ["0", "Chain 0 (X3.0x, both discs)"],
["1", "Chain 1 (X3.1x, Disc 1)"],
["2", "Chain 2 (X3.2x, Disc 2)"]]},
}
# 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|output (disc|image))\b", re.I)
_WRITES_ISO_NAMES = {"patch", "text-import", "evt-import", "ovl-import"}
# An --iso the command writes in place: never pre-filled with an original.
_IN_PLACE = re.compile(r"\bcopy\b", re.I)
_IN_PLACE_NAMES = {"chr-iso-patch", "chr-iso-sweep", "repack-patch", "repack-tree"}
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_bundle import ALL_KINDS
return list(ALL_KINDS)
except Exception:
return None
def _subparsers_of(p: argparse.ArgumentParser):
return next((a for a in p._actions if isinstance(a, argparse._SubParsersAction)), None)
def _fields(name: str, p: argparse.ArgumentParser, short: str) -> List[dict]:
writes_iso = bool(_WRITES_ISO.search(short)) or name in _WRITES_ISO_NAMES
fields = []
for a in p._actions:
if isinstance(a, (argparse._HelpAction, argparse._SubParsersAction, argparse._VersionAction)):
continue
if a.help == argparse.SUPPRESS:
continue
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"
elif isinstance(a, argparse._StoreConstAction) or a.nargs == 0:
kind = "flag"
else:
kind = "value"
hint = dict(FIELD_HINTS.get(a.dest, {}))
help_ = a.help or ""
default = a.default
if default in (None, False, argparse.SUPPRESS) or isinstance(default, (list, tuple)) and not default:
default = None
elif isinstance(default, (list, tuple)):
default = "\n".join(str(x) for x in default)
elif not isinstance(default, (str, int, float)):
default = str(default)
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_,
"default": 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", help_),
"nargs_many": bool(a.option_strings) and a.nargs in ("+", "*"),
}
if a.dest == "kinds" and name == "browse":
f["kind"] = "kinds"
f["choices"] = _kinds_choices()
if not f["choices"]:
f["kind"] = "value"
elif hint.get("choices") and not f["choices"]:
f["select"] = hint["choices"]
pick = hint.get("pick")
if a.dest == "iso" and (_IN_PLACE.search(help_) or name in _IN_PLACE_NAMES):
f["in_place"] = True
f["label"] = "Disc image (a COPY)"
f["placeholder"] = "a COPY of your disc image: this command writes it in place"
if a.dest == "out" and (writes_iso or re.search(r"\.iso\b|disc image", help_, re.I)):
pick = "save"
f["label"] = "Output disc"
f["suggest"] = "modded.iso"
if pick:
f["pick"] = pick
if hint.get("filter"):
f["filter"] = hint["filter"]
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|tsv|ttf|otf|glb|folder|dir|directory)\b",
help_, re.I):
f["pick"] = "any"
fields.append(f)
return fields
def command_schema(parser: Optional[argparse.ArgumentParser] = None) -> List[dict]:
"""One dict per card: name, argv path, section, help, aliases and fields.
A sub-command with sub-commands of its own (``lang scan``) gives one card
per leaf; its ``path`` is the words to put after the CLI (["lang", "scan"])."""
parser = parser or cli_parser()
sub = _subparsers_of(parser)
commands: List[dict] = []
by_signature: Dict[tuple, dict] = {}
def walk(sub_action, prefix: List[str]):
for name, p in sub_action.choices.items():
if not prefix and name in HIDDEN:
continue
path = prefix + [name]
full = " ".join(path)
short = _help_of(sub_action, name)
inner = _subparsers_of(p)
if inner is not None:
walk(inner, path)
continue
fields = _fields(full, p, short)
signature = (tuple(prefix), short, tuple((f["dest"], f["kind"]) for f in fields))
if short and signature in by_signature: # aliases: one card, two names
by_signature[signature]["aliases"].append(full)
continue
cmd = {"name": full, "path": path, "short": short, "help": COMMAND_HELP.get(full, ""),
"section": section_of(full), "aliases": [], "fields": fields}
by_signature[signature] = cmd
commands.append(cmd)
if sub is not None:
walk(sub, [])
order = {s: i for i, s in enumerate(SECTIONS)}
commands.sort(key=lambda c: order.get(c["section"], len(SECTIONS))) # stable: argparse order kept
return commands
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()
on = ("1", "on", "true", "yes")
argv = [*CLI_ARGV, *cmd.get("path", [cmd["name"]])]
positional: List[str] = []
for f in cmd["fields"]:
key = f["dest"]
if f["kind"] == "flag":
if val(key).lower() in on:
argv.append(f["flag"])
continue
if f["kind"] == "flag-off":
if val(key).lower() not in on:
argv.append(f["flag"])
continue
if f["kind"] == "kinds":
picked = [k for k in f["choices"] if val(f"{key}.{k}").lower() in on]
if not picked:
raise ValueError("Pick at least one kind to convert")
if len(picked) < len(f["choices"]):
argv += [f["flag"], ",".join(picked)]
continue
if f["kind"] == "multi":
items = [s.strip() for s in re.split(r"[\n;]", val(key)) if s.strip()]
if f["required"] and not items:
raise ValueError(f"{f['label']} is required")
if f["positional"]:
positional += items
elif f.get("nargs_many"):
if items:
argv += [f["flag"], *items]
else:
for it in items:
argv += [f["flag"], it]
continue
v = val(key)
if not v:
if f["required"]:
raise ValueError(f"{f['label']} is required")
continue
if f["type"] == "int":
try:
int(v, 0)
except ValueError:
raise ValueError(f"{f['label']} must be a whole number") from None
if f["type"] == "float":
try:
float(v)
except ValueError:
raise ValueError(f"{f['label']} must be a number") from None
if f["choices"] and v not in f["choices"]:
raise ValueError(f"{f['label']} must be one of {', '.join(f['choices'])}")
if f["positional"]:
positional.append(v)
else:
argv += [f["flag"], v]
# positionals go right after the command words, so an option taking many
# values (nargs '+') cannot swallow them
base = len(CLI_ARGV) + len(cmd.get("path", [cmd["name"]]))
return argv[:base] + positional + argv[base:]
_SCHEMA_CACHE: Optional[List[dict]] = None
_SCHEMA_LOCK = threading.Lock()
def schema() -> List[dict]:
global _SCHEMA_CACHE
with _SCHEMA_LOCK:
if _SCHEMA_CACHE is None:
_SCHEMA_CACHE = command_schema()
return _SCHEMA_CACHE
def find_command(name: str) -> Optional[dict]:
for c in schema():
if c["name"] == name or name in c["aliases"]:
return c
return None
# ---------------------------------------------------------------------------
# Job runner: one subprocess per launched command, lines streamed to clients
# ---------------------------------------------------------------------------
class Job:
def __init__(self, cmd: List[str], cwd: Optional[Path]):
self.id = uuid.uuid4().hex[:12]
self.cmd = cmd
self.cwd = str(cwd or ROOT)
self.started_at = time.time()
self.ended_at: Optional[float] = None
self.exit_code: Optional[int] = None
self.lines: List[str] = []
self.subscribers: List["queue.Queue[Optional[str]]"] = []
self._lock = threading.Lock()
self._proc = subprocess.Popen(
cmd, cwd=self.cwd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
text=True, encoding="utf-8", errors="replace", bufsize=1,
env={**os.environ, "PYTHONUNBUFFERED": "1", "PYTHONIOENCODING": "utf-8"},
)
self.lines.append(f"$ {' '.join(shlex.quote(c) for c in cmd)}")
threading.Thread(target=self._pump, daemon=True).start()
def _broadcast(self, line: Optional[str]) -> None:
with self._lock:
subs = list(self.subscribers)
for q in subs:
try:
q.put_nowait(line)
except queue.Full:
pass
def _pump(self) -> None:
assert self._proc.stdout is not None
for line in self._proc.stdout:
line = line.rstrip("\r\n")
with self._lock:
self.lines.append(line)
self._broadcast(line)
rc = self._proc.wait()
summary = f"[exit {rc}]"
with self._lock:
self.exit_code = rc
self.ended_at = time.time()
self.lines.append(summary)
self._broadcast(summary)
self._broadcast(None)
def subscribe(self) -> "queue.Queue[Optional[str]]":
q: "queue.Queue[Optional[str]]" = queue.Queue(maxsize=50000)
with self._lock:
self.subscribers.append(q)
for line in self.lines:
try:
q.put_nowait(line)
except queue.Full:
break
if self.ended_at is not None:
q.put_nowait(None)
return q
def unsubscribe(self, q) -> None:
with self._lock:
try:
self.subscribers.remove(q)
except ValueError:
pass
def status(self) -> str:
if self.exit_code is None:
return "running"
return "ok" if self.exit_code == 0 else "err"
def to_summary(self, with_log: bool = False) -> dict:
d = {"id": self.id, "cmd": self.cmd, "status": self.status(),
"exit_code": self.exit_code, "started_at": self.started_at,
"ended_at": self.ended_at}
if with_log:
with self._lock:
d["log"] = list(self.lines)
return d
JOBS: Dict[str, Job] = {}
JOBS_LOCK = threading.Lock()
# ---------------------------------------------------------------------------
# Disc detection: the USA pair, the Japanese pair and the May 2006 prototype
# ---------------------------------------------------------------------------
def _walk_for_isos(root: Path, max_depth: int, want: int, out: List[Path]) -> None:
"""Bounded depth-first scan for .iso files over 100 MB. Mutates ``out``."""
if len(out) >= want or max_depth < 0:
return
try:
entries = list(root.iterdir())
except (OSError, PermissionError):
return
entries.sort(key=lambda p: (not p.is_file(), p.name.lower()))
for child in entries:
if len(out) >= want:
return
try:
if child.is_file():
if child.suffix.lower() == ".iso" and child.stat().st_size > 100 * 1024 * 1024:
out.append(child)
elif child.is_dir() and not child.name.startswith("."):
_walk_for_isos(child, max_depth - 1, want, out)
except (OSError, PermissionError):
continue
def detect_isos() -> List[str]:
"""Best-effort, fast, depth-bounded scan of likely folders for .iso files,
plus the XS3_D1 / XS3_D2 / XS3_JP1 / XS3_JP2 / XS3_PROTO variables the
self-tests use."""
candidates: List[Path] = []
for var in ("XS3_D1", "XS3_D2", "XS3_JP1", "XS3_JP2", "XS3_PROTO"):
v = os.environ.get(var)
if v and Path(v).is_file():
candidates.append(Path(v))
for root, depth in ((ROOT.parent, 2), (Path.home() / "Downloads", 2),
(Path.home() / "Desktop", 2), (Path.home() / "Documents", 2)):
try:
if root.is_dir():
_walk_for_isos(root, depth, want=64, out=candidates)
except OSError:
continue
return list(dict.fromkeys(str(p) for p in candidates))
_XS3 = re.compile(r"episode iii\b|episode 3\b|zarathustra|xenosaga ?(iii|3)\b|"
r"slus.?213\.?89|slus.?214\.?17|slps.?256\.?4[01]", re.I)
_JP_NAME = re.compile(r"\(japan\)|kaku katariki|slps", re.I)
_PROTO_NAME = re.compile(r"proto|\d{1,2}-\d{1,2}-0\d|press|beta|demo", re.I)
BUILD_LABELS = {"us": "USA", "jp": "Japan", "proto_2006_05": "May 2006 prototype"}
def _build_by_name(path: str) -> str:
"""Build guessed from the file and folder names: "jp", "proto_2006_05" or "us"."""
p = Path(path)
names = f"{p.parent.name} {p.name}"
if _JP_NAME.search(names):
return "jp"
if _PROTO_NAME.search(names):
return "proto_2006_05"
return "us"
def _build_by_content(path: str) -> Optional[str]:
"""Build from the image itself (``region.region_of``: SYSTEM.CNF serial plus
executable hash), or None when the image cannot be read or is unknown."""
try:
import region
from iso9660 import IsoImage
with IsoImage(path) as iso:
name = region.region_of(iso).name
except Exception:
return None
return None if name == "unknown" else name
def _disc_no(path: str) -> int:
m = re.search(r"disc\s*([12])", Path(path).name, re.I) or \
re.search(r"disc\s*([12])", Path(path).parent.name, re.I)
return int(m.group(1)) if m else 1
def _serial_disc(path: str) -> Optional[int]:
"""Disc number from the boot serial (SLUS_213.89 / SLPS_256.40 = 1,
SLUS_214.17 / SLPS_256.41 = 2)."""
try:
from iso9660 import IsoImage
with IsoImage(path) as iso:
s = iso.boot_elf_name() or ""
except Exception:
return None
return {"SLUS_213.89": 1, "SLPS_256.40": 1, "SLUS_214.17": 2, "SLPS_256.41": 2}.get(s)
def xs3_builds(isos: List[str], check: bool = True) -> Dict[str, List[str]]:
"""The Episode III images among ``isos`` grouped by build, Disc 1 before
Disc 2, one image per disc: {"us": [...], "jp": [...], "proto_2006_05": [...]}.
Names pick the candidates (copies and other episodes are skipped); with
``check`` each one is then opened and ``region.region_of`` decides the
build, and the boot serial decides the disc number. An image the kit cannot
open keeps its name-based guess."""
builds: Dict[str, Dict[int, str]] = {}
for p in isos:
name = Path(p).name
if "copy" in name.lower() or "modded" in name.lower():
continue
if not (_XS3.search(name) or _XS3.search(Path(p).parent.name)):
continue
build = (_build_by_content(p) if check else None) or _build_by_name(p)
disc = (_serial_disc(p) if check else None) or _disc_no(p)
if build == "proto_2006_05":
disc = 1
builds.setdefault(build, {}).setdefault(disc, p)
order = ("us", "jp", "proto_2006_05")
ranked = sorted(builds, key=lambda b: order.index(b) if b in order else len(order))
return {b: [builds[b][n] for n in sorted(builds[b])] for b in ranked}
def preferred_build(builds: Dict[str, List[str]]) -> Optional[str]:
for b in ("us", "jp", "proto_2006_05"):
if builds.get(b):
return b
return next(iter(builds), None)
# ---------------------------------------------------------------------------
# Dependencies: all five Python packages are required; programs are found
# ---------------------------------------------------------------------------
REQUIRED_PACKAGES = ( # (import name, display name) — requirements.txt
("numpy", "numpy"),
("PIL", "Pillow"),
("capstone", "capstone"),
("fontTools", "fonttools"),
("uharfbuzz", "uharfbuzz"),
)
_BLENDER_LOCATIONS = (
"/Applications/Blender.app/Contents/MacOS/Blender",
"~/Applications/Blender.app/Contents/MacOS/Blender",
"/usr/bin/blender", "/usr/local/bin/blender", "/snap/bin/blender",
"/var/lib/flatpak/exports/bin/org.blender.Blender",
r"%ProgramFiles%\Blender Foundation\Blender*\blender.exe",
)
def _package_version(mod: str) -> str:
"""The installed version of a required package, or "" when it is missing."""
try:
m = __import__(mod)
except Exception:
return ""
v = getattr(m, "__version__", None) or getattr(m, "version", None)
if mod == "capstone":
try:
v = m.__version__ if hasattr(m, "__version__") else ".".join(map(str, m.cs_version()[:2]))
except Exception:
pass
if not isinstance(v, str):
try:
from importlib import metadata
v = metadata.version(dict(REQUIRED_PACKAGES).get(mod, mod))
except Exception:
v = "installed"
return v
def detect_blender() -> str:
"""Path to a Blender executable, or "". A kit module that knows better
(``blend.find_blender`` / ``blend.detect_blender``) is asked first."""
try:
import blend # noqa: F401 (added in a later round; absent is fine)
for fn in ("find_blender", "detect_blender"):
if hasattr(blend, fn):
p = getattr(blend, fn)()
if p:
return str(p)
except Exception:
pass
env = os.environ.get("BLENDER")
if env and Path(env).exists():
return env
p = shutil.which("blender")
if p:
return p
for raw in _BLENDER_LOCATIONS:
expanded = os.path.expanduser(os.path.expandvars(raw))
hits = sorted(glob.glob(expanded), reverse=True) if "*" in expanded else \
([expanded] if Path(expanded).exists() else [])
if hits:
return hits[0]
return ""
def detect_deps() -> dict:
"""What the right-side panel shows: Python, the CLI and its import errors,
the five required packages (version or ""), ffmpeg, Blender and 7-Zip."""
def _safe(fn):
try:
return fn() or ""
except Exception:
return ""
try:
from browse_bundle import detect_ffmpeg
except Exception:
detect_ffmpeg = lambda: shutil.which("ffmpeg") # noqa: E731
try:
from iso_ops import detect_sevenzip
except Exception:
detect_sevenzip = lambda: shutil.which("7z") or shutil.which("7za") # noqa: E731
try:
import_errors = cli_import_errors() if _SCHEMA_CACHE is not None else {}
except Exception as exc:
import_errors = {"cli": f"{type(exc).__name__}: {exc}"}
return {
"python": sys.version.split()[0],
"cli": str(CLI_TARGET) if CLI_TARGET.exists() else "",
"cli_import_errors": import_errors,
"packages": {disp: _package_version(mod) for mod, disp in REQUIRED_PACKAGES},
"ffmpeg": _safe(detect_ffmpeg),
"blender": _safe(detect_blender),
"7z": _safe(detect_sevenzip),
}
def default_out_dir(discs: List[str]) -> str:
if discs:
return str(Path(discs[0]).parent / "xs3-out")
return str(Path.home() / "xs3" / "out")
def detect() -> dict:
isos = detect_isos()
builds = xs3_builds(isos)
pref = preferred_build(builds)
discs = builds.get(pref, []) if pref else []
return {"root": str(ROOT), "isos": isos, "builds": builds, "build_labels": BUILD_LABELS,
"build": pref, "discs": discs, "deps": detect_deps(),
"default_out": default_out_dir(discs)}
# ---------------------------------------------------------------------------
# Filesystem browser for the picker
# ---------------------------------------------------------------------------
def list_roots() -> List[str]:
roots: List[str] = []
if os.name == "nt":
for d in string.ascii_uppercase:
p = Path(f"{d}:\\")
if p.exists():
roots.append(str(p))
else:
roots += ["/", str(Path.home())]
for parent in ("/mnt", "/media", "/Volumes"):
try:
pp = Path(parent)
if pp.is_dir():
roots += [str(c) for c in sorted(pp.iterdir()) if c.is_dir()]
except (OSError, PermissionError):
continue
return list(dict.fromkeys(roots))
def list_dir(path_str: str, ext_filter: Optional[str] = None) -> dict:
p = Path(path_str).expanduser() if path_str else Path.home()
if not p.exists():
p = Path.home()
if not p.is_dir():
p = p.parent
p = p.resolve()
entries: List[dict] = []
err: Optional[str] = None
try:
children = sorted(p.iterdir(), key=lambda x: (not x.is_dir(), x.name.lower()))
except (OSError, PermissionError) as exc:
children, err = [], str(exc)
for child in children:
try:
if child.is_symlink() and not child.exists():
continue
if child.is_dir():
if child.name.startswith("."):
continue
entries.append({"name": child.name, "type": "dir", "path": str(child)})
else:
if ext_filter and child.suffix.lower().lstrip(".") != ext_filter.lower().lstrip("."):
continue
entries.append({"name": child.name, "type": "file", "path": str(child),
"size": child.stat().st_size})
except (OSError, PermissionError):
continue
parent = str(p.parent) if p.parent != p else None
return {"path": str(p), "parent": parent, "entries": entries, "roots": list_roots(), "error": err}
# ---------------------------------------------------------------------------
# Embedded UI. The stylesheet (XS3_CSS, at the bottom of this file) is the
# earlier XS3 GUI's; the cards are generated from /schema.
# ---------------------------------------------------------------------------
INDEX_HTML = r"""<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>XENOSAGA III · Extractor</title>
<style>
/*__XS3_CSS__*/
</style>
</head>
<body>
<header>
<div class="title">
<h1>
<span>Xenosaga</span><span class="iii">III</span>
<span class="sep">·</span><span class="extractor">EXTRACTOR</span>
</h1>
<div class="tagline">Also sprach Zarathustra · disc unpacker</div>
</div>
<div class="actions">
<button class="ghost" id="btn-refresh">Refresh status</button>
</div>
</header>
<main>
<section id="cards"></section>
<aside id="right">
<h2>Environment</h2>
<div id="status-box"></div>
<h2>Output</h2>
<pre id="log"></pre>
</aside>
</main>
<div class="modal" id="fs-modal" hidden>
<div class="modal-backdrop" data-close></div>
<div class="modal-window">
<div class="modal-header">
<h2 id="fs-title">Select…</h2>
<button type="button" class="x" data-close>×</button>
</div>
<div class="fs-toolbar">
<button type="button" class="ghost" id="fs-up">↑ Up</button>
<div class="fs-crumb" id="fs-crumb"></div>
</div>
<div class="modal-error" id="fs-error" hidden></div>
<div class="fs-quick" id="fs-quick" hidden></div>
<div class="fs-list" id="fs-list"></div>
<div class="fs-roots" id="fs-roots"></div>
<div class="modal-footer">
<div class="sel-path" id="fs-sel">No selection</div>
<button type="button" class="ghost" data-close>Cancel</button>
<button type="button" id="fs-select" disabled>Select</button>
</div>
</div>
</div>
<script>
const log = document.getElementById('log');
let currentEventSource = null;
const cardEls = {};
let _detectedIsos = [];
let _detect = null;
function setStatus(name, status) {
const el = cardEls[name];
if (!el) return;
el.classList.remove('run','ok','err');
if (status) el.classList.add(status);
const badge = el.querySelector('.badge');
badge.classList.remove('run','ok','err');
badge.textContent = (status || 'idle');
if (status) badge.classList.add(status);
}
function appendLog(line) { log.textContent += line + '\n'; log.scrollTop = log.scrollHeight; }
function fmtSize(bytes) {
if (bytes < 1024) return bytes + ' B';
const units = ['KB','MB','GB','TB']; let v = bytes / 1024, i = 0;
while (v >= 1024 && i < units.length - 1) { v /= 1024; i++; }
return v.toFixed(v >= 10 ? 0 : 1) + ' ' + units[i];
}
function escapeHtml(s) {
return String(s).replace(/[&<>"']/g, c => ({'&':'&','<':'<','>':'>','"':'"',"'":'''})[c]);
}
function baseName(p) { return p.split('/').pop().split('\\').pop(); }
async function runCommand(name, body) {
if (currentEventSource) currentEventSource.close();
log.textContent = '';
setStatus(name, 'run');
const res = await fetch('/run/' + encodeURIComponent(name), {
method: 'POST', headers: {'Content-Type': 'application/x-www-form-urlencoded'}, body});
if (!res.ok) {
const t = await res.text(); let msg = t;
try { const j = JSON.parse(t); if (j && j.error) msg = j.error; } catch (_) {}
setStatus(name, 'err'); appendLog('[error] ' + msg); return;
}
const {job_id} = await res.json();
const es = new EventSource('/stream/' + job_id);
currentEventSource = es;
es.onmessage = (e) => {
if (e.data === '__eof__') {
es.close();
fetch('/job/' + job_id).then(r => r.json()).then(j => setStatus(name, j.status === 'ok' ? 'ok' : 'err'));
} else { appendLog(e.data); }
};
es.onerror = () => { es.close(); };
}
// ------------------------------------------------------------------ picker
const fsModal = document.getElementById('fs-modal'), fsTitle = document.getElementById('fs-title');
const fsCrumb = document.getElementById('fs-crumb'), fsList = document.getElementById('fs-list');
const fsRoots = document.getElementById('fs-roots'), fsError = document.getElementById('fs-error');
const fsQuick = document.getElementById('fs-quick'), fsSel = document.getElementById('fs-sel');
const fsSelectBtn = document.getElementById('fs-select'), fsUp = document.getElementById('fs-up');
const fsState = { mode: 'file', filter: null, current: null, parent: null, selected: null, onChoose: null };
function _renderQuickPick() {
const isos = fsState.filter === 'iso' ? _detectedIsos : [];
if (!isos.length) { fsQuick.hidden = true; return; }
fsQuick.hidden = false;
fsQuick.innerHTML = '<span>Detected:</span>' + isos.map(p =>
`<a class="qp" data-path="${escapeHtml(p)}" title="${escapeHtml(p)}">${escapeHtml(baseName(p))}</a>`).join('');
fsQuick.querySelectorAll('.qp').forEach(a => {
a.addEventListener('click', () => {
fsQuick.querySelectorAll('.qp').forEach(x => x.classList.remove('selected'));
a.classList.add('selected'); fsState.selected = a.dataset.path;
fsSel.classList.add('has'); fsSel.textContent = a.dataset.path; fsSelectBtn.disabled = false;
});
a.addEventListener('dblclick', () => { fsState.selected = a.dataset.path; chooseAndClose(); });
});
}
function openPicker({mode, filter, startPath, title, onChoose}) {
Object.assign(fsState, {mode, filter: filter || null, current: null, parent: null, selected: null, onChoose});
fsTitle.textContent = title || (mode === 'file' ? 'Select a file' : mode === 'any' ? 'Select a file or folder' : 'Select a folder');
fsSel.classList.remove('has'); fsSel.textContent = 'No selection';
fsSelectBtn.disabled = mode === 'file'; fsError.hidden = true;
_renderQuickPick(); fsModal.hidden = false; loadDir(startPath || '');
}
function closePicker() { fsModal.hidden = true; fsState.onChoose = null; }
async function loadDir(path) {
fsError.hidden = true;
try {
const qs = new URLSearchParams();
if (path) qs.set('path', path);
if (fsState.filter) qs.set('filter', fsState.filter);
const res = await fetch('/browse-fs?' + qs.toString());
if (!res.ok) { fsError.hidden = false; fsError.textContent = 'Cannot read directory.'; return; }
const data = await res.json();
if (data.error) { fsError.hidden = false; fsError.textContent = data.error; }
fsState.current = data.path; fsState.parent = data.parent; fsState.selected = null;
if (fsState.mode !== 'file') {