Repository navigation
Expand file tree
/
Copy pathDMPRepackGUI.py
More file actions
3903 lines (3423 loc) · 174 KB
/
Copy pathDMPRepackGUI.py
File metadata and controls
3903 lines (3423 loc) · 174 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
#!/usr/bin/env python3
"""
DMPRepack GUI – ARMGDDN Games Repack Tool
A graphical interface replacing Repack.bat and all PS1 scripts.
Requirements: Python 3.8+ (tkinter is bundled with standard Windows Python)
Usage : python DMPRepackGUI.py
or double-click if .py files open with Python on your machine
"""
import os
import re
import json
import configparser
import sys
import time
import shutil
import subprocess
import threading
import socket
import urllib.error
import urllib.request
import webbrowser
import tkinter as tk
from tkinter import ttk, filedialog, messagebox, scrolledtext, simpledialog
from pathlib import Path
# ─── Version / update check ──────────────────────────────────────────────────
# This string is the source of truth. The "Build & draft release" GitHub
# Actions workflow rewrites it from the version you type when you run it, then
# commits it back here — so you normally don't edit it by hand. make_version_file.py
# reads it to stamp the exe, and the app compares it against the latest GitHub
# release on launch.
__version__ = "1.2.3"
GITHUB_REPO = "DeliciousMeatPop/AGrepackGUI"
# ─── Resolve base directory ──────────────────────────────────────────────────
if getattr(sys, "frozen", False): # PyInstaller single-file exe
BASE_DIR = Path(sys.executable).parent
else:
BASE_DIR = Path(__file__).resolve().parent
RESOURCE_DIR = BASE_DIR / "Resource"
SETUP_DIR = BASE_DIR / "Setup"
COMPRESSOR = BASE_DIR / "COMPRESSOR"
SAVE_DIR = RESOURCE_DIR / "Save"
DLL_DIR = RESOURCE_DIR / "DLL"
SETTINGS_INI = BASE_DIR / "settings.ini"
SCRIPT_ISS = BASE_DIR / "Script.iss"
SEVEN_ZIP = BASE_DIR / "7z.exe"
CONVERSION_DIR = COMPRESSOR / "Conversion_Output" / "CONVERSION"
SETUP_FILES = COMPRESSOR / "Setup_Files"
ISCC = BASE_DIR / "Resources" / "IS_Files" / "ISCC.exe"
COMPIL32 = BASE_DIR / "Resources" / "IS_Files" / "Compil32Ex.exe"
ARC_EXE = COMPRESSOR / "Resources" / "Win64" / "Arc.exe"
APP_ICON = BASE_DIR / "setup.ico"
# Update-patch maker. It ships inside the toolkit (XDELTA_SHIPPED_DIR) but must run
# from a folder NEXT TO the toolkit (XDELTA_DIR) — the patch tools break on long
# paths when it sits inside. Nothing moves it automatically; the repacker is asked to.
XDELTA_SHIPPED_DIR = BASE_DIR / "XDelta"
XDELTA_DIR = BASE_DIR.parent / "XDelta"
PATCH_GUI_PS1 = XDELTA_DIR / "make_patch_gui.ps1"
PATCH_OLD_DIR = XDELTA_DIR / "Games" / "old"
PATCH_NEW_DIR = XDELTA_DIR / "Games" / "new"
PATCH_OLD_TAG = "-ARMGDDN"
PATCH_RESULT = XDELTA_DIR / "Output" / "last_patch_result.json"
# Testing-remote upload (rclone). All three files sit next to the program and are
# never committed: the custom rclone.exe carries the config password itself.
RCLONE_EXE = BASE_DIR / "rclone.exe"
RCLONE_CONF = BASE_DIR / "rclone.conf" # encrypted rclone config
REMOTES_INI = BASE_DIR / "remotes.ini" # [Remotes] pc= / pcvr= -> remote:path
UPLOAD_TARGETS = ("pc", "pcvr")
# Testing-site posting (AGTesting). Both files sit next to the program and are never
# committed: agtesting.ini holds the site address, agtesting.token is this PC's
# personal API token (written by the one-time browser link, revocable on the site).
SITE_INI = BASE_DIR / "agtesting.ini" # [Site] url= / optional [Types] pc= pcvr=
SITE_TOKEN = BASE_DIR / "agtesting.token"
SITE_DEFAULT_TYPES = {"pc": "PC", "pcvr": "VR"} # upload destination -> site repack type
SITE_TYPES_OK = ("PC", "VR", "BOTH")
# The site only accepts "Game Name vBUILDID -ARMGDDN" (same rule as its API)
GAME_NAME_RE = re.compile(r"^.+\s+v[A-Za-z0-9._\-]+\s+-ARMGDDN$")
# "Game vOLD-NEW_Update_Patch": the site wants the numeric old build
PATCH_FOLDER_RE = re.compile(r"\sv(\d+)-(\d+)[ _]Update[ _]Patch$", re.I)
# A build in a release name: no whitespace or filename-illegal characters. Mostly
# digits (Steam), but non-Steam games and VR mods can use things like "1.0b".
PATCH_BUILD_RE = r'[^\s\\/:*?"<>|]+'
PATCH_RELEASE_RE = r"^.+?\s+v" + PATCH_BUILD_RE + r"(\s+.+)?$"
INI_TEMPLATES = {
"PC": RESOURCE_DIR / "2.ini",
"VR": RESOURCE_DIR / "1.ini",
"VR Optional": RESOURCE_DIR / "3.ini",
}
COMPRESSION_BATS = {
"12": RESOURCE_DIR / "12.bat",
"8": RESOURCE_DIR / "8.bat",
"4": RESOURCE_DIR / "4.bat",
"0": RESOURCE_DIR / "store.bat",
}
# ─── Colour palette ──────────────────────────────────────────────────────────
BG = "#111827" # main window bg
PANEL = "#1f2937" # card / panel bg
BORDER = "#374151" # subtle divider
ACCENT = "#6366f1" # indigo primary
FG = "#f9fafb" # near-white text
FG2 = "#9ca3af" # muted / label text
ENTRY = "#0f172a" # entry background
BTN = "#374151" # default button
SUCCESS = "#22c55e" # green
DANGER = "#ef4444" # red
WARN = "#f59e0b" # amber
# ═══════════════════════════════════════════════════════════════════════════
# INI helpers
# ═══════════════════════════════════════════════════════════════════════════
def ini_read(path: Path) -> list:
if not path.exists():
return []
raw = path.read_bytes()
if raw.startswith(b"\xef\xbb\xbf"):
raw = raw[3:]
return raw.decode("utf-8", errors="replace").splitlines(keepends=True)
def ini_write(path: Path, lines: list):
# Write UTF-8 WITHOUT BOM — GetPrivateProfileString / ISPP ReadIni
# reads the BOM bytes as literal text and corrupts the first section header.
content = "".join(lines)
content = content.replace("\r\n", "\n").replace("\r", "\n").replace("\n", "\r\n")
path.write_bytes(content.encode("utf-8"))
def ini_set(lines: list, key: str, value: str, occurrence: int = 0) -> list:
"""Replace the (occurrence)-th `key=...` line. Appends if not found."""
prefix = key.lower() + "="
count = 0
for i, line in enumerate(lines):
if line.strip().lower().startswith(prefix):
if count == occurrence:
lines[i] = f"{key}={value}\n"
return lines
count += 1
lines.append(f"{key}={value}\n")
return lines
def ini_get(lines: list, key: str, default: str = "", occurrence: int = 0) -> str:
prefix = key.lower() + "="
count = 0
for line in lines:
s = line.strip()
if s.lower().startswith(prefix):
if count == occurrence:
return s.split("=", 1)[1].strip()
count += 1
return default
def ini_get_in_section(lines: list, section: str, key: str, default: str = "") -> str:
"""Read the first key=value within a specific [Section] block."""
in_target = False
for line in lines:
stripped = line.strip()
if stripped.startswith("[") and stripped.endswith("]"):
in_target = (stripped[1:-1].strip().lower() == section.lower())
continue
if in_target and stripped.lower().startswith(key.lower() + "="):
return stripped.split("=", 1)[1].strip()
return default
def parse_exe_sections(lines: list) -> list:
"""
Return a list of dicts, one per [ExecutableN] block found in the file.
Handles duplicate section names (as used in the VR Optional template).
"""
sections = []
current = None
for line in lines:
stripped = line.strip()
if stripped.startswith("[") and stripped.endswith("]"):
sec = stripped[1:-1].strip()
if sec.lower().startswith("executable"):
current = {}
sections.append(current)
else:
current = None
elif (current is not None
and "=" in stripped
and not stripped.startswith(";")
and not stripped.startswith("//")):
k, _, v = stripped.partition("=")
current[k.strip().lower()] = v.strip()
return sections
def ini_set_in_section(lines: list, section: str, key: str, value: str) -> list:
"""Replace key=value within a specific named [Section] block only."""
in_target = False
for i, line in enumerate(lines):
stripped = line.strip()
if stripped.startswith("[") and stripped.endswith("]"):
in_target = (stripped[1:-1].strip().lower() == section.lower())
continue
if in_target and stripped.lower().startswith(key.lower() + "="):
lines[i] = f"{key}={value}\r\n"
return lines
return lines
def ini_uncomment_block(lines: list, header: str) -> list:
"""Remove leading ; from a commented-out [Section] block."""
result = []
in_block = False
header_lo = header.strip().lower()
for line in lines:
stripped = line.strip()
no_semi = stripped.lstrip(";").strip()
if no_semi.lower() == header_lo:
in_block = True
result.append(no_semi + "\n")
continue
if in_block:
if stripped.startswith(";") and no_semi.startswith("["):
in_block = False
result.append(no_semi + "\n")
continue
if stripped.startswith(";"):
result.append(no_semi + "\n")
continue
result.append(line)
return result
# ═══════════════════════════════════════════════════════════════════════════
# Repacker identity
# ═══════════════════════════════════════════════════════════════════════════
def get_repacker() -> str:
p = SAVE_DIR / "repacker.txt"
return p.read_text(encoding="utf-8").strip() if p.exists() else ""
def save_repacker(name: str):
SAVE_DIR.mkdir(parents=True, exist_ok=True)
(SAVE_DIR / "repacker.txt").write_text(name + "\n", encoding="utf-8")
# ═══════════════════════════════════════════════════════════════════════════
# Worker functions (pure Python, no PS1 needed)
# ═══════════════════════════════════════════════════════════════════════════
def sanitize_name(name: str) -> str:
name = re.sub(r"['\?]", "", name)
return re.sub(r"\s+", " ", name).strip()
def fs_safe_name(name: str) -> str:
"""Make a release/game name usable as a Windows folder name (no : etc.)."""
name = re.sub(r'[<>:"/\\|?*\x00-\x1f]', "", name)
return re.sub(r"\s+", " ", name).strip().rstrip(". ") or "game"
def dir_size_str(folder: Path) -> str:
"""Return a human-readable size string for a directory (e.g. '14.23 GB')."""
total = sum(f.stat().st_size for f in folder.rglob("*") if f.is_file())
for unit in ("bytes", "KB", "MB", "GB", "TB"):
if total < 1024 or unit == "TB":
return f"{total:.2f} {unit}" if unit != "bytes" else f"{total} bytes"
total /= 1024
return ""
def _has_console() -> bool:
"""True if this process owns a console window.
A --console PyInstaller build (and a plain `python` run) always has one; a
--windowed build does not, and there its child processes need their own
console plus valid std handles to launch reliably.
"""
if os.name != "nt":
return True
try:
import ctypes
return ctypes.windll.kernel32.GetConsoleWindow() != 0
except Exception:
return sys.stdout is not None
def write_temp(filename: str, value: str):
import tempfile
p = Path(tempfile.gettempdir()) / filename
p.write_text(value + " \n", encoding="utf-8")
# ── Pre-processing ───────────────────────────────────────────────────────────
def work_copy_finish_bmp(log) -> None:
"""Copy Welcome.bmp → Finish.bmp in Setup/ if Welcome exists but Finish doesn't."""
welcome = SETUP_DIR / "Welcome.bmp"
finish = SETUP_DIR / "Finish.bmp"
if welcome.exists() and not finish.exists():
shutil.copy2(str(welcome), str(finish))
log(" Finish.bmp created from Welcome.bmp")
elif finish.exists():
log(" Finish.bmp already exists — skipped")
else:
log("[WARN] Welcome.bmp not found in Setup/ — Finish.bmp not created")
def work_rename_originals(game_dir: str, log) -> bool:
folder = Path(game_dir)
if not folder.is_dir():
log(f"[ERROR] Directory not found: {game_dir}")
return False
pattern = re.compile(r"_o(?=\.[^.]+$)|\s*\(Original\)", re.IGNORECASE)
renamed = 0
for f in folder.rglob("*"):
if f.is_file() and pattern.search(f.stem):
new_name = pattern.sub("", f.stem) + ".AG"
f.rename(f.parent / new_name)
log(f" Renamed: {f.name} → {new_name}")
renamed += 1
log(f" {renamed} file(s) renamed." if renamed else " No matching files found.")
return True
def work_sort_dlc(game_dir: str, log) -> bool:
folder = Path(game_dir)
matches = list(folder.rglob("DLC.txt"))
if not matches:
log("[ERROR] DLC.txt not found in game directory.")
return False
dlc_path = matches[0]
content = dlc_path.read_text(encoding="utf-8").splitlines()
def fmt(line):
line = re.sub(
r"^(\d+)\s+(.*?)\s+(?:\(.*?\))?\s+(?:last month|\d+\s+\w+\s+ago)",
r"\1=\2", line)
line = re.sub(r"^(\d+)\s+(\w)", r"\1=\2", line)
return line
modified = [fmt(l) for l in content]
sorted_c = sorted(
modified,
key=lambda l: int(re.match(r"(\d+)", l).group(1))
if re.match(r"(\d+)", l) else 0
)
dlc_path.write_text("\n".join(sorted_c), encoding="utf-8")
log(f" DLC.txt sorted: {dlc_path}")
return True
# ── Settings.ini ─────────────────────────────────────────────────────────────
def has_exe_path(game_type: str, fields: dict) -> bool:
"""True if at least ONE shortcut has an EXE path (not every shortcut is
used on every repack, but zero is never valid)."""
keys = {"PC": ["exe1"],
"VR": ["exe1", "exe2"] + (["exe3"] if fields.get("meta") else []),
"VR Optional": ["exe1", "exe2", "exe3"] + (["exe4"] if fields.get("meta") else []),
}.get(game_type, ["exe1"])
return any(fields.get(k, "").strip() for k in keys)
def ini_has_exe_path() -> bool:
"""True if the saved settings.ini has at least one non-empty Exe= value."""
if not SETTINGS_INI.exists():
return False
return any(l.strip().lower().startswith("exe=") and l.split("=", 1)[1].strip()
for l in ini_read(SETTINGS_INI)
if not l.strip().startswith(";"))
def work_build_settings(game_type: str, fields: dict, log) -> bool:
template = INI_TEMPLATES.get(game_type)
if not template or not template.exists():
log(f"[ERROR] Template not found: {template}")
return False
if not has_exe_path(game_type, fields):
log("[ERROR] No EXE path set for any shortcut — settings.ini not written.")
return False
lines = ini_read(template)
repacker = fields.get("repacker") or get_repacker()
name = fields["name"]
# Common top-level keys
lines = ini_set(lines, "Name", name)
lines = ini_set(lines, "APPID", fields.get("appid", ""))
lines = ini_set(lines, "Buildversion", fields.get("build", ""))
lines = ini_set(lines, "Size", fields.get("size", ""))
lines = ini_set(lines, "REPACKER", repacker)
lines = ini_set(lines, "CompactMode", "1" if fields.get("compact") else "0")
lines = ini_set(lines, "RunAppAsAdmin", "1" if fields.get("admin") else "0")
infobefore_val = "1" if fields.get("infobefore") else "0"
enablebat_val = "1" if fields.get("enablebat") else "0"
if game_type == "PC":
lines = ini_set(lines, "ShortcutName", name, 0)
lines = ini_set(lines, "Exe", fields.get("exe1", ""), 0)
lines = ini_set(lines, "ExeParam", fields.get("exe1p", ""), 0)
lines = ini_set_in_section(lines, "InfoBefore", "Enable", infobefore_val)
lines = ini_set_in_section(lines, "Batch", "Enable", enablebat_val)
if fields.get("enablebat"):
lines = ini_set_in_section(lines, "Batch", "BatchFile", fields.get("batfile", ""))
elif game_type == "VR":
lines = ini_set(lines, "ShortcutName", f"{name} (SteamVR)", 0)
lines = ini_set(lines, "Exe", fields.get("exe1", ""), 0)
lines = ini_set(lines, "ExeParam", fields.get("exe1p", ""), 0)
lines = ini_set(lines, "ShortcutName", f"{name} (VD)", 1)
lines = ini_set(lines, "Exe", fields.get("exe2", ""), 1)
lines = ini_set(lines, "ExeParam", fields.get("exe2p", ""), 1)
if fields.get("meta"):
lines = ini_uncomment_block(lines, "[Executable3]")
lines = ini_set(lines, "ShortcutName", f"{name} (Meta)", 2)
lines = ini_set(lines, "Exe", fields.get("exe3", ""), 2)
lines = ini_set(lines, "ExeParam", fields.get("exe3p",""), 2)
lines = ini_set_in_section(lines, "InfoBefore", "Enable", infobefore_val)
lines = ini_set_in_section(lines, "Batch", "Enable", enablebat_val)
if fields.get("enablebat"):
lines = ini_set_in_section(lines, "Batch", "BatchFile", fields.get("batfile", ""))
elif game_type == "VR Optional":
(BASE_DIR / "vroptional.txt").write_text("1", encoding="utf-8")
lines = ini_set(lines, "ShortcutName", f"{name} (Flat)", 0)
lines = ini_set(lines, "Exe", fields.get("exe1", ""), 0)
lines = ini_set(lines, "ExeParam", fields.get("exe1p", ""), 0)
lines = ini_set(lines, "ShortcutName", f"{name} (SteamVR)", 1)
lines = ini_set(lines, "Exe", fields.get("exe2", ""), 1)
lines = ini_set(lines, "ExeParam", fields.get("exe2p", ""), 1)
lines = ini_set(lines, "ShortcutName", f"{name} (VD)", 2)
lines = ini_set(lines, "Exe", fields.get("exe3", ""), 2)
lines = ini_set(lines, "ExeParam", fields.get("exe3p", ""), 2)
if fields.get("meta"):
lines = ini_uncomment_block(lines, "[Executable3]")
lines = ini_set(lines, "ShortcutName", f"{name} (Meta)", 3)
lines = ini_set(lines, "Exe", fields.get("exe4", ""), 3)
lines = ini_set(lines, "ExeParam", fields.get("exe4p",""), 3)
lines = ini_set_in_section(lines, "InfoBefore", "Enable", infobefore_val)
lines = ini_set_in_section(lines, "Batch", "Enable", enablebat_val)
if fields.get("enablebat"):
lines = ini_set_in_section(lines, "Batch", "BatchFile", fields.get("batfile", ""))
else:
log(f"[ERROR] Unknown game type: {game_type}")
return False
ini_write(SETTINGS_INI, lines)
log(f" settings.ini written for [{game_type}]: {name}")
return True
# ── Compile ──────────────────────────────────────────────────────────────────
def work_compile_gui(log) -> bool:
"""Open Inno Setup IDE to compile (non-blocking, user-facing)."""
if COMPIL32.exists():
subprocess.Popen([str(COMPIL32), "/CC", str(SCRIPT_ISS)],
cwd=str(BASE_DIR))
log(" Inno Setup compiler launched. Close its window when done.")
return True
bat = BASE_DIR / "Compile_Script.bat"
if bat.exists():
subprocess.Popen(str(bat), cwd=str(BASE_DIR), shell=True)
log(" Compile_Script.bat launched.")
return True
log("[ERROR] No compiler found (Compil32Ex.exe / Compile_Script.bat).")
return False
def work_compile_blocking(log) -> bool:
"""Use ISCC.exe (CLI) for a blocking compile in the full-run flow."""
if ISCC.exists():
log(" Compiling with ISCC.exe (blocking)...")
r = subprocess.run([str(ISCC), str(SCRIPT_ISS)], cwd=str(BASE_DIR),
capture_output=True, text=True)
for line in r.stdout.splitlines():
log(" " + line)
for line in r.stderr.splitlines():
log(" " + line)
if r.returncode == 0:
log(" Compilation successful.")
return True
log(f"[ERROR] ISCC exited with code {r.returncode}")
return False
# Fallback: launch GUI compiler and ask user to confirm
log(" ISCC.exe not found — falling back to GUI compiler.")
work_compile_gui(log)
return True # caller shows a dialog
# ── Compress ─────────────────────────────────────────────────────────────────
def work_compress(preset: str, game_dir: str, log) -> bool:
bat = COMPRESSION_BATS.get(preset)
if not bat or not bat.exists():
log(f"[ERROR] Compression bat not found for preset {preset}: {bat}")
return False
# The batch reads dir.tmp / directory.tmp from %TEMP% and writes all of its
# output underneath BASE_DIR (COMPRESSOR\...). If the install folder is not
# writable — e.g. installed under Program Files and launched without admin —
# every write below fails and the compression silently produces nothing.
# Catch that here with a clear message instead of a mystery "no data.bin".
try:
CONVERSION_DIR.mkdir(parents=True, exist_ok=True)
(COMPRESSOR / "Conversion_Output").mkdir(parents=True, exist_ok=True)
probe = COMPRESSOR / "Conversion_Output" / ".write_test"
probe.write_bytes(b"")
probe.unlink()
except OSError as e:
log(f"[ERROR] Cannot write to the working folder: {e}")
log(f" Location: {COMPRESSOR}")
log(" Run the app as administrator, or install it somewhere writable")
log(" (not inside Program Files).")
return False
write_temp("dir.tmp", game_dir)
write_temp("directory.tmp", str(BASE_DIR))
write_temp("preset.tmp", preset)
log(f" Running compression preset {preset} — this will take a while...")
log(" (watch the CMD window for Arc progress)")
# Clear any stale Data.bin so the success check below can't be fooled by a
# leftover from a previous run.
data_bin = CONVERSION_DIR / "Data.bin"
try:
if data_bin.exists():
data_bin.unlink()
except OSError:
pass
# Write a temp bat with PAUSE removed so the window closes automatically.
bat_lines = bat.read_bytes().decode("utf-8", errors="replace").splitlines(keepends=True)
no_pause = "".join(ln for ln in bat_lines if ln.strip().upper() != "PAUSE")
tmp_bat = bat.parent / f"_tmp_{bat.name}"
try:
tmp_bat.write_bytes(no_pause.encode("utf-8"))
except OSError as e:
log(f"[ERROR] Cannot write compression helper script: {e}")
log(f" Location: {tmp_bat.parent}")
log(" Run the app as administrator, or install it somewhere writable.")
return False
# In a --windowed (no-console) PyInstaller build the process has no console
# and its std handles are invalid, which can make the child cmd abort the
# moment it launches. Give the child its own console and a valid stdin so
# it runs the same way it does under the --console build.
run_kwargs = {"cwd": str(BASE_DIR), "shell": True}
if os.name == "nt" and not _has_console():
run_kwargs["creationflags"] = getattr(subprocess, "CREATE_NEW_CONSOLE", 0)
run_kwargs["stdin"] = subprocess.DEVNULL
try:
r = subprocess.run(str(tmp_bat), **run_kwargs)
finally:
try:
tmp_bat.unlink()
except OSError:
pass
if r.returncode != 0:
log(f"[ERROR] Compression failed (exit code {r.returncode}).")
return False
# Verify the batch actually produced Data.bin. A non-zero-length file is
# the only reliable signal that Arc ran to completion — the exit code alone
# is not trustworthy when the paths handed to the batch were empty/unreadable.
if not data_bin.exists() or data_bin.stat().st_size == 0:
log(f"[ERROR] Compression finished but Data.bin was not produced: {data_bin}")
log(" Common causes:")
log(" • The game directory was empty, wrong, or unreadable.")
log(" • The install folder is not writable (see Program Files / admin note above).")
log(" • The game path contains non-English characters.")
return False
log(" Compression complete.")
return True
# ── Records ──────────────────────────────────────────────────────────────────
def work_records(preset: str, log) -> bool:
data_bin = CONVERSION_DIR / "data.bin"
if not data_bin.exists():
log(f"[ERROR] data.bin not found: {data_bin}")
return False
template = DLL_DIR / "recordstemplate.ini"
if not template.exists():
log(f"[ERROR] recordstemplate.ini not found: {template}")
return False
size_bytes = data_bin.stat().st_size
formatted = "{:,}".format(size_bytes).replace(",", ".")
lines = ini_read(template)
lines = ini_set(lines, "Size", f"{formatted} bytes")
ini_write(template, lines)
dest = DLL_DIR / preset / "Records.ini"
dest.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(template, dest)
log(f" Records.ini written ({formatted} bytes) → {dest}")
return True
# ── Create DLL ───────────────────────────────────────────────────────────────
def work_create_dll(preset: str, log) -> bool:
if not ARC_EXE.exists():
log(f"[ERROR] Arc.exe not found: {ARC_EXE}")
return False
src_dir = DLL_DIR / preset
if not src_dir.is_dir():
log(f"[ERROR] DLL source folder not found: {src_dir}")
return False
tmp = BASE_DIR / "temp"
tmp.mkdir(exist_ok=True)
cmd = [str(ARC_EXE), "a", "-ep1", "-r", "-ed", "-s",
f"-w{tmp}", "-mx", "AGRepackInstaller.dll",
str(src_dir / "*")]
log(" Building AGRepackInstaller.dll with Arc...")
subprocess.run(cmd, cwd=str(BASE_DIR))
created = BASE_DIR / "AGRepackInstaller.dll"
dest = CONVERSION_DIR / "AGRepackInstaller.dll"
if created.exists():
CONVERSION_DIR.mkdir(parents=True, exist_ok=True)
shutil.move(str(created), str(dest))
log(f" AGRepackInstaller.dll → {dest}")
else:
log("[ERROR] AGRepackInstaller.dll was not produced by Arc.")
return False
# Remove Records.ini from preset dir (it's been consumed)
rec = src_dir / "Records.ini"
if rec.exists():
rec.unlink()
shutil.rmtree(tmp, ignore_errors=True)
return True
# ── Merge DLL into EXE ───────────────────────────────────────────────────────
def work_internal_dll(log, blocking_compile: bool = False) -> bool:
dll_src = CONVERSION_DIR / "AGRepackInstaller.dll"
if not dll_src.exists():
log(f"[ERROR] AGRepackInstaller.dll not found: {dll_src}")
return False
# VR Optional: back up DLL + Data.bin before consuming them
optional = BASE_DIR / "vroptional.txt"
if optional.exists():
SAVE_DIR.mkdir(parents=True, exist_ok=True)
shutil.copy2(str(dll_src), str(SAVE_DIR / "AGRepackInstaller.dll"))
data_bin = CONVERSION_DIR / "Data.bin"
if data_bin.exists():
shutil.copy2(str(data_bin), str(SAVE_DIR / "Data.bin"))
log(" VR Optional: DLL + Data.bin backed up to Save/")
# Remove Autorun.inf if present
autorun = CONVERSION_DIR / "Autorun.inf"
if autorun.exists():
autorun.unlink()
log(" Autorun.inf removed.")
# Move DLL next to Script.iss
dll_beside = BASE_DIR / "AGRepackInstaller.dll"
shutil.move(str(dll_src), str(dll_beside))
# Enable ;#define InternalDLL in Script.iss
iss_raw = SCRIPT_ISS.read_bytes()
bom = iss_raw[:3] == b"\xef\xbb\xbf"
iss_body = iss_raw[3:] if bom else iss_raw
lines = iss_body.decode("utf-8").splitlines(keepends=True)
for i, ln in enumerate(lines):
if "InternalDLL" in ln and ln.strip().startswith(";"):
eol = "\r\n" if ln.endswith("\r\n") else "\n"
lines[i] = f"#define InternalDLL{eol}"
break
iss_out = "".join(lines).encode("utf-8")
SCRIPT_ISS.write_bytes((b"\xef\xbb\xbf" if bom else b"") + iss_out)
log(" InternalDLL enabled — compiling...")
if blocking_compile:
compile_ok = work_compile_blocking(log)
else:
compile_ok = work_compile_gui(log)
time.sleep(2) # brief pause so the compile has a moment to start
# Re-disable InternalDLL
iss_raw2 = SCRIPT_ISS.read_bytes()
bom2 = iss_raw2[:3] == b"\xef\xbb\xbf"
iss_body2 = iss_raw2[3:] if bom2 else iss_raw2
lines2 = iss_body2.decode("utf-8").splitlines(keepends=True)
for i, ln in enumerate(lines2):
if "InternalDLL" in ln and not ln.strip().startswith(";"):
eol2 = "\r\n" if ln.endswith("\r\n") else "\n"
lines2[i] = f";#define InternalDLL{eol2}"
break
iss_out2 = "".join(lines2).encode("utf-8")
SCRIPT_ISS.write_bytes((b"\xef\xbb\xbf" if bom2 else b"") + iss_out2)
# Move DLL to Setup folder for archiving
dll_setup = SETUP_DIR / "AGRepackInstaller.dll"
if dll_beside.exists():
shutil.move(str(dll_beside), str(dll_setup))
# Move compiled EXE into CONVERSION dir
exe_src = SETUP_FILES / "AGRepackInstaller.exe"
exe_dest = CONVERSION_DIR / "AGRepackInstaller.exe"
if exe_src.exists():
shutil.move(str(exe_src), str(exe_dest))
log(f" AGRepackInstaller.exe → {exe_dest}")
else:
log("[WARN] AGRepackInstaller.exe not found in Setup_Files/ after compile.")
log(" DLL merge complete.")
return compile_ok
# ── Repack log dump ──────────────────────────────────────────────────────────
def save_repack_log(log_text: str, log) -> None:
"""Write the session log to Background/repack_log.txt so it gets bundled
into the art archive by work_archive_art()."""
bg_dir = SETUP_DIR / "Background"
bg_dir.mkdir(parents=True, exist_ok=True)
out = bg_dir / "repack_log.txt"
out.write_text(log_text, encoding="utf-8")
log(f" Repack log saved: {out.name}")
# ── Zip & Name ───────────────────────────────────────────────────────────────
def release_name_parts(lines: list) -> tuple:
"""(game name, build, group tag) exactly as the finished repack is named."""
name = sanitize_name(ini_get(lines, "Name", "Game"))
build = ini_get(lines, "Buildversion", "")
admin = ini_get(lines, "RunAppAsAdmin", "0")
if (BASE_DIR / "vroptional.txt").exists():
name += " VR"
group = "-ARMGDDN"
if admin.strip() == "1":
group += " + OFME"
return name, build, group
def work_zip_and_name(log, nested: bool = False):
"""Zip the converted files and name the package. Returns the package folder
(truthy) on success, False on failure.
Normal layout: <Release>\\<appid> and the .7z / .7z.00x beside it.
nested=True (an update patch goes with it):
<Release>\\<appid>
<Release>\\<Release>\\*.7z.00x
The patch folder is later moved into <Release> as <Release>\\<patch name>."""
if not SETTINGS_INI.exists():
log("[ERROR] settings.ini not found.")
return False
if not SEVEN_ZIP.exists():
log(f"[ERROR] 7z.exe not found: {SEVEN_ZIP}")
return False
lines = ini_read(SETTINGS_INI)
appid = ini_get(lines, "APPID", "")
optional = BASE_DIR / "vroptional.txt"
name, build, group = release_name_parts(lines)
zip_name = f"{name} v{build} {group}.7z"
folder_name = f"{name} v{build} {group}"
out_folder = BASE_DIR / folder_name
out_folder.mkdir(exist_ok=True)
archive_dir = out_folder / folder_name if nested else out_folder
archive_dir.mkdir(parents=True, exist_ok=True)
files = [f for f in CONVERSION_DIR.iterdir() if f.is_file()]
total = sum(f.stat().st_size for f in files)
split_flag = ["-v5000M"] if total > 10 * 1024 ** 3 else []
cmd = ([str(SEVEN_ZIP), "a", "-t7z", "-mx=0", "-sdel"]
+ split_flag
+ [zip_name, str(CONVERSION_DIR / "*")])
log(f" Creating archive: {zip_name}")
subprocess.run(cmd, cwd=str(BASE_DIR))
# Move single or multi-part archive into output folder
parts = sorted(BASE_DIR.glob("*.001"))
if parts:
n = 1
while True:
part_list = list(BASE_DIR.glob(f"*.{n:03d}"))
if not part_list:
break
for pf in part_list:
shutil.move(str(pf), str(archive_dir / pf.name))
n += 1
log(f" Multi-part archive moved to: {archive_dir}")
else:
zf = BASE_DIR / zip_name
if zf.exists():
shutil.move(str(zf), str(archive_dir / zf.name))
log(f" Archive moved to: {archive_dir}")
if appid:
(out_folder / appid).touch()
# Drop crashfix.bat into the repack, loose next to the appid file (not zipped)
crashfix_src = SETUP_DIR / "crashfix.bat"
if crashfix_src.exists():
shutil.copy2(str(crashfix_src), str(out_folder / crashfix_src.name))
log(f" Added crashfix.bat to: {out_folder}")
else:
log(f" [WARN] crashfix.bat not found in Setup — skipped: {crashfix_src}")
# VR Optional: restore backed-up files for the 2nd pass
if optional.exists():
dll_save = SAVE_DIR / "AGRepackInstaller.dll"
bin_save = SAVE_DIR / "Data.bin"
if dll_save.exists():
shutil.move(str(dll_save), str(CONVERSION_DIR / "AGRepackInstaller.dll"))
if bin_save.exists():
shutil.move(str(bin_save), str(CONVERSION_DIR / "Data.bin"))
optional.unlink()
log(" VR Optional files restored for second pass.")
return out_folder
# ── Update patch (XDelta) ────────────────────────────────────────────────────
# Flow: the OLD repack is silently installed to XDelta\Games\old while the new
# one compresses; once the new installer exists it is silently installed to
# XDelta\Games\new, then the patch maker opens pre-filled while zipping carries on.
def patch_clear_dirs(log) -> None:
"""Empty Games/old and Games/new (keeping their .gitkeep placeholders)."""
for d in (PATCH_OLD_DIR, PATCH_NEW_DIR):
d.mkdir(parents=True, exist_ok=True)
for item in d.iterdir():
if item.name in (".gitkeep", ".gitignore"):
continue
if item.is_dir():
shutil.rmtree(item, ignore_errors=True)
else:
try:
item.unlink()
except OSError:
pass
log(" Cleared XDelta\\Games\\old and XDelta\\Games\\new.")
def patch_dirs_dirty() -> bool:
return any(item.name not in (".gitkeep", ".gitignore")
for d in (PATCH_OLD_DIR, PATCH_NEW_DIR) if d.exists()
for item in d.iterdir())
def _run_installer(exe: Path, args: str) -> int:
"""Run an installer, wait for it and return its exit code. The installers
ask for administrator rights; Python's normal process launch refuses
those when the repacker isn't elevated (WinError 740), so fall back to
ShellExecuteEx 'runas', which raises the UAC prompt instead."""
cmdline = f'"{exe}" {args}'
try:
return subprocess.run(cmdline, cwd=str(exe.parent)).returncode
except OSError as e:
if getattr(e, "winerror", None) != 740:
raise
import ctypes
from ctypes import wintypes
class SHELLEXECUTEINFOW(ctypes.Structure):
_fields_ = [("cbSize", wintypes.DWORD), ("fMask", wintypes.ULONG),
("hwnd", wintypes.HWND), ("lpVerb", wintypes.LPCWSTR),
("lpFile", wintypes.LPCWSTR), ("lpParameters", wintypes.LPCWSTR),
("lpDirectory", wintypes.LPCWSTR), ("nShow", ctypes.c_int),
("hInstApp", wintypes.HINSTANCE), ("lpIDList", ctypes.c_void_p),
("lpClass", wintypes.LPCWSTR), ("hkeyClass", wintypes.HKEY),
("dwHotKey", wintypes.DWORD), ("hIcon", wintypes.HANDLE),
("hProcess", wintypes.HANDLE)]
SEE_MASK_NOCLOSEPROCESS = 0x40
info = SHELLEXECUTEINFOW()
info.cbSize = ctypes.sizeof(info)
info.fMask = SEE_MASK_NOCLOSEPROCESS
info.lpVerb = "runas"
info.lpFile = str(exe)
info.lpParameters = args
info.lpDirectory = str(exe.parent)
info.nShow = 0 # SW_HIDE
if not ctypes.windll.shell32.ShellExecuteExW(ctypes.byref(info)):
return -1 # UAC declined
ctypes.windll.kernel32.WaitForSingleObject(info.hProcess, 0xFFFFFFFF)
code = wintypes.DWORD()
ctypes.windll.kernel32.GetExitCodeProcess(info.hProcess, ctypes.byref(code))
ctypes.windll.kernel32.CloseHandle(info.hProcess)
return code.value
def patch_install(label: str, installer: Path, dest: Path, log,
uninstaller: bool = True) -> bool:
"""Silently install a repack into dest (Inno Setup switches). /LANG skips
the installer's language picker and /NOICONS/TASKS keep it from adding
shortcuts. uninstaller=False adds /NOUNINSTALL (our Script.iss switch):
the NEW repack ships without an uninstaller, so the patch deletes the old
one from the user's install instead of leaving it behind, broken."""
if not installer.exists():
log(f"[ERROR] {label} repack installer not found: {installer}")
return False
dest.mkdir(parents=True, exist_ok=True)
log(f" Installing {label} repack silently → {dest}")
args = (f'/VERYSILENT /SUPPRESSMSGBOXES /NORESTART /SP- /NOICONS /TASKS="" '
f'/LANG=english /DIR="{dest}"' + ("" if uninstaller else " /NOUNINSTALL"))
try:
code = _run_installer(installer, args)
except OSError as e:
log(f"[ERROR] Could not start the {label} installer: {e}")
return False
if code != 0:
log(f"[ERROR] {label} installer exited with code {code}.")
return False
if not any(dest.iterdir()):
log(f"[ERROR] {label} installer reported success but {dest} is empty.")
return False
log(f" {label.capitalize()} repack installed.")
return True
def patch_launch_maker(old_release: str, new_release: str, log):
"""Open the patch maker GUI pre-filled with both release names. Returns the
process (so the upload step can wait for the result file) or None."""
if not PATCH_GUI_PS1.exists():
log(f"[ERROR] Patch maker not found: {PATCH_GUI_PS1}")
return None
PATCH_RESULT.parent.mkdir(parents=True, exist_ok=True)
try:
PATCH_RESULT.unlink() # a stale result must never count as this run's
except OSError:
pass
cmd = ["powershell.exe", "-NoProfile", "-ExecutionPolicy", "Bypass",
"-WindowStyle", "Hidden", "-File", str(PATCH_GUI_PS1),
"-OldRelease", old_release, "-NewRelease", new_release, "-KeepGames",
"-ToolkitDir", str(BASE_DIR), "-ResultFile", str(PATCH_RESULT)]
flags = getattr(subprocess, "CREATE_NO_WINDOW", 0)
proc = subprocess.Popen(cmd, cwd=str(XDELTA_DIR), creationflags=flags)
log(" Patch maker opened — click Build Patch there when ready.")
return proc
def patch_wait_result(proc, log):
"""Block until the patch maker has packaged a patch (or been closed without
one). Returns the patch's upload folder, or None."""
log(" Waiting for the update patch to finish building "
"(click Build Patch in the patch maker if you haven't)...")
waited = 0
while True:
if PATCH_RESULT.exists():
try:
data = json.loads(PATCH_RESULT.read_text(encoding="utf-8-sig"))
folder = Path(data.get("uploadDir", ""))
if folder.is_dir():
log(f" Update patch ready: {folder.name}")
return folder
except (OSError, ValueError):
pass # half-written — look again next pass
if proc is not None and proc.poll() is not None and not PATCH_RESULT.exists():
return None # patch maker closed with nothing built
time.sleep(3)
waited += 3
if waited % 300 == 0:
log(f" ...still waiting for the update patch ({waited // 60} min)")
def patch_place_in_release(patch_folder: Path, release_folder: Path, log) -> Path:
"""Move the finished patch into <Release>\\<patch name>\\ (beside the nested
<Release>\\<Release> archive folder), so it uploads with the release. Returns
the patch's new folder (or the original if it couldn't be moved)."""
dest = release_folder / patch_folder.name
if dest.resolve() == patch_folder.resolve():
return patch_folder
try:
dest.mkdir(parents=True, exist_ok=True)
for item in patch_folder.iterdir():