Skip to content

Play your own Switch games on iPhone/iPad — one-click macOS app, no terminal. | 把 Switch 游戏装进 iPhone:图形界面一键构建,不用命令行。Bring your own game.

Qt launcher: a Switch 2 game as a game folder or a NUP file builds with no prod.keys

v0lumehi301e25953086
diff --git a/frontend-qt/nspb_qt/inputs.py b/frontend-qt/nspb_qt/inputs.py
index 3e411625..7ba55971 100644
--- a/frontend-qt/nspb_qt/inputs.py
+++ b/frontend-qt/nspb_qt/inputs.py
@@ -2,7 +2,10 @@
The same rules as the Mac launcher's GameInputs.classify, so both front ends agree."""
from __future__ import annotations
+import os
import re
+import struct
+from dataclasses import dataclass, field
from pathlib import Path
GAME_SUFFIXES = ('.nsp', '.xci', '.nsz', '.xcz')
@@ -95,3 +98,210 @@ def classify(files: list[Path]) -> dict:
newest = max(updates, key=lambda u: u[2]) if updates else None
return {'base': base, 'update': newest[1] if newest else None,
'dlc': sorted(dlcs), 'update_count': len(updates)}
+
+
+# ---- a game as a folder of its files, or one NUP file (Switch 2 games). The same rules as the Mac launcher's GameFolder,
+# which follow the engine's pack_dump.py (is_dump, scan, program_id), pack_nup.py and build_ipa_from_nsp.py (dump_folder,
+# nup_file). Neither is encrypted, so the build needs no prod.keys. Reads names and the first bytes of main.npdm only.
+
+_PACKAGES = ('.nsp', '.xci', '.nsz', '.xcz')
+
+
+@dataclass
+class GameFolderContents:
+ """What a game folder or a NUP holds."""
+ folder: str # the game folder, or the folder a NUP is in
+ title_id: int # the program ID in base/exefs/main.npdm, or the NUP's (0: the script reads it from the code)
+ updates: list[tuple[int, str]] = field(default_factory=list) # (version, path), oldest first
+ dlc: list[tuple[int, str]] = field(default_factory=list) # (DLC title ID, path), sorted by title ID
+ nup: str | None = None # the NUP file the game is in, None for a folder of files
+
+ @property
+ def title_id_hex(self) -> str:
+ return f'{self.title_id:016X}'
+
+ @property
+ def has_title_id(self) -> bool:
+ return self.title_id != 0
+
+ @property
+ def base_path(self) -> str:
+ return self.nup or str(Path(self.folder, 'base'))
+
+ @property
+ def script_input(self) -> str:
+ """What the script is given: the NUP file, else the folder."""
+ return self.nup or self.folder
+
+ @property
+ def newest_update(self) -> tuple[int, str] | None:
+ return self.updates[-1] if self.updates else None
+
+
+@dataclass(frozen=True)
+class GameFolderProblem:
+ """Why a game folder cannot be built. `kind` is the Mac launcher's Problem case, `args` fill its text
+ (`folder.problem.<key>`, see `l10n_key`)."""
+ kind: str # missing noBaseFolder unreadableNPDM notBaseTitle packageBeside dlcName notDLC dlcRomFS notNUP nupPartial severalNUPs
+ args: tuple = ()
+
+ @property
+ def l10n_key(self) -> str:
+ return 'folder.problem.' + {
+ 'missing': 'missing', 'noBaseFolder': 'noBase', 'unreadableNPDM': 'npdm', 'notBaseTitle': 'notBase',
+ 'packageBeside': 'package', 'dlcName': 'dlcName', 'notDLC': 'notDLC', 'dlcRomFS': 'dlcRomFS',
+ 'notNUP': 'notNUP', 'nupPartial': 'nupPartial', 'severalNUPs': 'severalNUPs'}[self.kind]
+
+
+def _is_file(p: str | Path) -> bool:
+ return Path(p).is_file()
+
+
+def _is_nup_name(path: str) -> bool:
+ return str(path).lower().endswith('.nup') and _is_file(path)
+
+
+def nup_files(folder: str) -> list[str]:
+ """The NUP files at the top of a folder (the script looks there only), by name."""
+ try:
+ names = os.listdir(folder)
+ except OSError:
+ return []
+ return sorted(n for n in names if not n.startswith('._') and n.lower().endswith('.nup') and _is_file(Path(folder, n)))
+
+
+def is_game_folder_candidate(path: str) -> bool:
+ """Whether the path is meant as a game folder or a NUP: a .nup file, a folder with a .nup at its top, a folder with
+ base/exefs/main.npdm, or exefs/main.npdm with no base/ (the files one level too high). Cheap."""
+ if _is_nup_name(path):
+ return True
+ if _is_file(Path(path, 'base', 'exefs', 'main.npdm')) or nup_files(path):
+ return True
+ return _is_file(Path(path, 'exefs', 'main.npdm')) and not Path(path, 'base').exists()
+
+
+def program_id(npdm: bytes) -> int | None:
+ """The ACI0 program ID of an NPDM (pack_dump.py program_id): the ACI0 offset and size at 0x70, the ID at ACI0 + 0x10."""
+ if len(npdm) < 0x78 or npdm[:4] != b'META':
+ return None
+ off, size = struct.unpack_from('<II', npdm, 0x70)
+ if size < 0x18 or off + 0x18 > len(npdm) or npdm[off:off + 4] != b'ACI0':
+ return None
+ return struct.unpack_from('<Q', npdm, off + 0x10)[0]
+
+
+def read_nup(path: str) -> GameFolderContents | GameFolderProblem:
+ """A NUP's title ID, updates and DLC from its header and package table (SPEC v1, pack_nup.py). The title ID is the base
+ package's, else an update's with the low 12 bits cleared, else 0. Checks the magic, the version and the file size,
+ not the SHA-256s (the script checks every file it reads)."""
+ name = Path(path).name
+ try:
+ size = os.path.getsize(path)
+ with open(path, 'rb') as f:
+ head = f.read(0x80)
+ if len(head) != 0x80 or head[:3] != b'NUP' or head[3] != 1:
+ return GameFolderProblem('notNUP', (name,))
+ if struct.unpack_from('<Q', head, 0x40)[0] != size:
+ return GameFolderProblem('nupPartial', (name,))
+ toc = struct.unpack_from('<Q', head, 0x08)[0]
+ count = struct.unpack_from('<I', head, 0x48)[0]
+ if not 0 < count < 100_000 or toc + 0x30 + count * 0x40 > size:
+ return GameFolderProblem('notNUP', (name,))
+ f.seek(toc)
+ table = f.read(0x30 + count * 0x40)
+ except OSError:
+ return GameFolderProblem('notNUP', (name,))
+ if len(table) != 0x30 + count * 0x40 or table[:4] != b'TOC\x01':
+ return GameFolderProblem('notNUP', (name,))
+ base = update_title = 0
+ updates: list[tuple[int, str]] = []
+ addons: list[int] = []
+ for i in range(count):
+ o = 0x30 + i * 0x40
+ tid = struct.unpack_from('<Q', table, o)[0]
+ version = struct.unpack_from('<I', table, o + 20)[0]
+ kind = table[o + 24]
+ if kind == 0:
+ base = tid
+ elif kind == 1:
+ updates.append((version, path))
+ if update_title == 0:
+ update_title = tid & ~0xFFF
+ elif kind == 2:
+ addons.append(tid)
+ app = base if base != 0 and base & 0xFFF == 0 else update_title
+ return GameFolderContents(folder=str(Path(path).parent), title_id=app, updates=sorted(updates, key=lambda u: u[0]),
+ dlc=[(t, path) for t in sorted(addons)], nup=path)
+
+
+def scan_game_folder(path: str) -> GameFolderContents | GameFolderProblem:
+ """What the folder (or NUP file) holds, or the first reason it cannot be built, in the order the script finds them."""
+ if _is_nup_name(path):
+ return read_nup(path)
+ root = Path(path)
+
+ def dirs(p: Path) -> list[str]:
+ try:
+ return sorted(n for n in os.listdir(p) if not n.startswith('.') and Path(p, n).is_dir())
+ except OSError:
+ return []
+
+ try:
+ top = sorted(os.listdir(path))
+ except OSError:
+ top = []
+ for n in top:
+ if not n.startswith('._') and n.lower().endswith(_PACKAGES) and _is_file(root / n):
+ return GameFolderProblem('packageBeside', (n,))
+ nups = nup_files(path)
+ if len(nups) > 1:
+ return GameFolderProblem('severalNUPs', (len(nups),))
+ if nups:
+ return read_nup(str(root / nups[0]))
+ npdm = root / 'base' / 'exefs' / 'main.npdm'
+ if not npdm.is_file():
+ if (root / 'exefs' / 'main.npdm').is_file() and not (root / 'base').exists():
+ return GameFolderProblem('noBaseFolder')
+ return GameFolderProblem('missing', ('base/exefs/main.npdm',))
+ versions = [v for v in dirs(root / 'updates') if v.isascii() and v.isdigit()] if (root / 'updates').is_dir() else []
+ if not ((root / 'base' / 'romfs').is_dir() or any((root / 'updates' / v / 'romfs').is_dir() for v in versions)):
+ return GameFolderProblem('missing', ('base/romfs',))
+ try:
+ app = program_id(npdm.read_bytes())
+ except OSError:
+ app = None
+ if app is None:
+ return GameFolderProblem('unreadableNPDM')
+ if app & 0xFFF:
+ return GameFolderProblem('notBaseTitle', (f'{app:016X}',))
+ updates = sorted((int(v), str(root / 'updates' / v)) for v in versions)
+ dlc: list[tuple[int, str]] = []
+ for name in dirs(root / 'dlc') if (root / 'dlc').is_dir() else []:
+ d = root / 'dlc' / name
+ try:
+ tid = int(name, 16) if len(name) <= 16 else None
+ except ValueError:
+ tid = None
+ if tid is None:
+ return GameFolderProblem('dlcName', (name,))
+ if not 0 < tid - app - 0x1000 <= 2000:
+ return GameFolderProblem('notDLC', (name,))
+ numbered = [n for n in dirs(d) if (d / n / 'romfs').is_dir()]
+ count = len(numbered) if numbered else (1 if (d / 'romfs').is_dir() else 0)
+ if count != 1:
+ return GameFolderProblem('dlcRomFS', (name, count))
+ dlc.append((tid, str(d)))
+ return GameFolderContents(folder=path, title_id=app, updates=updates, dlc=sorted(dlc))
+
+
+def engine_builds_folders(engine_root: str) -> bool:
+ return bool(engine_root) and Path(engine_root, 'scripts', 'pack_dump.py').is_file()
+
+
+def engine_builds_nups(engine_root: str) -> bool:
+ return bool(engine_root) and Path(engine_root, 'scripts', 'pack_nup.py').is_file()
+
+
+def engine_has_profile(title_id: int, engine_root: str) -> bool:
+ """The script packs a game folder only for a game with a profile."""
+ return bool(engine_root) and Path(engine_root, 'dm', 'games', f'{title_id:016X}', 'game.tsv').is_file()
diff --git a/frontend-qt/nspb_qt/l10n.py b/frontend-qt/nspb_qt/l10n.py
index ddbc164b..2ee79740 100644
--- a/frontend-qt/nspb_qt/l10n.py
+++ b/frontend-qt/nspb_qt/l10n.py
@@ -21,6 +21,7 @@ from __future__ import annotations
import json
import os
+import re
import sys
from dataclasses import dataclass
from typing import TYPE_CHECKING
@@ -147,8 +148,10 @@ def t(key: str, lang: Lang, *args: object) -> str:
s = row.get(lang.code, row.get('en', key)) if row else key
if not args:
return s
- py = s.replace("%@", "%s") # %d is the same in both; %@ is Swift-only
try:
+ if re.search(r'%\d+\$[@d]', s): # positional (%1$@, %2$d): the argument by its number
+ return re.sub(r'%(\d+)\$([@d])', lambda m: str(args[int(m.group(1)) - 1]), s)
+ py = s.replace("%@", "%s") # %d is the same in both; %@ is Swift-only
return py % args
- except (TypeError, ValueError):
+ except (TypeError, ValueError, IndexError):
return s
diff --git a/frontend-qt/nspb_qt/model.py b/frontend-qt/nspb_qt/model.py
index f0e42bb6..b843d601 100644
--- a/frontend-qt/nspb_qt/model.py
+++ b/frontend-qt/nspb_qt/model.py
@@ -109,6 +109,8 @@ class Model(QObject):
self.update_path = ''
self.dlc_paths: list[str] = []
self.keys_path = ''
+ self.game_folder: inputs.GameFolderContents | None = None # a game chosen as a folder of files or a NUP (no keys needed)
+ self.game_folder_problem = '' # why a chosen game folder cannot be built, shown on the base row
self.out_dir = ''
self.ipa_path = ''
self.archive_path = ''
@@ -1174,6 +1176,10 @@ class Model(QObject):
def scan_game_dir(self, d: str) -> None:
"""Pick the four inputs out of a folder (and its subfolders, one level): a base NSP,
an update, DLCs and prod.keys, by the naming the dumps use."""
+ if inputs.is_game_folder_candidate(d):
+ self.take_game_folder(d)
+ return
+ self.leave_game_folder()
self.game_dir = d
root = Path(d)
if not root.is_dir():
@@ -1191,10 +1197,86 @@ class Model(QObject):
self.dlc_paths = [str(f) for f in found['dlc']]
self.repoChanged.emit()
+ # ---- a game as a folder of its files or a NUP (Switch 2 games), see inputs.scan_game_folder
+
+ def take_game_folder(self, path: str) -> None:
+ """Fill the rows from a game folder or a NUP file, or show the reason it cannot be built on the base row."""
+ self.game_dir = str(Path(path).parent) if path.lower().endswith('.nup') else path
+ self.game_folder = None
+ self.game_folder_problem = ''
+ self.base_path = self.update_path = ''
+ self.dlc_paths = []
+ found = inputs.scan_game_folder(path)
+ if isinstance(found, inputs.GameFolderProblem):
+ self.game_folder_problem = self.t(found.l10n_key, *found.args)
+ else:
+ why = self.game_folder_engine_problem(found)
+ if why:
+ self.game_folder_problem = why
+ else:
+ self.game_folder = found
+ self.base_path = found.base_path
+ newest = found.newest_update
+ self.update_path = newest[1] if newest else ''
+ self.dlc_paths = [p for _, p in found.dlc]
+ self.repoChanged.emit()
+
+ def leave_game_folder(self) -> None:
+ """Back to packages: the folder's rows are emptied, so a picked package never mixes with them."""
+ if self.game_folder is None and not self.game_folder_problem:
+ return
+ self.game_folder = None
+ self.game_folder_problem = ''
+ self.base_path = self.update_path = ''
+ self.dlc_paths = []
+
+ def game_folder_engine_problem(self, found: 'inputs.GameFolderContents') -> str:
+ """What the engine lacks for this game: the packer (an older engine) or a profile for the game. '' when nothing,
+ and before the engine exists (the build asks again)."""
+ eng = self.engine_path
+ if not eng or not Path(eng, 'dm').is_dir():
+ return ''
+ builds = inputs.engine_builds_nups(eng) if found.nup else inputs.engine_builds_folders(eng)
+ if not builds:
+ return self.t('folder.engineOldNUP' if found.nup else 'folder.engineOld')
+ if found.has_title_id and not inputs.engine_has_profile(found.title_id, eng):
+ return self.t('folder.noProfile', found.title_id_hex)
+ return ''
+
+ def input_row_text(self, key: str) -> str | None:
+ """A row's text while a game folder is chosen, None otherwise (the row then shows its files as for packages)."""
+ f = self.game_folder
+ if f is None:
+ return None
+ if key == 'base':
+ if f.nup is None:
+ return self.t('folder.base', f.title_id_hex)
+ return self.t('folder.nupBase', f.title_id_hex) if f.has_title_id else self.t('folder.nupBaseNoID')
+ if key == 'update':
+ newest = f.newest_update
+ if newest is None:
+ return self.t('data.notSelectedOptional')
+ return (self.t('folder.updates', newest[0], len(f.updates)) if len(f.updates) > 1
+ else self.t('folder.update', newest[0]))
+ if key == 'dlc':
+ return self.t('folder.dlc', len(f.dlc)) if f.dlc else self.t('data.notSelectedDlc')
+ if key == 'keys':
+ return self.t('folder.keys')
+ return None
+
+ @property
+ def build_key(self) -> str:
+ """The name of the work folder and the app (<key>_build, <key>.app): the folder's title ID, else the base package's."""
+ f = self.game_folder
+ if f is None:
+ return inputs.build_key(self.base_path)
+ return f.title_id_hex if f.has_title_id else inputs.build_key(f.script_input)
+
@property
def can_build(self) -> bool:
- return (self.repo_ok and bool(self.base_path) and bool(self.keys_path)
- and self.all_deps_ok and not self.running)
+ # a game folder needs no keys, a refused one cannot build
+ inputs_ready = self.game_folder is not None or (bool(self.base_path) and bool(self.keys_path))
+ return self.repo_ok and inputs_ready and self.all_deps_ok and not self.running
# ---- build
@@ -1209,14 +1291,21 @@ class Model(QObject):
self.sync_engine(lambda ok: QMetaObject.invokeMethod(self, '_build_after_sync', Qt.QueuedConnection, Q_ARG(bool, ok)))
return
py = self.python_path or ('python' if pu.IS_WIN else '/usr/bin/python3')
- base_dir = str(Path(self.base_path).parent)
- all_files = [self.base_path, self.update_path] + self.dlc_paths
+ folder = self.game_folder
+ if folder is not None:
+ why = self.game_folder_engine_problem(folder)
+ if why:
+ self.finished.emit(False, why)
+ return
+ base_dir = folder.folder if folder is not None else str(Path(self.base_path).parent)
+ # a game folder or a NUP goes to the script as it is: nothing is staged and no file is a package
+ all_files = [] if folder is not None else [self.base_path, self.update_path] + self.dlc_paths
dirs = {str(Path(f).parent) for f in all_files if f}
- tid_hex = inputs.build_key(self.base_path)
+ tid_hex = self.build_key
work_dir = str(Path(self.out_dir or base_dir, f'{tid_hex}_build'))
- input_dir = base_dir
+ input_dir = folder.script_input if folder is not None else base_dir
if len(dirs) > 1:
# files from different folders: a stable folder of links per game, so the script sees one
# folder and its fingerprints match on the next build (#132)
@@ -1243,7 +1332,8 @@ class Model(QObject):
else:
entry = [str(Path(self.engine_path, 'scripts', 'build_ipa_from_nsp.py'))]
cwd = self.engine_path
- args = entry + [input_dir, '-k', self.keys_path, '--progress', 'lines']
+ # a game folder's files are not encrypted: no -k, the keys are not asked for
+ args = entry + [input_dir] + ([] if folder is not None else ['-k', self.keys_path]) + ['--progress', 'lines']
has_work_dir = self.supports_work_dir()
if has_work_dir:
args += ['--work-dir', work_dir]
@@ -1260,7 +1350,7 @@ class Model(QObject):
elif self.out_dir:
self.ipa_path = str(Path(self.out_dir, f'{tid_hex}.ipa'))
args += ['-o', self.ipa_path]
- self.effective_work_dir = work_dir if has_work_dir else str(Path(input_dir, f'{tid_hex}_build'))
+ self.effective_work_dir = work_dir if has_work_dir else str(Path(base_dir if folder is not None else input_dir, f'{tid_hex}_build'))
flag = self.override.take() # for this build only: the next one asks again
args = bf.arguments(args, flag)
diff --git a/frontend-qt/nspb_qt/ui.py b/frontend-qt/nspb_qt/ui.py
index 4b867397..e9de6db7 100644
--- a/frontend-qt/nspb_qt/ui.py
+++ b/frontend-qt/nspb_qt/ui.py
@@ -14,6 +14,7 @@ from PySide6.QtWidgets import (
QProgressBar, QPushButton, QScrollArea, QSizePolicy, QTextEdit, QVBoxLayout, QWidget,
)
+from . import inputs
from . import platform_util as pu
from .model import DepState, Model
from .style import CARD_EDGE, GREEN, MUTED, ORANGE, RED
@@ -472,6 +473,19 @@ class MainWindow(QMainWindow):
else self.m.t('data.folderHint'))
vals = {'base': self.m.base_path, 'update': self.m.update_path, 'keys': self.m.keys_path}
for key, (dot, val) in self.input_rows.items():
+ folder_text = self.m.input_row_text(key)
+ if folder_text is not None: # a game folder or a NUP: what it holds, and no keys needed
+ dot.setText('●')
+ dot.setStyleSheet(f'color: {GREEN};')
+ val.setText(folder_text)
+ val.setStyleSheet(f'color: {MUTED};')
+ continue
+ if key == 'base' and self.m.game_folder_problem: # refused: the reason, on the base row
+ dot.setText('✕')
+ dot.setStyleSheet(f'color: {RED};')
+ val.setText(self.m.game_folder_problem)
+ val.setStyleSheet(f'color: {ORANGE};')
+ continue
if key == 'dlc':
n = len(self.m.dlc_paths)
text = (Path(self.m.dlc_paths[0]).name + (f' +{n - 1}' if n > 1 else '')) if n else ''
@@ -754,6 +768,10 @@ class MainWindow(QMainWindow):
path, _ = QFileDialog.getOpenFileName(self, self.m.t('data.choose'))
if not path:
return
+ if key == 'base' and inputs.is_game_folder_candidate(path): # a .nup file
+ self.m.take_game_folder(path)
+ return
+ self.m.leave_game_folder() # picking packages leaves the game-folder mode
if key == 'base':
self.m.base_path = path
elif key == 'update':
diff --git a/frontend-qt/tests/test_game_folder.py b/frontend-qt/tests/test_game_folder.py
new file mode 100644
index 00000000..f5509047
--- /dev/null
+++ b/frontend-qt/tests/test_game_folder.py
@@ -0,0 +1,387 @@
+"""A Switch 2 game as a folder of its files or one NUP file builds with no prod.keys (LNPANDY/NX2Apple#512, #445).
+The same cases as the Mac launcher's GameFolder tests. Synthetic folders and NUP bytes, no game data.
+
+The model tests need PySide6 and are skipped without it."""
+from __future__ import annotations
+
+import os
+import struct
+import sys
+import tempfile
+import unittest
+from pathlib import Path
+from unittest import mock
+
+ROOT = Path(__file__).resolve().parents[2]
+sys.path.insert(0, str(ROOT / 'frontend-qt'))
+os.environ.setdefault('QT_QPA_PLATFORM', 'offscreen')
+
+from nspb_qt import inputs # noqa: E402
+
+try:
+ from nspb_qt import model as model_mod # noqa: E402
+ from nspb_qt.i18n import Lang # noqa: E402
+except ImportError: # no PySide6
+ model_mod = None
+
+TID = 0x0400000000A00000
+
+
+def npdm(program_id: int) -> bytes:
+ """A minimal main.npdm: META header, the ACI0 section at 0x80 with the program ID at +0x10."""
+ d = bytearray(0x100)
+ d[:4] = b'META'
+ struct.pack_into('<II', d, 0x70, 0x80, 0x40)
+ d[0x80:0x84] = b'ACI0'
+ struct.pack_into('<Q', d, 0x90, program_id)
+ return bytes(d)
+
+
+def nup(packages: list[tuple[int, int, int]], size_delta: int = 0, magic: bytes = b'NUP\x01') -> bytes:
+ """A NUP: header, then the table of contents at 0x80 with one 0x40 entry per (title ID, version, kind)."""
+ toc = 0x80
+ total = toc + 0x30 + 0x40 * len(packages)
+ d = bytearray(total)
+ d[:4] = magic
+ struct.pack_into('<Q', d, 0x08, toc)
+ struct.pack_into('<Q', d, 0x40, total + size_delta)
+ struct.pack_into('<I', d, 0x48, len(packages))
+ d[toc:toc + 4] = b'TOC\x01'
+ for i, (tid, version, kind) in enumerate(packages):
+ o = toc + 0x30 + i * 0x40
+ struct.pack_into('<Q', d, o, tid)
+ struct.pack_into('<I', d, o + 20, version)
+ d[o + 24] = kind
+ return bytes(d)
+
+
+class FolderTests(unittest.TestCase):
+ def setUp(self):
+ self._tmp = tempfile.TemporaryDirectory()
+ self.dir = Path(self._tmp.name) / 'game'
+ self.dir.mkdir()
+
+ def tearDown(self):
+ self._tmp.cleanup()
+
+ def make(self, rel: str, data: bytes = b'x') -> Path:
+ p = self.dir / rel
+ p.parent.mkdir(parents=True, exist_ok=True)
+ p.write_bytes(data)
+ return p
+
+ def game(self, tid: int = TID):
+ self.make('base/exefs/main.npdm', npdm(tid))
+ (self.dir / 'base/romfs').mkdir(parents=True, exist_ok=True)
+
+ def scan(self):
+ return inputs.scan_game_folder(str(self.dir))
+
+ def problem(self, kind: str, args: tuple = ()):
+ r = self.scan()
+ self.assertEqual(r, inputs.GameFolderProblem(kind, args))
+
+ # ---- detection
+
+ def test_candidates(self):
+ self.assertFalse(inputs.is_game_folder_candidate(str(self.dir)))
+ self.make('exefs/main.npdm')
+ self.assertTrue(inputs.is_game_folder_candidate(str(self.dir))) # one level too high
+ (self.dir / 'base').mkdir()
+ self.assertFalse(inputs.is_game_folder_candidate(str(self.dir)))
+
+ def test_candidate_base_and_nup(self):
+ self.game()
+ self.assertTrue(inputs.is_game_folder_candidate(str(self.dir)))
+ other = self.dir.parent / 'other'
+ other.mkdir()
+ (other / 'g.NUP').write_bytes(b'')
+ self.assertTrue(inputs.is_game_folder_candidate(str(other)))
+ self.assertTrue(inputs.is_game_folder_candidate(str(other / 'g.NUP')))
+ (other / '._g.nup').write_bytes(b'')
+ self.assertEqual(inputs.nup_files(str(other)), ['g.NUP'])
+
+ # ---- a folder of files
+
+ def test_contents(self):
+ self.game()
+ (self.dir / 'updates/458752/romfs').mkdir(parents=True)
+ (self.dir / 'updates/65536/romfs').mkdir(parents=True)
+ (self.dir / 'updates/notes').mkdir(parents=True)
+ (self.dir / f'dlc/{TID + 0x1001:016x}/0/romfs').mkdir(parents=True)
+ (self.dir / f'dlc/{TID + 0x1002:016X}/romfs').mkdir(parents=True)
+ r = self.scan()
+ self.assertIsInstance(r, inputs.GameFolderContents)
+ self.assertEqual(r.title_id, TID)
+ self.assertEqual(r.title_id_hex, '0400000000A00000')
+ self.assertEqual([v for v, _ in r.updates], [65536, 458752])
+ self.assertEqual(r.newest_update[0], 458752)
+ self.assertEqual([t for t, _ in r.dlc], [TID + 0x1001, TID + 0x1002])
+ self.assertIsNone(r.nup)
+ self.assertEqual(r.script_input, str(self.dir))
+ self.assertEqual(r.base_path, str(self.dir / 'base'))
+
+ def test_base_without_romfs_but_update_has_one(self):
+ self.make('base/exefs/main.npdm', npdm(TID))
+ self.problem('missing', ('base/romfs',))
+ (self.dir / 'updates/1/romfs').mkdir(parents=True)
+ self.assertIsInstance(self.scan(), inputs.GameFolderContents)
+
+ def test_problems(self):
+ self.problem('missing', ('base/exefs/main.npdm',))
+ self.make('exefs/main.npdm')
+ self.problem('noBaseFolder')
+
+ def test_unreadable_npdm(self):
+ self.make('base/exefs/main.npdm', b'not an npdm')
+ (self.dir / 'base/romfs').mkdir()
+ self.problem('unreadableNPDM')
+ self.make('base/exefs/main.npdm', npdm(TID)[:0x84]) # ACI0 cut short
+ self.problem('unreadableNPDM')
+
+ def test_not_base_title(self):
+ self.game(TID + 0x800)
+ self.problem('notBaseTitle', ('0400000000A00800',))
+
+ def test_package_beside(self):
+ self.game()
+ self.make('game.NSZ')
+ self.problem('packageBeside', ('game.NSZ',))
+ os.remove(self.dir / 'game.NSZ')
+ self.make('._x.nsp')
+ self.assertIsInstance(self.scan(), inputs.GameFolderContents)
+
+ def test_dlc_problems(self):
+ self.game()
+ (self.dir / 'dlc/bonus/romfs').mkdir(parents=True)
+ self.problem('dlcName', ('bonus',))
+ os.rename(self.dir / 'dlc/bonus', self.dir / f'dlc/{TID + 0x5000:016X}')
+ self.problem('notDLC', (f'{TID + 0x5000:016X}',))
+ os.rename(self.dir / f'dlc/{TID + 0x5000:016X}', self.dir / f'dlc/{TID + 0x1001:016X}')
+ self.assertIsInstance(self.scan(), inputs.GameFolderContents)
+ (self.dir / f'dlc/{TID + 0x1001:016X}/romfs').rmdir()
+ self.problem('dlcRomFS', (f'{TID + 0x1001:016X}', 0))
+ (self.dir / f'dlc/{TID + 0x1001:016X}/1/romfs').mkdir(parents=True)
+ (self.dir / f'dlc/{TID + 0x1001:016X}/2/romfs').mkdir(parents=True)
+ self.problem('dlcRomFS', (f'{TID + 0x1001:016X}', 2))
+
+ def test_problem_keys_exist_in_the_shared_strings(self):
+ from nspb_qt import l10n
+ for kind in ('missing', 'noBaseFolder', 'unreadableNPDM', 'notBaseTitle', 'packageBeside', 'dlcName', 'notDLC',
+ 'dlcRomFS', 'notNUP', 'nupPartial', 'severalNUPs'):
+ self.assertIn(inputs.GameFolderProblem(kind).l10n_key, l10n.CATALOGS['en'])
+
+ def test_program_id(self):
+ self.assertEqual(inputs.program_id(npdm(TID)), TID)
+ self.assertIsNone(inputs.program_id(b'META'))
+ self.assertIsNone(inputs.program_id(b'XXXX' + npdm(TID)[4:]))
+
+ # ---- a NUP
+
+ def test_nup_base_updates_dlc(self):
+ p = self.make('Game.nup', nup([(TID, 0, 0), (TID + 0x800, 65536, 1), (TID + 0x800, 458752, 1),
+ (TID + 0x1002, 0, 2), (TID + 0x1001, 0, 2)]))
+ for r in (inputs.scan_game_folder(str(p)), self.scan()): # the file, and the folder that holds it
+ self.assertIsInstance(r, inputs.GameFolderContents)
+ self.assertEqual(r.title_id, TID)
+ self.assertEqual(r.nup, str(p))
+ self.assertEqual(r.folder, str(self.dir))
+ self.assertEqual([v for v, _ in r.updates], [65536, 458752])
+ self.assertEqual([t for t, _ in r.dlc], [TID + 0x1001, TID + 0x1002])
+ self.assertEqual(r.script_input, str(p))
+ self.assertEqual(r.base_path, str(p))
+
+ def test_nup_title_id_from_an_update_or_none(self):
+ p = self.make('a.nup', nup([(TID + 0x800, 1, 1)]))
+ self.assertEqual(inputs.read_nup(str(p)).title_id, TID)
+ p = self.make('a.nup', nup([(TID, 0, 0), (TID + 0x800, 1, 1)]))
+ self.assertEqual(inputs.read_nup(str(p)).title_id, TID)
+ p = self.make('a.nup', nup([(TID + 0x1001, 0, 2)]))
+ r = inputs.read_nup(str(p))
+ self.assertEqual(r.title_id, 0)
+ self.assertFalse(r.has_title_id)
+
+ def test_nup_problems(self):
+ self.make('a.nup', nup([(TID, 0, 0)], magic=b'NUP\x02'))
+ self.problem('notNUP', ('a.nup',))
+ self.make('a.nup', nup([(TID, 0, 0)], size_delta=5))
+ self.problem('nupPartial', ('a.nup',))
+ self.make('a.nup', b'short')
+ self.problem('notNUP', ('a.nup',))
+ self.make('a.nup', nup([(TID, 0, 0)])[:-8])
+ self.assertIsInstance(self.scan(), inputs.GameFolderProblem) # cut table: partial
+ self.make('a.nup', nup([(TID, 0, 0)]))
+ self.make('b.nup', nup([(TID, 0, 0)]))
+ self.problem('severalNUPs', (2,))
+
+ def test_nup_beside_packages_is_refused(self):
+ self.make('a.nup', nup([(TID, 0, 0)]))
+ self.make('g.xci')
+ self.problem('packageBeside', ('g.xci',))
+
+
[email protected](model_mod is None, 'PySide6 is not installed')
+class ModelTests(unittest.TestCase):
+ def setUp(self):
+ self._tmp = tempfile.TemporaryDirectory()
+ root = Path(self._tmp.name)
+ self.eng = root / 'engine' # an engine tree: the marker file makes it the repo itself
+ (self.eng / 'dm/tools/nx_extract').mkdir(parents=True)
+ (self.eng / 'dm/tools/nx_extract/Program.cs').write_text('')
+ (self.eng / 'scripts').mkdir()
+ for n in ('pack_dump.py', 'pack_nup.py'):
+ (self.eng / 'scripts' / n).write_text('')
+ (self.eng / 'scripts/build_ipa_from_nsp.py').write_text("p.add_argument('--work-dir')\n")
+ (self.eng / f'dm/games/{TID:016X}').mkdir(parents=True)
+ (self.eng / f'dm/games/{TID:016X}/game.tsv').write_text('name\tGame\n')
+ self.game = root / 'game'
+ (self.game / 'base/exefs').mkdir(parents=True)
+ (self.game / 'base/romfs').mkdir()
+ (self.game / 'base/exefs/main.npdm').write_bytes(npdm(TID))
+ self.m = model_mod.Model()
+ self.m.lang = Lang('en')
+ self.m.repo_path = str(self.eng)
+ self.m.python_path = '/usr/bin/python3'
+
+ def tearDown(self):
+ self._tmp.cleanup()
+
+ def ready(self):
+ """Pass the dependency gate: this is about the inputs."""
+ p = mock.patch.object(model_mod.Model, 'all_deps_ok', new_callable=mock.PropertyMock, return_value=True)
+ p.start()
+ self.addCleanup(p.stop)
+
+ def test_folder_fills_rows_and_needs_no_keys(self):
+ self.ready()
+ (self.game / 'updates/458752/romfs').mkdir(parents=True)
+ (self.game / f'dlc/{TID + 0x1001:016X}/0/romfs').mkdir(parents=True)
+ self.m.scan_game_dir(str(self.game))
+ self.assertEqual(self.m.keys_path, '')
+ self.assertTrue(self.m.can_build)
+ self.assertEqual(self.m.input_row_text('base'), 'Game folder, title ID 0400000000A00000 from main.npdm')
+ self.assertEqual(self.m.input_row_text('update'), 'Update version 458752')
+ self.assertEqual(self.m.input_row_text('dlc'), 'Add-on content folders: 1')
+ self.assertIn('Not needed', self.m.input_row_text('keys'))
+
+ def test_several_updates_text_uses_both_numbers(self):
+ (self.game / 'updates/1/romfs').mkdir(parents=True)
+ (self.game / 'updates/2/romfs').mkdir(parents=True)
+ self.m.scan_game_dir(str(self.game))
+ self.assertEqual(self.m.input_row_text('update'), 'Update version 2, the newest of 2')
+
+ def test_nup_rows(self):
+ self.ready()
+ p = self.game.parent / 'g.nup'
+ p.write_bytes(nup([(TID, 0, 0)]))
+ self.m.scan_game_dir(str(p))
+ self.assertTrue(self.m.can_build)
+ self.assertEqual(self.m.base_path, str(p))
+ self.assertEqual(self.m.input_row_text('base'), f'NUP file, title ID {TID:016X}')
+ p.write_bytes(nup([(TID + 0x1001, 0, 2)]))
+ self.m.scan_game_dir(str(p))
+ self.assertEqual(self.m.input_row_text('base'), 'NUP file. The build reads its title ID.')
+
+ def test_refused_with_the_reason(self):
+ self.ready()
+ (self.game / 'base/romfs').rmdir()
+ self.m.scan_game_dir(str(self.game))
+ self.assertFalse(self.m.can_build)
+ self.assertEqual(self.m.game_folder_problem, 'This game folder has no base/romfs.')
+ self.assertIsNone(self.m.input_row_text('base'))
+
+ def test_refused_without_a_profile_or_with_an_old_engine(self):
+ (self.eng / f'dm/games/{TID:016X}/game.tsv').unlink()
+ self.m.scan_game_dir(str(self.game))
+ self.assertIn(f'The engine has no profile for {TID:016X}.', self.m.game_folder_problem)
+ self.assertIsNone(self.m.game_folder)
+ (self.eng / 'scripts/pack_dump.py').unlink()
+ self.m.scan_game_dir(str(self.game))
+ self.assertEqual(self.m.game_folder_problem, 'This engine does not build game folders. Update the engine first.')
+ p = self.game.parent / 'g.nup'
+ p.write_bytes(nup([(TID, 0, 0)]))
+ (self.eng / 'scripts/pack_nup.py').unlink()
+ self.m.scan_game_dir(str(p))
+ self.assertEqual(self.m.game_folder_problem, 'This engine does not build NUP files. Update the engine first.')
+
+ def test_dlc_problem_text_has_both_numbers(self):
+ (self.game / f'dlc/{TID + 0x1001:016X}/romfs').mkdir(parents=True)
+ (self.game / f'dlc/{TID + 0x1001:016X}/romfs').rmdir()
+ (self.game / f'dlc/{TID + 0x1001:016X}').mkdir(exist_ok=True)
+ self.m.scan_game_dir(str(self.game))
+ self.assertEqual(self.m.game_folder_problem, f'dlc/{TID + 0x1001:016X} needs one romfs folder and has 0.')
+
+ def test_picking_packages_leaves_the_mode(self):
+ self.m.scan_game_dir(str(self.game))
+ self.assertIsNotNone(self.m.game_folder)
+ self.m.leave_game_folder()
+ self.assertIsNone(self.m.game_folder)
+ self.assertEqual((self.m.base_path, self.m.update_path, self.m.dlc_paths), ('', '', []))
+ self.assertIsNone(self.m.input_row_text('keys'))
+ self.assertFalse(self.m.can_build) # packages need the keys again
+
+ def run_build(self, out_dir: str = '') -> tuple[list[str], 'model_mod.Model']:
+ self.m.out_dir = out_dir
+ seen: list[list[str]] = []
+
+ class Fake:
+ returncode = 1
+ stdout: list[str] = []
+
+ def __init__(self, cmd, **kw):
+ seen.append(cmd)
+
+ def wait(self):
+ pass
+
+ with mock.patch.object(model_mod.subprocess, 'Popen', Fake), \
+ mock.patch.object(model_mod.pu, 'IS_WIN', False):
+ self.m.start_build()
+ self.m._thread.join(10)
+ builds = [c for c in seen if '--progress' in c] # other processes may start too (the dependency checks)
+ self.assertTrue(builds, 'the script was not started')
+ return builds[0], self.m
+
+ def test_build_arguments_for_a_folder(self):
+ self.ready()
+ self.m.scan_game_dir(str(self.game))
+ args, m = self.run_build()
+ self.assertNotIn('-k', args)
+ self.assertEqual(args[args.index(str(self.eng / 'scripts/build_ipa_from_nsp.py')) + 1], str(self.game))
+ self.assertEqual(args[args.index('--work-dir') + 1], str(self.game / f'{TID:016X}_build'))
+ self.assertEqual(m.effective_work_dir, str(self.game / f'{TID:016X}_build'))
+
+ def test_build_arguments_for_a_nup_with_an_output_folder(self):
+ self.ready()
+ p = self.game.parent / 'g.nup'
+ p.write_bytes(nup([(TID, 0, 0)]))
+ self.m.scan_game_dir(str(p))
+ out = str(self.game.parent / 'out')
+ self.m.target = 'mac-app'
+ args, _ = self.run_build(out)
+ self.assertNotIn('-k', args)
+ self.assertEqual(args[args.index(str(self.eng / 'scripts/build_ipa_from_nsp.py')) + 1], str(p))
+ self.assertEqual(args[args.index('--work-dir') + 1], str(Path(out, f'{TID:016X}_build')))
+ self.assertEqual(args[args.index('-o') + 1], str(Path(out, f'{TID:016X}.app')))
+
+ def test_a_nup_without_a_title_id_names_the_build_after_the_file(self):
+ self.ready()
+ p = self.game.parent / 'g.nup'
+ p.write_bytes(nup([(TID + 0x1001, 0, 2)]))
+ self.m.scan_game_dir(str(p))
+ self.assertEqual(self.m.build_key, inputs.build_key(str(p)))
+
+ def test_packages_still_pass_the_keys(self):
+ self.ready()
+ pk = self.game.parent / 'pk'
+ pk.mkdir()
+ (pk / '0100AAAA0000A000.nsp').write_bytes(b'x')
+ (pk / 'prod.keys').write_bytes(b'x')
+ self.m.scan_game_dir(str(pk))
+ self.assertIsNone(self.m.game_folder)
+ args, _ = self.run_build()
+ self.assertEqual(args[args.index('-k') + 1], str(pk / 'prod.keys'))
+
+
+if __name__ == '__main__':
+ unittest.main()