Play your own Switch games on iPhone/iPad — one-click macOS app, no terminal. | 把 Switch 游戏装进 iPhone:图形界面一键构建,不用命令行。Bring your own game.
Swift apple-siliconcustom-formathomebrewiosipaipadipadosiphonemetalnative-portnintendo-switchnxnativeromfsswitch-games
frontend-qt: a PySide6 front end, so Windows gets a native window too
LNPANDYb7fcb47800f5
diff --git a/frontend-qt/README.md b/frontend-qt/README.mdnew file mode 100644index 00000000..d29c7d6a--- /dev/null+++ b/frontend-qt/README.md@@ -0,0 +1,65 @@+# NS Port Builder — Qt front end (Windows and macOS)++The SwiftUI app in `../frontend/` is the macOS-native one. This is the **cross-platform**+counterpart: same job, same strings, built with PySide6 so Windows users get a native window.++## Why a second front end++The build pipeline (`scripts/build_ipa_from_nsp.py`) is Python and runs on both systems, but+the SwiftUI app cannot: it needs macOS. Rather than maintain two unrelated GUIs, this one is+written once and runs everywhere Python and Qt do.++| | SwiftUI (`frontend/`) | Qt (this) |+|---|---|---|+| Platforms | macOS 13+ | Windows 10+, macOS 11+ |+| Language | Swift | Python 3.9+ |+| Strings | `Localization.swift` | generated from that same file |+| Build logic | runs the Python scripts | runs the same scripts |++The strings are **generated** from the SwiftUI table (`gen_localization.py`), so the two front+ends cannot drift apart: edit `Localization.swift`, run the generator.++## Run it++```bash+python3 -m venv .venv+.venv/bin/pip install PySide6 # Windows: .venv\Scripts\pip install PySide6+.venv/bin/python -m nspb_qt # Windows: .venv\Scripts\python -m nspb_qt+```++From this folder. It looks for the repository checkout next to itself, in `~/NX2Apple`, or+wherever `NSPB_REPO` points, and the repository group lets you pick it by hand.++## What works today++- Dependency detection per platform: Python + packages, .NET SDK, and either **Xcode + iOS SDK ++ Metal toolchain** (macOS) or **iPhoneOS SDK + Apple's Metal Developer Tools** (Windows), plus+ xcodegen / zstd / spirv-cross. Each row has an install button when a command can fix it.+- Pick a game folder (or its four inputs separately); base / update / DLC / `prod.keys` are+ recognised from the dump names.+- Build: runs the same script the SwiftUI app runs, streams its stage lines and log, then packs+ the RomFS archive and reports where the IPA and archive landed.+- `--work-dir` is passed only when the checkout's script declares it (an upstream checkout has+ no such option — issue #5).+- Bilingual: Chinese on Chinese devices, English elsewhere; the header button switches.++## What is not there yet++- **The Windows build path is untested.** The platform layer is written (tool discovery, the+ SDK/Metal checks, `CREATE_NO_WINDOW` for child processes) but no Windows machine has run it.+ The cross-compile steps themselves live in the WebUI-style toolchain, not here yet.+- No self-update, no repository download/update buttons (the SwiftUI app has both).+- No per-stage progress bar, no cancel-with-cleanup (cancel terminates the child).++## Layout++```+nspb_qt/+ __main__.py entry point+ model.py state, dependency detection, build runner (Qt signals, no widgets)+ ui.py the window+ platform_util.py per-OS paths, tool discovery, child environment+ i18n.py language choice+ localization.py generated from ../frontend/Sources/NSPortBuilder/Localization.swift+gen_localization.py regenerates localization.py+```diff --git a/frontend-qt/gen_localization.py b/frontend-qt/gen_localization.pynew file mode 100644index 00000000..0323f48b--- /dev/null+++ b/frontend-qt/gen_localization.py@@ -0,0 +1,66 @@+"""Generate localization.py from the SwiftUI app's Localization.swift.++The two front ends show the same strings, so the table has one source: the Swift file. Running+this after editing it keeps the Qt app in step instead of letting the two drift.+ python3 frontend-qt/gen_localization.py+"""+from __future__ import annotations++import re+from pathlib import Path++HERE = Path(__file__).resolve().parent+SWIFT = HERE.parent / 'frontend' / 'Sources' / 'NSPortBuilder' / 'Localization.swift'+OUT = HERE / 'nspb_qt' / 'localization.py'++PAIR = re.compile(r'"([^"]+)":\s*\(\s*"((?:[^"\\]|\\.)*)"\s*,\s*"((?:[^"\\]|\\.)*)"\s*\)', re.S)+++def main() -> None:+ text = SWIFT.read_text(encoding='utf-8')+ rows = PAIR.findall(text)+ if not rows:+ raise SystemExit(f'no strings found in {SWIFT}')+ lines = [+ '"""Localised strings, generated from the SwiftUI app\'s Localization.swift.',+ '',+ 'Do not edit by hand: run frontend-qt/gen_localization.py after changing the Swift table,',+ 'so both front ends say the same thing."""',+ 'from __future__ import annotations',+ '',+ 'from .i18n import Lang',+ '',+ '# key: (Chinese, English)',+ 'TABLE: dict[str, tuple[str, str]] = {',+ ]+ for key, zh, en in rows:+ zh = zh.replace('\\"', '"').replace('\\n', '\\n')+ en = en.replace('\\"', '"').replace('\\n', '\\n')+ lines.append(f' {key!r}: ({zh!r}, {en!r}),')+ lines += [+ '}',+ '',+ '',+ 'def t(key: str, lang: Lang, *args: object) -> str:',+ ' """The string for `key` in `lang`, with %@-style arguments filled in.',+ '',+ ' The Swift table uses %@ as its placeholder (String(format:)); the Qt side uses',+ ' Python\'s %s, so the placeholder is translated here rather than in every call site.',+ ' """',+ ' zh, en = TABLE.get(key, (key, key))',+ ' s = zh if lang is Lang.ZH else en',+ ' if not args:',+ ' return s',+ ' py = s.replace("%@", "%s").replace("%d", "%d")',+ ' try:',+ ' return py % args',+ ' except (TypeError, ValueError):',+ ' return s',+ '',+ ]+ OUT.write_text('\n'.join(lines), encoding='utf-8')+ print(f'{len(rows)} strings -> {OUT.relative_to(HERE)}')+++if __name__ == '__main__':+ main()diff --git a/frontend-qt/nspb_qt/__init__.py b/frontend-qt/nspb_qt/__init__.pynew file mode 100644index 00000000..e333ad9a--- /dev/null+++ b/frontend-qt/nspb_qt/__init__.py@@ -0,0 +1,12 @@+"""NS Port Builder — Qt front end (Windows and macOS from one code base).++The SwiftUI app in ../frontend/ is the macOS-native one. This is the cross-platform+counterpart: same job (drive scripts/build_ipa_from_nsp.py and pack the RomFS archive),+same localisation strings, built with PySide6 so Windows users get a native window too.++Layout mirrors the SwiftUI app so the two stay recognisable:+ model.py state, dependency detection, build runner (Qt signals, no UI)+ ui.py the window+ localization.py the zh/en table (shared keys with the SwiftUI app)+ platform_*.py per-OS paths and tool discovery+"""diff --git a/frontend-qt/nspb_qt/__main__.py b/frontend-qt/nspb_qt/__main__.pynew file mode 100644index 00000000..897d0e14--- /dev/null+++ b/frontend-qt/nspb_qt/__main__.py@@ -0,0 +1,23 @@+"""Entry point: python3 -m nspb_qt (or run main.py)."""+from __future__ import annotations++import sys++from PySide6.QtWidgets import QApplication++from .model import Model+from .ui import MainWindow+++def main() -> int:+ app = QApplication(sys.argv)+ app.setApplicationName('NS Port Builder')+ app.setApplicationDisplayName('NS Port Builder')+ model = Model()+ win = MainWindow(model)+ win.show()+ return app.exec()+++if __name__ == '__main__':+ raise SystemExit(main())diff --git a/frontend-qt/nspb_qt/i18n.py b/frontend-qt/nspb_qt/i18n.pynew file mode 100644index 00000000..e9879284--- /dev/null+++ b/frontend-qt/nspb_qt/i18n.py@@ -0,0 +1,43 @@+"""Language choice: Chinese on Chinese devices, English everywhere else."""+from __future__ import annotations++import locale+import os+import sys+from enum import Enum+++class Lang(Enum):+ ZH = 'zh'+ EN = 'en'++ @property+ def other(self) -> 'Lang':+ return Lang.EN if self is Lang.ZH else Lang.ZH++ @property+ def toggle_label(self) -> str:+ return 'EN' if self is Lang.ZH else '中文'++ @staticmethod+ def initial() -> 'Lang':+ """Saved choice, else the device language: any Chinese variant is Chinese, everything+ else is English (the same rule the SwiftUI app uses)."""+ saved = os.environ.get('NSPB_LANG', '')+ if saved in ('zh', 'en'):+ return Lang(saved)+ try:+ tag = locale.getlocale()[0] or ''+ except (ValueError, TypeError):+ tag = ''+ tag = tag or os.environ.get('LANG', '') or os.environ.get('LC_ALL', '')+ if not tag and sys.platform.startswith('win'):+ import ctypes+ try:+ buf = ctypes.create_unicode_buffer(85)+ ctypes.windll.kernel32.GetUserDefaultUILanguage() # noqa: F841 (kept for clarity)+ ctypes.windll.kernel32.GetLocaleInfoW(0x0800, 0x00000002, buf, 85) # LOCALE_SISO639LANGNAME+ tag = buf.value+ except Exception:+ tag = ''+ return Lang.ZH if tag.lower().startswith('zh') else Lang.ENdiff --git a/frontend-qt/nspb_qt/localization.py b/frontend-qt/nspb_qt/localization.pynew file mode 100644index 00000000..b87fcf09--- /dev/null+++ b/frontend-qt/nspb_qt/localization.py@@ -0,0 +1,161 @@+"""Localised strings, generated from the SwiftUI app's Localization.swift.++Do not edit by hand: run frontend-qt/gen_localization.py after changing the Swift table,+so both front ends say the same thing."""+from __future__ import annotations++from .i18n import Lang++# key: (Chinese, English)+TABLE: dict[str, tuple[str, str]] = {+ 'app.subtitle': ('Switch 游戏 → iPhone IPA · 归档分片 · 大内存', 'Switch games → iPhone IPA · archive shards · large memory'),+ 'repo.title': ('项目仓库', 'Project repository'),+ 'repo.note': ('App 调用这里的构建脚本', 'the app runs the build scripts from here'),+ 'repo.choose': ('选择仓库…', 'Choose repository…'),+ 'repo.notFound': ('未找到本项目——下载,或点右侧选择 clone 的位置', 'Project not found — download it, or pick your clone with the button'),+ 'repo.notRepo': ('不是本项目的仓库:%@', "Not this project's repository: %@"),+ 'repo.pickMessage': ('选择本项目(含 dm/tools/nx_extract/Program.cs)的文件夹', "Pick this project's folder (the one holding dm/tools/nx_extract/Program.cs)"),+ 'repo.download': ('下载仓库', 'Download repository'),+ 'repo.downloading': ('正在下载到 ~/NX2Apple…(进度见下方日志,约一分钟)', 'Downloading to ~/NX2Apple… (progress in the log below, about a minute)'),+ 'repo.downloadDone': ('仓库已下载到 %@', 'Repository downloaded to %@'),+ 'repo.downloadFail': ('下载失败——网络不顺?用下面的手动方法', 'Download failed — flaky network? Use the manual route below'),+ 'repo.manualHint': ('网络不顺也可以手动:打开', 'Flaky network? Do it by hand: open'),+ 'repo.manualHint2': ('→ 点绿色 Code 按钮 → Download ZIP,解压后点「选择仓库…」选中解压出的文件夹', '→ the green Code button → Download ZIP, unzip, then pick the unzipped folder with Choose repository…'),+ 'repo.noGit': ('这是 ZIP 下载的副本(无 git 历史),构建不受影响;点「接入 git」转为可更新', 'This is a ZIP copy (no git history); builds work fine — Make updatable connects it to git'),+ 'repo.adopt': ('接入 git(可更新)', 'Make updatable (git)'),+ 'repo.adopting': ('正在接入 git…', 'Connecting git…'),+ 'repo.adopted': ('已接入 git,可以检查更新了', 'Connected — updates work now'),+ 'repo.adoptFail': ('接入失败——详情见日志', 'Connect failed — see the log'),+ 'app.checking': ('正在检查 App 更新…', 'Checking for a new app version…'),+ 'app.upToDate': ('App 已是最新版本', 'The app is up to date'),+ 'app.found': ('App 有新版本 %@,点右上角按钮更新', 'A new version %@ is out — update from the top-right button'),+ 'app.updateBtn': ('更新到 %@', 'Update to %@'),+ 'app.downloading': ('正在下载新版本…', 'Downloading the new version…'),+ 'app.installing': ('正在安装…(旧版本会进废纸篓)', 'Installing… (the old version goes to the Trash)'),+ 'app.relaunching': ('已更新到 %@,正在重启 App…', 'Updated to %@ — restarting…'),+ 'app.installFail': ('安装失败:%@——新版本已下载,可手动替换', 'Install failed: %@ — the new version was downloaded; replace by hand'),+ 'app.netFail': ('网络失败(GitHub 不通?稍后再试)', 'Network failed (GitHub unreachable? try again later)'),+ 'repo.destBusy': ('%@ 已存在且不是本项目——换个位置,或点「选择仓库…」', '%@ already exists and is not this project — use another place, or Choose repository…'),+ 'repo.firstHint': ('第一次用?点「下载仓库」自动获取项目(约一分钟,需要网络)', 'First time here? Download repository fetches the project for you (about a minute, needs network)'),+ 'repo.check': ('检查更新', 'Check for updates'),+ 'repo.checking': ('正在检查更新…', 'Checking for updates…'),+ 'repo.upToDate': ('已是最新版本', 'Up to date'),+ 'repo.behind': ('有更新:%d 个新提交,点「拉取更新」', 'Updates available: %d new commits — pull them'),+ 'repo.pull': ('拉取更新', 'Pull updates'),+ 'repo.pulling': ('正在更新…(构建不受影响,之前的构建文件不在仓库里)', 'Updating… (your builds are safe — their files live outside the repository)'),+ 'repo.pulled': ('已更新到最新', 'Updated to the latest'),+ 'repo.pullFail': ('更新失败——详情见日志(本地文件被改过?)', 'Update failed — see the log (local changes?)'),+ 'repo.gitMissing': ('没找到 git:在终端运行 xcode-select --install 装一下命令行工具', 'git not found: run xcode-select --install in Terminal to get the Command Line Tools'),+ 'repo.netFail': ('检查更新失败(网络不通?)', 'Could not check for updates (offline?)'),+ 'data.title': ('游戏数据', 'Game data'),+ 'data.note': ('四项可以分开选', 'four inputs, picked separately'),+ 'data.pickFolder': ('选整个文件夹…', 'Pick a folder…'),+ 'data.folderHint': ('同一个文件夹里都有时,用右上角一次选好', 'When everything is in one folder, the button fills all four at once'),+ 'data.base': ('游戏本体', 'Base game'),+ 'data.update': ('更新包', 'Update'),+ 'data.dlc': ('追加内容 DLC', 'DLC (add-on)'),+ 'data.keys': ('主机密钥 prod.keys', 'prod.keys'),+ 'data.notSelected': ('未选择', 'Not selected'),+ 'data.notSelectedOptional': ('未选择(可选)', 'Not selected (optional)'),+ 'data.files': ('%d 个文件:', '%d files: '),+ 'data.clear': ('清除', 'Clear'),+ 'data.choose': ('选择…', 'Choose…'),+ 'data.change': ('更换…', 'Change…'),+ 'data.noBase': ('这个文件夹里没有本体 NSP([xxxx…000])', 'No base game NSP in this folder ([xxxx…000])'),+ 'data.noNsp': ('这个文件夹里没有 NSP/XCI', 'No NSP/XCI in this folder'),+ 'build.start': ('开始构建', 'Start build'),+ 'build.cancel': ('取消构建', 'Cancel build'),+ 'build.outDir': ('输出目录…', 'Output folder…'),+ 'msg.ipaAt': ('IPA:%@', 'IPA: %@'),+ 'msg.archiveAt': ('归档:%@', 'Archive: %@'),+ 'repo.ok': ('仓库可用', 'repository ready'),+ 'dep.iossdk': ('iPhoneOS SDK', 'iPhoneOS SDK'),+ 'dep.iossdk.hint': ('Windows 上需要 iPhoneOS SDK(用于交叉编译)', 'Windows needs an iPhoneOS SDK for the cross build'),+ 'dep.metal.missing': ('未找到 metal.exe(Apple Metal Developer Tools for Windows)', 'metal.exe not found (Apple Metal Developer Tools for Windows)'),+ 'dep.title': ('设备依赖', 'Device dependencies'),+ 'dep.checking': ('检测中…', 'Checking…'),+ 'dep.allReady': ('全部就绪', 'All ready'),+ 'dep.missing': ('缺 %d 项', '%d missing'),+ 'dep.recheck': ('重新检测', 'Check again'),+ 'dep.install': ('安装', 'Install'),+ 'dep.installing': ('安装中…', 'Installing…'),+ 'dep.openAppStore': ('打开 App Store', 'Open App Store'),+ 'dep.xcode': ('Xcode + iOS SDK', 'Xcode + iOS SDK'),+ 'dep.xcode.hint': ('App Store 安装,约 12 GB', 'from the App Store, about 12 GB'),+ 'dep.xcode.noSDK': ('Xcode 已装,但 iOS SDK 未下载(Xcode 15 起 iOS 平台是单独下载的)', 'Xcode is installed but the iOS SDK is not downloaded (a separate download since Xcode 15)'),+ 'dep.metal': ('Metal Toolchain', 'Metal Toolchain'),+ 'dep.metal.hint': ('xcodebuild -downloadComponent MetalToolchain(约 840 MB)', 'xcodebuild -downloadComponent MetalToolchain (about 840 MB)'),+ 'dep.brew': ('Homebrew', 'Homebrew'),+ 'dep.brew.hint': ('brew.sh(后续包的前置)', 'brew.sh (needed by the packages below)'),+ 'dep.xcodegen': ('brew: xcodegen', 'brew: xcodegen'),+ 'dep.xcodegen.hint': ('Xcode 工程生成', 'generates the Xcode project'),+ 'dep.zstd': ('brew: zstd', 'brew: zstd'),+ 'dep.zstd.hint': ('解压', 'decompression'),+ 'dep.spirv': ('brew: spirv-cross', 'brew: spirv-cross'),+ 'dep.spirv.hint': ('shader 转换', 'shader translation'),+ 'dep.dotnet': ('.NET SDK 10', '.NET SDK 10'),+ 'dep.dotnet.hint': ('dotnet-install.sh 装到 ~/.dotnet', 'dotnet-install.sh into ~/.dotnet'),+ 'dep.dotnet.missing': ('没找到带 SDK 10 的 dotnet', 'no dotnet with SDK 10 found'),+ 'dep.python': ('Python + 包', 'Python + packages'),+ 'dep.python.hint': ('lz4 capstone fonttools backports.zstd', 'lz4 capstone fonttools backports.zstd'),+ 'dep.python.missing': ('%@ 缺包', '%@ is missing packages'),+ 'dep.install.fail': ('安装失败(退出码 %d),见下方日志', 'Install failed (exit code %d) — see the log below'),+ 'dep.python.old': ('Python %@ 太旧(需要 %@ 或更新);系统的 /usr/bin/python3 没有这些包', 'Python %@ is too old (need %@ or newer); the system /usr/bin/python3 has none of these packages'),+ 'prog.title': ('构建进度', 'Build progress'),+ 'prog.empty': ('开始构建后,这里显示脚本自己的每个阶段', "The script's own stages appear here once the build starts"),+ 'prog.archive': ('RomFS 归档分片(200 MiB/片)', 'RomFS archive shards (200 MiB each)'),+ 'prog.archiveShort': ('RomFS 归档分片', 'RomFS archive shards'),+ 'prog.noRomfs': ('找不到解出的 RomFS', 'no extracted RomFS found'),+ 'log.placeholder': ('构建日志会显示在这里', 'The build log appears here'),+ 'btn.build': ('开始构建', 'Start build'),+ 'btn.rebuild': ('重新构建', 'Rebuild'),+ 'btn.stop': ('停止', 'Stop'),+ 'btn.outDir': ('输出目录…', 'Output folder…'),+ 'status.checkingDeps': ('正在检测依赖…', 'Checking dependencies…'),+ 'status.installFirst': ('先安装上方缺失的依赖', 'Install the missing dependencies above first'),+ 'status.chooseRepo': ('先选择项目仓库', 'Choose the project repository first'),+ 'status.needInputs': ('还需要选择游戏本体和 prod.keys', 'Still need the base game and prod.keys'),+ 'status.output': ('输出:%@', 'Output: %@'),+ 'install.title': ('安装到 iPhone', 'Install on the iPhone'),+ 'install.step1': ('1\\t用 AltStore / Sideloadly 安装上面的 IPA', '1\\tInstall the IPA above with AltStore / Sideloadly'),+ 'install.step2': ('2\\t把上面的 romfs 文件夹整个拷到游戏 App 的 Documents 里(文件 App → 我的 iPhone → 游戏名)', "2\\tCopy the whole romfs folder above into the game app's Documents (Files → On My iPhone → game name)"),+ 'install.step3': ('3\\t启动游戏', '3\\tLaunch the game'),+ 'install.reveal': ('在访达中显示', 'Reveal in Finder'),+ 'msg.running': ('运行:%@', 'Running: %@'),+ 'msg.installingNsz': ('选中的是 NSZ / XCZ 压缩格式,正在给构建用的 Python 安装 nsz…', "The selected dump is NSZ / XCZ — installing nsz into the build's Python…"),+ 'msg.noWorkDir': ('这个仓库不是 NX2Apple 的最新版本(构建脚本没有 --work-dir):按脚本默认布局构建。建议换用 NX2Apple 仓库以获得归档复用与断点续传', "This checkout is not the latest NX2Apple (its build script has no --work-dir): using the script's default layout. Switch to the NX2Apple repository for archive reuse and resumable builds"),+ 'msg.nszFailed': ('nsz 安装失败(构建用的 Python:%@)——网络不通?或手动执行 pip install nsz', 'Could not install nsz (build Python: %@) — network trouble? Or run pip install nsz by hand'),+ 'msg.stopped': ('已停止', 'Stopped'),+ 'msg.buildFailed': ('构建失败(退出码 %d),见下方日志', 'Build failed (exit code %d) — see the log below'),+ 'msg.exitCode': ('退出码 %d', 'exit code %d'),+ 'msg.stagingFailed': ('无法在暂存文件夹里建立链接(文件在不同磁盘?)', 'Could not create links in the staging folder (files on different volumes?)'),+ 'msg.launchFailed': ('无法启动构建脚本:%@', 'Could not start the build script: %@'),+ 'msg.repoInvalid': ('仓库路径无效:%@——用上方的「选择仓库…」指向本项目的 clone', 'Invalid repository path: %@ — use Choose repository… above to point at your clone'),+ 'msg.repoInvalidEmpty': ('仓库路径无效:未选择——用上方的「选择仓库…」指向本项目的 clone', 'Invalid repository path: none chosen — use Choose repository… above'),+ 'msg.archiveSkipped': ('IPA 已生成,但归档跳过:找不到 %@/v*/RomFS', 'IPA built, archive skipped: no %@/v*/RomFS'),+ 'msg.archiveFailed': ('归档失败(退出码 %d)', 'Archive failed (exit code %d)'),+ 'msg.archiveNoStart': ('无法启动 romfs_arc.py', 'Could not start romfs_arc.py'),+ 'msg.archiveIpaOnly': ('IPA 已生成,归档失败', 'IPA built, but the archive failed'),+ 'msg.done': ('完成:IPA 与 romfs 归档已生成,按下面三步装到手机', 'Done: the IPA and the romfs archive are ready — three steps below'),+ 'prog.archiveDone': ('归档就绪:%@', 'archive ready: %@'),+ 'prog.archiveReused': ('复用上次归档(%d 个文件未变)', 'reused the previous archive (%d files unchanged)'),+ 'msg.archiveReused': ('归档未变,复用 %@', 'archive unchanged, reusing %@'),+ 'msg.archiveLog': ('归档:%@ → %@', 'Archive: %@ → %@'),+}+++def t(key: str, lang: Lang, *args: object) -> str:+ """The string for `key` in `lang`, with %@-style arguments filled in.++ The Swift table uses %@ as its placeholder (String(format:)); the Qt side uses+ Python's %s, so the placeholder is translated here rather than in every call site.+ """+ zh, en = TABLE.get(key, (key, key))+ s = zh if lang is Lang.ZH else en+ if not args:+ return s+ py = s.replace("%@", "%s").replace("%d", "%d")+ try:+ return py % args+ except (TypeError, ValueError):+ return sdiff --git a/frontend-qt/nspb_qt/model.py b/frontend-qt/nspb_qt/model.pynew file mode 100644index 00000000..5b4c5372--- /dev/null+++ b/frontend-qt/nspb_qt/model.py@@ -0,0 +1,495 @@+"""State, dependency detection and the build runner. No UI here: the window connects to signals."""+from __future__ import annotations++import os+import shutil+import subprocess+import sys+import tempfile+import threading+import time+from dataclasses import dataclass, field+from enum import Enum+from pathlib import Path++from PySide6.QtCore import QObject, Signal++from . import platform_util as pu+from .i18n import Lang+from .localization import t+++# ---------------------------------------------------------------- dependency rows++class DepState(Enum):+ OK = 'ok'+ MISSING = 'missing'+ OLD = 'old' # present but unusable (a too-old interpreter, a stub launcher)+++@dataclass+class Dep:+ id: str+ title_key: str+ hint_key: str+ state: DepState = DepState.MISSING+ detail: str = '' # a path, or a localisation key, or "key:arg"+ install: list[str] = field(default_factory=list) # command that fixes it, empty = manual+ installing: bool = False++ @property+ def ok(self) -> bool:+ return self.state is DepState.OK+++# ---------------------------------------------------------------- build stages++@dataclass+class Stage:+ name: str+ state: str = 'pending' # pending | running | done | failed+ detail: str = ''+ percent: float = 0.0+++# ---------------------------------------------------------------- the model++class Model(QObject):+ """Everything the window reads, and every action it can take.++ Long work runs on a thread and reports through signals, so the window never blocks: Qt+ requires UI updates on the main thread, and a build takes minutes.+ """++ depsChanged = Signal()+ stagesChanged = Signal()+ logAppended = Signal(str)+ repoChanged = Signal()+ runningChanged = Signal(bool)+ finished = Signal(bool, str) # ok, note+ appUpdateFound = Signal(str, str) # tag, url++ def __init__(self) -> None:+ super().__init__()+ self.lang = Lang.initial()+ self.repo_path = self._find_repo()+ self.python_path, self.python_ok, self.python_ver = pu.find_python()+ self.dotnet_path, self.dotnet_ok = pu.find_dotnet()+ self.deps: list[Dep] = []+ self.deps_checked = False+ self.stages: list[Stage] = []+ self.running = False+ self.log_tail = ''+ self.game_dir = ''+ self.base_path = ''+ self.update_path = ''+ self.dlc_paths: list[str] = []+ self.keys_path = ''+ self.out_dir = ''+ self.ipa_path = ''+ self.archive_path = ''+ self._proc: subprocess.Popen | None = None+ self._thread: threading.Thread | None = None+ self._line_buf = ''++ # ---- strings++ def t(self, key: str, *args: object) -> str:+ return t(key, self.lang, *args)++ def toggle_lang(self) -> None:+ self.lang = self.lang.other+ self.repoChanged.emit()+ self.depsChanged.emit()++ # ---- repository++ @staticmethod+ def is_repo(d: str) -> bool:+ return bool(d) and Path(d, 'dm', 'tools', 'nx_extract', 'Program.cs').is_file()++ def _find_repo(self) -> str:+ saved = os.environ.get('NSPB_REPO', '')+ if self.is_repo(saved):+ return saved+ seeds = [Path.cwd(), Path(__file__).resolve().parents[2], Path.home()]+ for base in ('Documents', 'Desktop', ''):+ seeds.append(Path.home() / base / 'NX2Apple' if base else Path.home() / 'NX2Apple')+ for s in seeds:+ d = Path(s)+ for _ in range(4):+ if self.is_repo(str(d)):+ return str(d)+ if d.parent == d:+ break+ d = d.parent+ return ''++ @property+ def repo_ok(self) -> bool:+ return self.is_repo(self.repo_path)++ @property+ def repo_is_git(self) -> bool:+ return bool(self.repo_path) and Path(self.repo_path, '.git').exists()++ def supports_work_dir(self) -> bool:+ """Whether the checkout's build script declares --work-dir (an upstream checkout or an+ old ZIP does not; passing it there stops at argparse — issue #5)."""+ f = Path(self.repo_path, 'scripts', 'build_ipa_from_nsp.py')+ try:+ text = f.read_text(encoding='utf-8', errors='replace')+ except OSError:+ return False+ return "'--work-dir'" in text or '"--work-dir"' in text++ # ---- dependencies++ def check_deps(self) -> None:+ self.deps_checked = False+ threading.Thread(target=self._check_deps_worker, daemon=True).start()++ def _check_deps_worker(self) -> None:+ deps: list[Dep] = []++ # Python + packages+ py, py_ok, py_ver = pu.find_python()+ if py_ok:+ deps.append(Dep('python', 'dep.python', 'dep.python.hint', DepState.OK, py))+ elif py_ver and pu._ver_tuple(py_ver) >= (3, 9):+ deps.append(Dep('python', 'dep.python', 'dep.python.hint', DepState.MISSING,+ f'dep.python.missing:{py} ({py_ver})',+ install=[py, '-m', 'pip', 'install', 'lz4', 'capstone', 'fonttools',+ 'backports.zstd', 'nsz']))+ else:+ deps.append(Dep('python', 'dep.python', 'dep.python.hint', DepState.OLD,+ f'dep.python.old:{py_ver or "?"}:3.9'))++ # .NET+ dn, dn_ok = pu.find_dotnet()+ deps.append(Dep('dotnet', 'dep.dotnet', 'dep.dotnet.hint',+ DepState.OK if dn_ok else DepState.MISSING,+ dn if dn_ok else 'dep.dotnet.missing'))++ # Xcode (macOS) or the cross toolchain (Windows)+ if pu.IS_WIN:+ sdk = pu.ios_sdk_ok()+ deps.append(Dep('ios_sdk', 'dep.iossdk', 'dep.iossdk.hint',+ DepState.OK if sdk else DepState.MISSING,+ os.environ.get('IPHONEOS_SDK_DIR', '') if sdk else ''))+ mtl = pu.metal_toolchain_ok()+ deps.append(Dep('metal', 'dep.metal', 'dep.metal.hint',+ DepState.OK if mtl else DepState.MISSING,+ pu.find_tool('metal') or ''))+ else:+ xc = pu.xcode_ok()+ sdk = xc and pu.ios_sdk_ok()+ deps.append(Dep('xcode', 'dep.xcode', 'dep.xcode.hint',+ DepState.OK if sdk else DepState.MISSING,+ '' if sdk else ('dep.xcode.noSDK' if xc else ''),+ install=[] if sdk else (['/usr/bin/xcodebuild', '-downloadPlatform', 'iOS'] if xc else [])))+ mtl = pu.metal_toolchain_ok()+ deps.append(Dep('metal', 'dep.metal', 'dep.metal.hint',+ DepState.OK if mtl else DepState.MISSING,+ '' if mtl else 'dep.metal.missing',+ install=[] if mtl else ['/usr/bin/xcodebuild', '-downloadComponent', 'MetalToolchain']))++ # the remaining command-line tools+ for tool, key in (('xcodegen', 'dep.xcodegen'), ('zstd', 'dep.zstd'), ('spirv-cross', 'dep.spirv')):+ found = pu.find_tool(tool)+ deps.append(Dep('tool:' + tool, key, key + '.hint',+ DepState.OK if found else DepState.MISSING, found or ''))++ self.deps = deps+ self.python_path, self.python_ok, self.python_ver = py, py_ok, py_ver+ self.dotnet_path, self.dotnet_ok = dn, dn_ok+ self.deps_checked = True+ self.depsChanged.emit()++ @property+ def all_deps_ok(self) -> bool:+ return self.deps_checked and all(d.ok for d in self.deps)++ def install_dep(self, dep: Dep) -> None:+ """Run a dependency's fix on a thread, streaming its output to the log."""+ if not dep.install:+ return+ dep.installing = True+ self.depsChanged.emit()++ def work() -> None:+ ok = True+ if dep.id == 'python':+ ok = self._make_venv(self.python_path)+ else:+ self.logAppended.emit('$ ' + ' '.join(dep.install) + '\n')+ try:+ p = subprocess.Popen(dep.install, stdout=subprocess.PIPE,+ stderr=subprocess.STDOUT, text=True,+ errors='replace', env=pu.child_env(),+ **pu.no_window_kwargs())+ assert p.stdout is not None+ for line in p.stdout:+ self.logAppended.emit(line)+ p.wait()+ ok = p.returncode == 0+ except OSError as e:+ self.logAppended.emit(f'{e}\n')+ ok = False+ dep.installing = False+ self.depsChanged.emit()+ self.check_deps()++ threading.Thread(target=work, daemon=True).start()++ def _make_venv(self, base: str) -> bool:+ vpy = pu.venv_python()+ if not Path(vpy).is_file():+ vdir = pu.venv_dir()+ vdir.parent.mkdir(parents=True, exist_ok=True)+ self.logAppended.emit(f'$ {base} -m venv {vdir}\n')+ if not pu._runs(base, ['-m', 'venv', str(vdir)]):+ self.logAppended.emit('venv creation failed\n')+ return False+ ver = pu._ver_tuple(pu._python_version(vpy))+ pkgs = ['lz4', 'capstone', 'fonttools', 'nsz']+ if ver < (3, 14):+ pkgs.insert(3, 'backports.zstd')+ self.logAppended.emit(f'$ {vpy} -m pip install {" ".join(pkgs)}\n')+ try:+ p = subprocess.Popen([vpy, '-m', 'pip', 'install'] + pkgs, stdout=subprocess.PIPE,+ stderr=subprocess.STDOUT, text=True, errors='replace',+ env=pu.child_env(), **pu.no_window_kwargs())+ assert p.stdout is not None+ for line in p.stdout:+ self.logAppended.emit(line)+ p.wait()+ return p.returncode == 0+ except OSError as e:+ self.logAppended.emit(f'{e}\n')+ return False++ # ---- inputs++ 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."""+ self.game_dir = d+ root = Path(d)+ if not root.is_dir():+ return+ files: list[Path] = []+ for p in sorted(root.iterdir()):+ if p.is_file():+ files.append(p)+ elif p.is_dir():+ files += [q for q in sorted(p.iterdir()) if q.is_file()]+ self.keys_path = next((str(f) for f in files if f.name.lower() == 'prod.keys'), self.keys_path)+ nsps = [f for f in files if f.suffix.lower() in ('.nsp', '.xci', '.nsz', '.xcz')]+ updates = [f for f in nsps if '[upd]' in f.name.lower() or 'update' in f.name.lower()]+ dlcs = [f for f in nsps if '[dlc]' in f.name.lower() or 'addon' in f.name.lower()]+ bases = [f for f in nsps if f not in updates and f not in dlcs]+ self.base_path = str(bases[0]) if bases else ''+ self.update_path = str(updates[0]) if updates else ''+ self.dlc_paths = [str(f) for f in dlcs]+ self.repoChanged.emit()++ @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)++ # ---- build++ def start_build(self) -> None:+ if self.running:+ return+ if not self.repo_ok:+ self.finished.emit(False, self.t('msg.repoInvalidEmpty'))+ 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+ dirs = {str(Path(f).parent) for f in all_files if f}++ staging: str | None = None+ input_dir = base_dir+ if len(dirs) > 1:+ # files from different folders: a staging folder of links so the script sees one folder+ staging = tempfile.mkdtemp(prefix='nspb-stage-')+ linked = 0+ for f in all_files:+ if not f:+ continue+ dst = Path(staging, Path(f).name)+ try:+ os.link(f, dst) if not pu.IS_WIN else shutil.copy2(f, dst)+ linked += 1+ except OSError:+ try:+ shutil.copy2(f, dst)+ linked += 1+ except OSError:+ pass+ if linked == 0:+ self.finished.emit(False, self.t('msg.stagingFailed'))+ return+ input_dir = staging++ tid = self._title_id(self.base_path)+ tid_hex = f'{tid:016X}' if tid else 'game'+ work_dir = str(Path(self.out_dir or base_dir, f'{tid_hex}_build'))++ compressed = any(Path(f).suffix.lower() in ('.nsz', '.xcz')+ for f in all_files if f)+ if compressed and not pu._runs(py, ['-c', 'import nsz']):+ self.logAppended.emit(self.t('msg.installingNsz') + '\n')+ if not pu._runs(py, ['-m', 'pip', 'install', 'nsz']):+ self.finished.emit(False, self.t('msg.nszFailed', py))+ return++ args = [str(Path(self.repo_path, 'scripts', 'build_ipa_from_nsp.py')),+ input_dir, '-k', self.keys_path, '--progress', 'lines']+ has_work_dir = self.supports_work_dir()+ if has_work_dir:+ args += ['--work-dir', work_dir]+ else:+ self.logAppended.emit(self.t('msg.noWorkDir') + '\n')+ if self.out_dir:+ args += ['-o', str(Path(self.out_dir, f'{tid_hex}.ipa'))]+ self.effective_work_dir = work_dir if has_work_dir else str(Path(input_dir, f'{tid_hex}_build'))++ self.running = True+ self.runningChanged.emit(True)+ self.stages = []+ self.log_tail = ''+ self.stagesChanged.emit()+ self.logAppended.emit(self.t('msg.running', py + ' ' + ' '.join(args)) + '\n')++ env = pu.child_env()+ droot = pu.dotnet_root(self.dotnet_path) if self.dotnet_ok else None+ if droot:+ env['DOTNET_ROOT'] = droot+ env['DOTNET_ROOT_ARM64'] = droot++ def work() -> None:+ ok = False+ try:+ self._proc = subprocess.Popen([py] + args, cwd=self.repo_path,+ stdout=subprocess.PIPE, stderr=subprocess.STDOUT,+ text=True, errors='replace', bufsize=1, env=env,+ **pu.no_window_kwargs())+ assert self._proc.stdout is not None+ for line in self._proc.stdout:+ self._on_line(line.rstrip('\n'))+ self._proc.wait()+ ok = self._proc.returncode == 0+ except OSError as e:+ self.logAppended.emit(f'{e}\n')+ finally:+ self._proc = None+ self._flush_lines()+ self.running = False+ self.runningChanged.emit(False)+ if ok:+ self.pack_archive()+ else:+ if self.stages:+ self.stages[-1].state = 'failed'+ self.stagesChanged.emit()+ self.finished.emit(False, self.t('msg.buildFailed'))+ if staging:+ shutil.rmtree(staging, ignore_errors=True)++ self._thread = threading.Thread(target=work, daemon=True)+ self._thread.start()++ def cancel_build(self) -> None:+ if self._proc and self._proc.poll() is None:+ self._proc.terminate()++ # ---- the script's own progress lines++ def _on_line(self, line: str) -> None:+ """Feed one line of the build's output: stage lines move the stage list, everything+ else goes to the log (which is what the window shows)."""+ self.logAppended.emit(line + '\n')+ if line.startswith('output IPA:'):+ self.ipa_path = line.split(':', 1)[1].strip()+ low = line.lower()+ for st in self.stages:+ if st.state == 'running':+ st.detail = line[:120]+ break+ if '[' in line and ']' in line:+ head = line[:line.find(']') + 1]+ if '/' in head:+ name = line[line.find(']') + 1:].strip()+ if name:+ if self.stages and self.stages[-1].state == 'running':+ self.stages[-1].state = 'done'+ self.stages.append(Stage(name=name, state='running'))+ self.stagesChanged.emit()+ del low++ def _flush_lines(self) -> None:+ self._line_buf = ''++ # ---- the archive step (what makes a 16 GB game installable)++ def pack_archive(self) -> None:+ work = getattr(self, 'effective_work_dir', '')+ extract = Path(work, 'extract')+ versions = []+ if extract.is_dir():+ for d in sorted(extract.iterdir()):+ if d.is_dir() and d.name.startswith('v') and (d / 'RomFS').is_dir():+ try:+ versions.append((int(d.name[1:]), d))+ except ValueError:+ pass+ if not versions:+ self.finished.emit(True, self.t('msg.archiveSkipped', str(extract)))+ return+ romfs = str(versions[-1][1] / 'RomFS')+ dest = str(Path(self.out_dir or Path(self.base_path).parent, 'romfs'))+ self.stages.append(Stage(name=self.t('prog.archiveShort'), state='running'))+ self.stagesChanged.emit()++ def work_() -> None:+ args = [self.python_path, str(Path(self.repo_path, 'dm', 'tools', 'romfs_arc.py')),+ 'pack', romfs, str(Path(dest, 'romfs')), '--shard-mib', '200']+ env = pu.child_env({'PYTHONPATH': str(Path(self.repo_path, 'dm', 'tools'))})+ ok = True+ try:+ p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,+ text=True, errors='replace', env=env,+ **pu.no_window_kwargs())+ assert p.stdout is not None+ for line in p.stdout:+ self.logAppended.emit(line)+ p.wait()+ ok = p.returncode == 0+ except OSError as e:+ self.logAppended.emit(f'{e}\n')+ ok = False+ if self.stages:+ self.stages[-1].state = 'done' if ok else 'failed'+ self.archive_path = dest if ok else ''+ self.stagesChanged.emit()+ self.finished.emit(ok, '' if ok else self.t('msg.archiveFailed'))++ threading.Thread(target=work_, daemon=True).start()++ @staticmethod+ def _title_id(nsp: str) -> int | None:+ """The title ID from a dump's file name: the 16 hex digits in [0100…], which every+ dumper puts there."""+ import re+ m = re.search(r'\[([0-9A-Fa-f]{16})\]', Path(nsp).name)+ if not m:+ return None+ try:+ return int(m.group(1), 16)+ except ValueError:+ return Nonediff --git a/frontend-qt/nspb_qt/platform_util.py b/frontend-qt/nspb_qt/platform_util.pynew file mode 100644index 00000000..9205d2a9--- /dev/null+++ b/frontend-qt/nspb_qt/platform_util.py@@ -0,0 +1,227 @@+"""Per-OS paths, tool discovery and process launching.++Everything the UI needs that differs between Windows and macOS lives here, so the model and+the window never branch on sys.platform themselves.+"""+from __future__ import annotations++import os+import shutil+import subprocess+import sys+from pathlib import Path++IS_WIN = sys.platform.startswith('win')+IS_MAC = sys.platform == 'darwin'+++# ---------------------------------------------------------------- tool discovery++def _which(name: str, extra: list[str] | None = None) -> str | None:+ """shutil.which plus a list of absolute candidates (a GUI launch does not inherit the+ shell's PATH on either OS, so the usual install locations are probed by hand)."""+ if found := shutil.which(name):+ return found+ for c in extra or []:+ if c and Path(c).is_file() and os.access(c, os.X_OK):+ return c+ return None+++def find_python() -> tuple[str, bool, str]:+ """The interpreter to build with: (path, has_packages, version_or_empty).++ The build scripts need lz4, capstone, fontTools, zstd and (for compressed dumps) nsz. A+ system interpreter rarely has them, so the venv the app manages is checked first, then+ every python on the machine.+ """+ probe = (+ "import lz4, capstone, fontTools\n"+ "try:\n"+ " from compression import zstd\n"+ "except ImportError:\n"+ " from backports import zstd\n"+ )+ cands: list[str] = [venv_python()]+ if IS_WIN:+ cands += [+ os.path.expandvars(r'%LOCALAPPDATA%\Programs\Python\Python312\python.exe'),+ os.path.expandvars(r'%LOCALAPPDATA%\Programs\Python\Python311\python.exe'),+ os.path.expandvars(r'%ProgramFiles%\Python312\python.exe'),+ ]+ else:+ fw = '/Library/Frameworks/Python.framework/Versions'+ if Path(fw).is_dir():+ for v in sorted(os.listdir(fw), reverse=True):+ cands.append(f'{fw}/{v}/bin/python3')+ cands += ['/opt/homebrew/bin/python3', '/usr/local/bin/python3', '/usr/bin/python3']+ if w := _which('python3' if not IS_WIN else 'python'):+ cands.append(w)++ fallback: tuple[str, str] | None = None+ seen: set[str] = set()+ for c in cands:+ if not c or c in seen or not Path(c).is_file():+ continue+ seen.add(c)+ ver = _python_version(c)+ if not ver or _ver_tuple(ver) < (3, 9):+ continue+ if _runs(c, ['-c', probe]):+ return (c, True, ver)+ if fallback is None:+ fallback = (c, ver)+ if fallback:+ return (fallback[0], False, fallback[1])+ return ('python' if IS_WIN else '/usr/bin/python3', False, '')+++def _python_version(py: str) -> str:+ try:+ r = subprocess.run([py, '-c', 'import sys;print("%d.%d"%sys.version_info[:2])'],+ capture_output=True, text=True, timeout=20)+ return r.stdout.strip() if r.returncode == 0 else ''+ except Exception:+ return ''+++def _ver_tuple(v: str) -> tuple[int, int]:+ parts = v.split('.')+ try:+ return (int(parts[0]), int(parts[1]))+ except (IndexError, ValueError):+ return (0, 0)+++def _runs(exe: str, args: list[str]) -> bool:+ try:+ return subprocess.run([exe] + args, capture_output=True, timeout=120).returncode == 0+ except Exception:+ return False+++def venv_dir() -> Path:+ if IS_WIN:+ base = Path(os.environ.get('LOCALAPPDATA', Path.home() / 'AppData' / 'Local'))+ else:+ base = Path.home() / 'Library' / 'Application Support'+ return base / 'NS Port Builder' / 'venv'+++def venv_python() -> str:+ v = venv_dir()+ return str(v / ('Scripts/python.exe' if IS_WIN else 'bin/python3'))+++# ---------------------------------------------------------------- dotnet++def find_dotnet() -> tuple[str, bool]:+ cands = []+ if IS_WIN:+ cands += [r'C:\Program Files\dotnet\dotnet.exe',+ os.path.expandvars(r'%LOCALAPPDATA%\Microsoft\dotnet\dotnet.exe')]+ else:+ cands += [str(Path.home() / '.dotnet' / 'dotnet'),+ '/usr/local/share/dotnet/dotnet',+ '/opt/homebrew/bin/dotnet']+ path = _which('dotnet', cands) or ('dotnet.exe' if IS_WIN else 'dotnet')+ ok = _runs(path, ['--list-sdks'])+ return (path, ok)+++def dotnet_root(dotnet: str) -> str | None:+ """The runtime root the apphost looks for, from `dotnet --list-runtimes`.++ A set-but-wrong DOTNET_ROOT is worse than none (the apphost stops searching), so this+ returns None when the derivation does not answer and the caller leaves the variable out —+ the build script derives and verifies its own in that case.+ """+ try:+ r = subprocess.run([dotnet, '--list-runtimes'], capture_output=True, text=True, timeout=60)+ if r.returncode != 0:+ return None+ except Exception:+ return None+ for ln in r.stdout.splitlines():+ if not ln.startswith('Microsoft.NETCore.App'):+ continue+ if '[' in ln and ']' in ln:+ p = ln[ln.rfind('[') + 1:ln.rfind(']')]+ else:+ continue+ suffix = os.sep + os.path.join('shared', 'Microsoft.NETCore.App')+ if p.endswith(suffix):+ return p[:-len(suffix)]+ if p:+ return p+ return None+++# ---------------------------------------------------------------- external tools++def find_tool(name: str) -> str | None:+ """xcodegen / zstd / spirv-cross / metal, by the usual locations per OS."""+ if IS_WIN:+ extra = [rf'C:\Program Files\{name}\{name}.exe',+ rf'C:\ProgramData\chocolatey\bin\{name}.exe']+ return _which(name + '.exe', extra)+ return _which(name, [f'/opt/homebrew/bin/{name}', f'/usr/local/bin/{name}'])+++def metal_toolchain_ok() -> bool:+ """Whether a Metal compiler answers. On Windows that is Apple's Metal Developer Tools+ (metal.exe + metallib.exe); on macOS it is xcrun's."""+ if IS_WIN:+ return find_tool('metal') is not None and find_tool('metallib') is not None+ return _runs('/usr/bin/xcrun', ['-sdk', 'macosx', 'metal', '--version'])+++def ios_sdk_ok() -> bool:+ if IS_WIN:+ # The Windows path uses an iPhoneOS SDK extracted from an archive, located by the+ # caller (the WebUI does the same); presence of the directory is the check.+ return bool(os.environ.get('IPHONEOS_SDK_DIR') and Path(os.environ['IPHONEOS_SDK_DIR']).is_dir())+ return _runs('/usr/bin/xcrun', ['--sdk', 'iphoneos', '--show-sdk-version'])+++def xcode_ok() -> bool:+ if IS_WIN:+ return False # Xcode is macOS-only; Windows uses the cross toolchain instead+ return Path('/Applications/Xcode.app').is_dir() and Path('/usr/bin/xcodebuild').is_file()+++# ---------------------------------------------------------------- process helpers++def child_env(extra: dict[str, str] | None = None) -> dict[str, str]:+ """The environment every child process gets: a PATH with the usual tool directories,+ HOME/USER present (a GUI launch can strip them), and DOTNET_CLI_HOME so .NET's first-run+ state has somewhere to go."""+ env = dict(os.environ)+ dirs = [env.get('PATH', '')]+ if IS_WIN:+ dirs += [r'C:\Program Files\dotnet', os.path.expandvars(r'%LOCALAPPDATA%\Microsoft\dotnet')]+ sep = ';'+ else:+ dirs += ['/opt/homebrew/bin', '/usr/local/bin', '/usr/bin', '/bin']+ sep = ':'+ env['PATH'] = sep.join(d for d in dirs if d)+ if not env.get('HOME') or not Path(env['HOME']).is_dir():+ env['HOME'] = str(Path.home())+ env.setdefault('USER', os.environ.get('USERNAME') or os.environ.get('USER') or 'user')+ env.setdefault('DOTNET_CLI_HOME', env['HOME'])+ if extra:+ env.update(extra)+ return env+++def short_path(p: str) -> str:+ """Home shown as ~ (keeps the account name out of screenshots)."""+ home = str(Path.home())+ return '~' + p[len(home):] if p.startswith(home) else p+++def no_window_kwargs() -> dict:+ """Hide the console window a child process would otherwise flash on Windows."""+ if IS_WIN:+ return {'creationflags': subprocess.CREATE_NO_WINDOW}+ return {}diff --git a/frontend-qt/nspb_qt/ui.py b/frontend-qt/nspb_qt/ui.pynew file mode 100644index 00000000..fa0b65ce--- /dev/null+++ b/frontend-qt/nspb_qt/ui.py@@ -0,0 +1,348 @@+"""The window: header, repository, inputs, dependencies, build, log. Mirrors the SwiftUI app."""+from __future__ import annotations++import os+from pathlib import Path++from PySide6.QtCore import Qt, QTimer+from PySide6.QtGui import QFont, QFontDatabase+from PySide6.QtWidgets import (+ QCheckBox, QFileDialog, QFrame, QGridLayout, QGroupBox, QHBoxLayout, QLabel,+ QMainWindow, QMessageBox, QProgressBar, QPushButton, QScrollArea, QSizePolicy,+ QTextEdit, QVBoxLayout, QWidget,+)++from . import platform_util as pu+from .model import Dep, DepState, Model+++class MainWindow(QMainWindow):+ def __init__(self, model: Model) -> None:+ super().__init__()+ self.m = model+ self.setWindowTitle('NS Port Builder')+ self.resize(980, 900)+ self._mono = QFontDatabase.systemFont(QFontDatabase.FixedFont)++ root = QWidget()+ self.setCentralWidget(root)+ outer = QVBoxLayout(root)+ outer.setContentsMargins(0, 0, 0, 0)+ outer.setSpacing(0)++ scroll = QScrollArea()+ scroll.setWidgetResizable(True)+ scroll.setFrameShape(QFrame.NoFrame)+ body = QWidget()+ self.body = QVBoxLayout(body)+ self.body.setContentsMargins(16, 14, 16, 14)+ self.body.setSpacing(12)+ scroll.setWidget(body)+ outer.addWidget(scroll, 1)++ self._build_header()+ self._build_repository()+ self._build_inputs()+ self._build_deps()+ self._build_actions()+ self._build_log()+ outer.addWidget(self._separator())+ self._build_footer()++ self.m.depsChanged.connect(self._refresh_deps)+ self.m.repoChanged.connect(self._refresh_all)+ self.m.stagesChanged.connect(self._refresh_stages)+ self.m.logAppended.connect(self._append_log)+ self.m.runningChanged.connect(self._refresh_running)+ self.m.finished.connect(self._on_finished)++ self._refresh_all()+ self.m.check_deps()++ # ---------------------------------------------------------------- sections++ def _build_header(self) -> None:+ row = QHBoxLayout()+ title = QLabel('NS Port Builder')+ f = title.font()+ f.setPointSize(20)+ f.setBold(True)+ title.setFont(f)+ self.subtitle = QLabel(self.m.t('app.subtitle'))+ self.subtitle.setStyleSheet('color: palette(mid);')+ left = QVBoxLayout()+ left.setSpacing(2)+ left.addWidget(title)+ left.addWidget(self.subtitle)+ row.addLayout(left)+ row.addStretch(1)+ self.lang_btn = QPushButton(self.m.lang.toggle_label)+ self.lang_btn.clicked.connect(self._toggle_lang)+ row.addWidget(self.lang_btn, 0, Qt.AlignTop)+ self.body.addLayout(row)++ def _build_repository(self) -> None:+ box = QGroupBox(self.m.t('repo.title'))+ self.repo_box = box+ lay = QVBoxLayout(box)+ note = QLabel(self.m.t('repo.note'))+ note.setStyleSheet('color: palette(mid);')+ lay.addWidget(note)+ row = QHBoxLayout()+ self.repo_path_label = QLabel('')+ self.repo_path_label.setFont(self._mono)+ self.repo_path_label.setTextInteractionFlags(Qt.TextSelectableByMouse)+ row.addWidget(self.repo_path_label, 1)+ self.choose_btn = QPushButton(self.m.t('repo.choose'))+ self.choose_btn.clicked.connect(self._choose_repo)+ row.addWidget(self.choose_btn)+ lay.addLayout(row)+ self.repo_status = QLabel('')+ self.repo_status.setStyleSheet('color: palette(mid);')+ lay.addWidget(self.repo_status)+ box.setStyleSheet('QGroupBox { margin-top: 10px; padding-top: 6px; } QGroupBox::title { subcontrol-origin: margin; left: 10px; padding: 0 4px; }')+ self.body.addWidget(box)++ def _build_inputs(self) -> None:+ box = QGroupBox(self.m.t('data.title'))+ self.data_box = box+ lay = QVBoxLayout(box)+ note = QLabel(self.m.t('data.note'))+ note.setStyleSheet('color: palette(mid);')+ lay.addWidget(note)+ grid = QGridLayout()+ grid.setColumnStretch(1, 1)+ self.input_labels: dict[str, QLabel] = {}+ rows = [('base', 'data.base'), ('update', 'data.update'), ('dlc', 'data.dlc'), ('keys', 'data.keys')]+ for i, (key, l10n) in enumerate(rows):+ name = QLabel(self.m.t(l10n))+ val = QLabel('—')+ val.setFont(self._mono)+ val.setTextInteractionFlags(Qt.TextSelectableByMouse)+ val.setStyleSheet('color: palette(mid);')+ grid.addWidget(name, i, 0)+ grid.addWidget(val, i, 1)+ self.input_labels[key] = val+ lay.addLayout(grid)+ row = QHBoxLayout()+ self.folder_label = QLabel(self.m.t('data.folderHint'))+ self.folder_label.setStyleSheet('color: palette(mid);')+ row.addWidget(self.folder_label, 1)+ pick = QPushButton(self.m.t('data.pickFolder'))+ pick.clicked.connect(self._pick_folder)+ row.addWidget(pick)+ lay.addLayout(row)+ box.setStyleSheet('QGroupBox { margin-top: 10px; padding-top: 6px; } QGroupBox::title { subcontrol-origin: margin; left: 10px; padding: 0 4px; }')+ self.body.addWidget(box)++ def _build_deps(self) -> None:+ box = QGroupBox(self.m.t('dep.title'))+ self.deps_box = box+ lay = QVBoxLayout(box)+ head = QHBoxLayout()+ self.deps_summary = QLabel('')+ head.addWidget(self.deps_summary, 1)+ recheck = QPushButton(self.m.t('dep.recheck'))+ recheck.clicked.connect(self.m.check_deps)+ head.addWidget(recheck)+ lay.addLayout(head)+ self.deps_container = QVBoxLayout()+ lay.addLayout(self.deps_container)+ box.setStyleSheet('QGroupBox { margin-top: 10px; padding-top: 6px; } QGroupBox::title { subcontrol-origin: margin; left: 10px; padding: 0 4px; }')+ self.body.addWidget(box)++ def _build_actions(self) -> None:+ row = QHBoxLayout()+ self.build_btn = QPushButton(self.m.t('build.start'))+ self.build_btn.setMinimumHeight(38)+ f = self.build_btn.font()+ f.setPointSize(13)+ f.setBold(True)+ self.build_btn.setFont(f)+ self.build_btn.clicked.connect(self.m.start_build)+ row.addWidget(self.build_btn, 1)+ self.out_btn = QPushButton(self.m.t('build.outDir'))+ self.out_btn.clicked.connect(self._choose_out)+ row.addWidget(self.out_btn)+ self.body.addLayout(row)+ self.stages_container = QVBoxLayout()+ self.body.addLayout(self.stages_container)+ self.body.addStretch(1)++ def _build_log(self) -> None:+ self.log = QTextEdit()+ self.log.setReadOnly(True)+ self.log.setFont(self._mono)+ self.log.setPlaceholderText(self.m.t('log.placeholder'))+ self.log.setMinimumHeight(150)+ self.log.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)+ self.body.addWidget(self.log, 1)++ def _build_footer(self) -> None:+ row = QHBoxLayout()+ row.setContentsMargins(16, 8, 16, 10)+ self.footer = QLabel('')+ row.addWidget(self.footer, 1)+ wrap = QWidget()+ wrap.setLayout(row)+ self.centralWidget().layout().addWidget(wrap)++ @staticmethod+ def _separator() -> QFrame:+ line = QFrame()+ line.setFrameShape(QFrame.HLine)+ line.setFrameShadow(QFrame.Sunken)+ return line++ # ---------------------------------------------------------------- refresh++ def _refresh_all(self) -> None:+ self.subtitle.setText(self.m.t('app.subtitle'))+ self.lang_btn.setText(self.m.lang.toggle_label)+ self.repo_box.setTitle(self.m.t('repo.title'))+ self.choose_btn.setText(self.m.t('repo.choose'))+ self.data_box.setTitle(self.m.t('data.title'))+ self.deps_box.setTitle(self.m.t('dep.title'))+ if self.m.repo_ok:+ self.repo_path_label.setText(pu.short_path(self.m.repo_path))+ self.repo_path_label.setStyleSheet('')+ self.repo_status.setText(self.m.t('repo.ok') if self.m.repo_is_git else self.m.t('repo.noGit'))+ else:+ self.repo_path_label.setText(self.m.repo_path or self.m.t('repo.notFound'))+ self.repo_path_label.setStyleSheet('color: palette(highlight);')+ self.repo_status.setText(self.m.t('repo.firstHint'))+ for key, lbl in self.input_labels.items():+ v = {'base': self.m.base_path, 'update': self.m.update_path,+ 'keys': self.m.keys_path}.get(key)+ if key == 'dlc':+ v = f'{len(self.m.dlc_paths)} 个' if self.m.dlc_paths else ''+ lbl.setText(Path(v).name if v else '—')+ lbl.setStyleSheet('' if v else 'color: palette(mid);')+ self.folder_label.setText(pu.short_path(self.m.game_dir) if self.m.game_dir else self.m.t('data.folderHint'))+ self._refresh_deps()++ def _refresh_deps(self) -> None:+ while self.deps_container.count():+ item = self.deps_container.takeAt(0)+ if w := item.widget():+ w.deleteLater()+ for d in self.m.deps:+ row = QWidget()+ h = QHBoxLayout(row)+ h.setContentsMargins(0, 1, 0, 1)+ mark = QLabel('✓' if d.ok else ('!' if d.state is DepState.OLD else '✗'))+ mark.setFixedWidth(18)+ mark.setStyleSheet(f'color: {"#2e9e4f" if d.ok else "#c0392b"}; font-weight: bold;')+ h.addWidget(mark)+ h.addWidget(QLabel(self.m.t(d.title_key)), 0)+ detail = d.detail+ if detail.startswith('dep.'):+ if ':' in detail:+ key, arg = detail.split(':', 1)+ detail = self.m.t(key, arg)+ else:+ detail = self.m.t(detail)+ elif detail:+ detail = pu.short_path(detail)+ lab = QLabel(detail)+ lab.setFont(self._mono)+ lab.setStyleSheet('color: palette(mid);')+ lab.setTextInteractionFlags(Qt.TextSelectableByMouse)+ h.addWidget(lab, 1)+ if not d.ok:+ if d.install:+ btn = QPushButton(self.m.t('dep.install'))+ btn.setEnabled(not d.installing)+ btn.clicked.connect(lambda _=False, dep=d: self.m.install_dep(dep))+ h.addWidget(btn)+ else:+ hint = QLabel(self.m.t(d.hint_key))+ hint.setStyleSheet('color: palette(mid);')+ h.addWidget(hint)+ self.deps_container.addWidget(row)+ if self.m.deps_checked:+ n_ok = sum(1 for d in self.m.deps if d.ok)+ if self.m.all_deps_ok:+ self.deps_summary.setText(self.m.t('dep.allReady'))+ self.deps_summary.setStyleSheet('color: #2e9e4f;')+ else:+ self.deps_summary.setText(self.m.t('dep.missing', len(self.m.deps) - n_ok))+ self.deps_summary.setStyleSheet('color: #c0392b;')+ else:+ self.deps_summary.setText(self.m.t('dep.checking'))+ self.deps_summary.setStyleSheet('color: palette(mid);')+ self._refresh_running()++ def _refresh_stages(self) -> None:+ while self.stages_container.count():+ item = self.stages_container.takeAt(0)+ if w := item.widget():+ w.deleteLater()+ for st in self.m.stages:+ row = QWidget()+ h = QHBoxLayout(row)+ h.setContentsMargins(0, 1, 0, 1)+ mark = {'done': '✓', 'running': '…', 'failed': '✗'}.get(st.state, '·')+ colour = {'done': '#2e9e4f', 'failed': '#c0392b'}.get(st.state, 'palette(mid)')+ lab = QLabel(mark)+ lab.setFixedWidth(16)+ lab.setStyleSheet(f'color: {colour};')+ h.addWidget(lab)+ h.addWidget(QLabel(st.name), 0)+ det = QLabel(st.detail)+ det.setFont(self._mono)+ det.setStyleSheet('color: palette(mid);')+ h.addWidget(det, 1)+ self.stages_container.addWidget(row)++ def _refresh_running(self) -> None:+ running = self.m.running+ self.build_btn.setText(self.m.t('build.cancel') if running else self.m.t('build.start'))+ self.build_btn.setEnabled(running or self.m.can_build)+ if not running:+ try:+ self.build_btn.clicked.disconnect()+ except (RuntimeError, TypeError):+ pass+ self.build_btn.clicked.connect(self.m.cancel_build if running else self.m.start_build)++ def _append_log(self, s: str) -> None:+ self.log.moveCursor(self.log.textCursor().MoveOperation.End)+ self.log.insertPlainText(s)+ self.log.moveCursor(self.log.textCursor().MoveOperation.End)++ def _on_finished(self, ok: bool, note: str) -> None:+ if ok:+ msg = self.m.t('msg.done') if not note else note+ if self.m.ipa_path:+ msg += '\n' + self.m.t('msg.ipaAt', self.m.ipa_path)+ if self.m.archive_path:+ msg += '\n' + self.m.t('msg.archiveAt', self.m.archive_path)+ self.footer.setText(msg)+ self.footer.setStyleSheet('color: #2e9e4f;')+ else:+ self.footer.setText(note or self.m.t('msg.buildFailed'))+ self.footer.setStyleSheet('color: #c0392b;')++ # ---------------------------------------------------------------- actions++ def _toggle_lang(self) -> None:+ self.m.toggle_lang()+ self._refresh_all()++ def _choose_repo(self) -> None:+ d = QFileDialog.getExistingDirectory(self, self.m.t('repo.pickMessage'))+ if d:+ self.m.repo_path = d+ self.m.repoChanged.emit()++ def _pick_folder(self) -> None:+ d = QFileDialog.getExistingDirectory(self, self.m.t('data.pickFolder'))+ if d:+ self.m.scan_game_dir(d)++ def _choose_out(self) -> None:+ d = QFileDialog.getExistingDirectory(self, self.m.t('build.outDir'))+ if d:+ self.m.out_dir = d+ self._refresh_all()diff --git a/frontend-qt/requirements.txt b/frontend-qt/requirements.txtnew file mode 100644index 00000000..a3e9b8ba--- /dev/null+++ b/frontend-qt/requirements.txt@@ -0,0 +1 @@+PySide6>=6.5diff --git a/frontend/Sources/NSPortBuilder/Localization.swift b/frontend/Sources/NSPortBuilder/Localization.swiftindex 560a2b4a..f3fb78b5 100644--- a/frontend/Sources/NSPortBuilder/Localization.swift+++ b/frontend/Sources/NSPortBuilder/Localization.swift@@ -110,6 +110,19 @@ enum L10n {"data.noNsp": ("这个文件夹里没有 NSP/XCI", "No NSP/XCI in this folder"),// ---- dependencies ----+ // ---- Qt front end (frontend-qt): keys the SwiftUI app does not use yet ----+ "build.start": ("开始构建", "Start build"),+ "build.cancel": ("取消构建", "Cancel build"),+ "build.outDir": ("输出目录…", "Output folder…"),+ "msg.ipaAt": ("IPA:%@", "IPA: %@"),+ "msg.archiveAt": ("归档:%@", "Archive: %@"),+ "repo.ok": ("仓库可用", "repository ready"),+ "dep.iossdk": ("iPhoneOS SDK", "iPhoneOS SDK"),+ "dep.iossdk.hint": ("Windows 上需要 iPhoneOS SDK(用于交叉编译)",+ "Windows needs an iPhoneOS SDK for the cross build"),+ "dep.metal.missing": ("未找到 metal.exe(Apple Metal Developer Tools for Windows)",+ "metal.exe not found (Apple Metal Developer Tools for Windows)"),+"dep.title": ("设备依赖", "Device dependencies"),"dep.checking": ("检测中…", "Checking…"),"dep.allReady": ("全部就绪", "All ready"),