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
Windows installs: the tools landed where nothing looked for them
LNPANDY0424f4f13e37
diff --git a/frontend-qt/gen_localization.py b/frontend-qt/gen_localization.pyindex 0323f48b..0f835998 100644--- a/frontend-qt/gen_localization.py+++ b/frontend-qt/gen_localization.py@@ -51,7 +51,7 @@ def main() -> None:' s = zh if lang is Lang.ZH else en',' if not args:',' return s',- ' py = s.replace("%@", "%s").replace("%d", "%d")',+ ' py = s.replace("%@", "%s") # %d is the same in both; %@ is Swift-only',' try:',' return py % args',' except (TypeError, ValueError):',diff --git a/frontend-qt/nspb_qt/localization.py b/frontend-qt/nspb_qt/localization.pyindex 88e4f77a..4b2affac 100644--- a/frontend-qt/nspb_qt/localization.py+++ b/frontend-qt/nspb_qt/localization.py@@ -97,6 +97,7 @@ TABLE: dict[str, tuple[str, str]] = {'dep.optionalMissing': ('可选,未安装', 'optional, not installed'),'dep.glslang': ('glslangValidator(可选)', 'glslangValidator (optional)'),'dep.glslang.hint': ('仅 OpenGL 游戏需要', 'only needed for OpenGL games'),+ 'dep.installTimeout': ('安装超时(30 分钟)——网络太慢或卡住了', 'Install timed out (30 minutes) — the network is slow or stuck'),'dep.installAll': ('一键安装全部缺失项', 'Install all missing'),'dep.recheck': ('重新检测', 'Check again'),'dep.install': ('安装', 'Install'),@@ -128,6 +129,10 @@ TABLE: dict[str, tuple[str, str]] = {'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.export': ('导出日志…', 'Export log…'),+ 'log.exported': ('日志已保存:%@', 'Log saved: %@'),+ 'log.exportFail': ('保存失败:%@', 'Could not save: %@'),+ 'log.at': ('日志同时写入 %@', 'The log is also written to %@'),'log.placeholder': ('构建日志会显示在这里', 'The build log appears here'),'btn.build': ('开始构建', 'Start build'),'btn.rebuild': ('重新构建', 'Rebuild'),@@ -176,7 +181,7 @@ def t(key: str, lang: Lang, *args: object) -> str:s = zh if lang is Lang.ZH else enif not args:return s- py = s.replace("%@", "%s").replace("%d", "%d")+ py = s.replace("%@", "%s") # %d is the same in both; %@ is Swift-onlytry:return py % argsexcept (TypeError, ValueError):diff --git a/frontend-qt/nspb_qt/model.py b/frontend-qt/nspb_qt/model.pyindex 41da77db..fcc72e65 100644--- a/frontend-qt/nspb_qt/model.py+++ b/frontend-qt/nspb_qt/model.py@@ -94,6 +94,17 @@ class Model(QObject):self._proc: subprocess.Popen | None = Noneself._thread: threading.Thread | None = Noneself._line_buf = ''+ # Every log line also goes to a file, so a user on a handheld can send one file instead of+ # copying text out of the window. One file per run, overwritten at start; the path is shown+ # in the log's first line so it can be found.+ try:+ base = (Path(os.environ['LOCALAPPDATA']) / 'NS Port Builder' / 'logs') if pu.IS_WIN \+ else (Path.home() / 'Library' / 'Logs' / 'NS Port Builder')+ base.mkdir(parents=True, exist_ok=True)+ self.log_path = base / 'last-run.log'+ self.log_path.write_text('', encoding='utf-8')+ except OSError:+ self.log_path = None# ---- strings@@ -315,32 +326,32 @@ class Model(QObject):if not git:if not pu.IS_WIN:self.repoChanged.emit()- self.logAppended.emit(self.t('repo.gitMissing') + '\n')+ self.log(self.t('repo.gitMissing') + '\n')return# Windows with no git at all: fetch PortableGit, then carry on with the clone. This is# the one case where "one click" has to install something first; it needs no# administrator rights and no installer.self.repo_busy = Trueself.repoChanged.emit()- self.logAppended.emit(self.t('repo.gitInstalling') + '\n')+ self.log(self.t('repo.gitInstalling') + '\n')def install_then_clone() -> None:ok = Falsetry:from .win import fetch as wf- path = wf.install_git(log=lambda s: self.logAppended.emit(str(s) + '\n'),- progress=lambda d, t_: self.logAppended.emit(+ path = wf.install_git(log=lambda s: self.log(str(s) + '\n'),+ progress=lambda d, t_: self.log(f' {d // 1048576} MB' +(f' / {t_ // 1048576} MB ({d * 100 // t_}%)' if t_ else '') + '\n'))ok = Path(path).is_file()except Exception as e:- self.logAppended.emit(self.t('repo.gitInstallFail', str(e)) + '\n')+ self.log(self.t('repo.gitInstallFail', str(e)) + '\n')self.repo_busy = Falseself.repoChanged.emit()if ok:self.clone_repo(dest) # now git exists: the normal pathelse:- self.logAppended.emit(self.t('repo.gitMissing') + '\n')+ self.log(self.t('repo.gitMissing') + '\n')threading.Thread(target=install_then_clone, daemon=True).start()return@@ -350,11 +361,11 @@ class Model(QObject):self.repo_path = targetself.repoChanged.emit()else:- self.logAppended.emit(self.t('repo.destBusy', target) + '\n')+ self.log(self.t('repo.destBusy', target) + '\n')returnself.repo_busy = Trueself.repoChanged.emit()- self.logAppended.emit(f'$ git clone --depth 1 {self.REPO_URL} {target}\n')+ self.log(f'$ git clone --depth 1 {self.REPO_URL} {target}\n')def work() -> None:ok = False@@ -365,11 +376,11 @@ class Model(QObject):errors='replace', env=pu.child_env(), **pu.no_window_kwargs())assert p.stdout is not Nonefor line in p.stdout:- self.logAppended.emit(line.replace('\r', '\n'))+ self.log(line.replace('\r', '\n'))p.wait()ok = p.returncode == 0except OSError as e:- self.logAppended.emit(f'{e}\n')+ self.log(f'{e}\n')self.repo_busy = Falseif ok and self.is_repo(target):self.repo_path = target@@ -400,7 +411,7 @@ class Model(QObject):out, self.repo_status = str(e), self.t('repo.pullFail')self.repo_busy = Falseif out:- self.logAppended.emit(out + '\n')+ self.log(out + '\n')self.repoChanged.emit()threading.Thread(target=work, daemon=True).start()@@ -436,114 +447,48 @@ class Model(QObject):# ---- installing what is missing ----def install_all_missing(self) -> None:- """Walk the dependency rows and run each one's install command in turn.+ """Install every missing dependency, one at a time, in order.- Sequential on purpose: the installers compete for the same package manager and the- output is far easier to follow one tool at a time.+ Genuinely sequential: each installer runs on its own thread, so an earlier version+ started them all at once and their downloads interleaved in the log (reported from a+ handheld: LLVM and SDK lines mixed). Order also matters for correctness — the SDK is+ fetched with git, which the git row may be installing."""- for d in list(self.deps):- if not d.ok and d.install:- self.install_dep(d)-- 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:+ pending = [d for d in self.deps if not d.ok and d.install]+ if not pending or getattr(self, '_install_all_running', False):return- # A Windows toolchain row carries a marker instead of a command line: the download is- # in-process (nspb_qt.win.fetch), so there is nothing to spawn.- if dep.install[0].startswith('__win__:'):- self._install_win(dep, dep.install[0].split(':', 1)[1])- return- dep.installing = True- self.depsChanged.emit()+ self._install_all_running = True- 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()+ def run_all() -> None:+ try:+ for d in pending:+ self.log(f'--- {self.t(d.title_key)} ---\n')+ self.install_dep(d)+ waited = 0.0+ while d.installing and waited < 1800:+ time.sleep(0.25)+ waited += 0.25+ if d.installing:+ self.log(self.t('dep.installTimeout') + '\n')+ self.check_deps() # one refresh at the end, with everything in place+ finally:+ self._install_all_running = False- threading.Thread(target=work, daemon=True).start()+ threading.Thread(target=run_all, daemon=True).start()- def _install_win(self, dep: Dep, what: str) -> None:- """Download and unpack a Windows toolchain piece, with progress in the log.+ def log(self, s: str) -> None:+ """Append to the window's log and to the log file.- Runs on a thread. Every failure names the step and what to do by hand, because a- download can fail for reasons the app cannot fix (a proxy, a proxy that blocks GitHub,- an Apple ID needed for the Metal tools).+ The file is what makes a bug report possible from a handheld, where copying text out of+ the window is painful: one path, one file, sent as-is."""- dep.installing = True- self.depsChanged.emit()-- def work() -> None:- ok = False+ self.logAppended.emit(s)+ if getattr(self, 'log_path', None):try:- from .win import fetch as wf, toolchain as wtc- if what == 'llvm':- self.logAppended.emit(self.t('dep.llvm.downloading') + '\n')- path = wf.install_llvm(log=lambda s: self.logAppended.emit(str(s) + '\n'),- progress=lambda d, t_: self.logAppended.emit(- f' {d // 1048576} MB' + (f' / {t_ // 1048576} MB ({d * 100 // t_}%)' if t_ else '') + '\n'))- self.logAppended.emit(self.t('dep.llvm.done', str(path)) + '\n')- ok = True- elif what == 'ios_sdk':- self.logAppended.emit(self.t('dep.iossdk.downloading') + '\n')- from .win import sdk_fetch as sf- path = sf.clone_sdk(log=lambda s: self.logAppended.emit(str(s) + '\n'))- self.logAppended.emit(self.t('dep.iossdk.done', str(path)) + '\n')- ok = True- except Exception as e: # DownloadError, OSError, a missing attribute: all reported- self.logAppended.emit(self.t('dep.install.fail', str(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+ with open(self.log_path, 'a', encoding='utf-8', errors='replace') as f:+ f.write(s)+ except OSError:+ self.log_path = None # one failure disables the file, not the app# ---- inputs@@ -619,7 +564,7 @@ class Model(QObject):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')+ self.log(self.t('msg.installingNsz') + '\n')if not pu._runs(py, ['-m', 'pip', 'install', 'nsz']):self.finished.emit(False, self.t('msg.nszFailed', py))return@@ -638,7 +583,7 @@ class Model(QObject):if has_work_dir:args += ['--work-dir', work_dir]else:- self.logAppended.emit(self.t('msg.noWorkDir') + '\n')+ self.log(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'))@@ -648,7 +593,7 @@ class Model(QObject):self.stages = []self.log_tail = ''self.stagesChanged.emit()- self.logAppended.emit(self.t('msg.running', py + ' ' + ' '.join(args)) + '\n')+ self.log(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@@ -665,9 +610,9 @@ class Model(QObject):env = wshim.build_env(env, python_exe=py)ok_shim, why = wshim.verify_shim(env)if not ok_shim:- self.logAppended.emit(f'[shim] {why}\n')+ self.log(f'[shim] {why}\n')except Exception as e: # a broken shim must be visible, not fatal- self.logAppended.emit(f'[shim] could not prepare the Windows shim: {e}\n')+ self.log(f'[shim] could not prepare the Windows shim: {e}\n')env['NSPB_REPO'] = self.repo_pathdef work() -> None:@@ -683,7 +628,7 @@ class Model(QObject):self._proc.wait()ok = self._proc.returncode == 0except OSError as e:- self.logAppended.emit(f'{e}\n')+ self.log(f'{e}\n')finally:self._proc = Noneself._flush_lines()@@ -711,7 +656,7 @@ class Model(QObject):def _on_line(self, line: str) -> None:"""Feed one line of the build's output: stage lines move the stage list, everythingelse goes to the log (which is what the window shows)."""- self.logAppended.emit(line + '\n')+ self.log(line + '\n')if line.startswith('output IPA:'):self.ipa_path = line.split(':', 1)[1].strip()low = line.lower()@@ -765,11 +710,11 @@ class Model(QObject):**pu.no_window_kwargs())assert p.stdout is not Nonefor line in p.stdout:- self.logAppended.emit(line)+ self.log(line)p.wait()ok = p.returncode == 0except OSError as e:- self.logAppended.emit(f'{e}\n')+ self.log(f'{e}\n')ok = Falseif self.stages:self.stages[-1].state = 'done' if ok else 'failed'diff --git a/frontend-qt/nspb_qt/ui.py b/frontend-qt/nspb_qt/ui.pyindex 717c1965..0b802fc6 100644--- a/frontend-qt/nspb_qt/ui.py+++ b/frontend-qt/nspb_qt/ui.py@@ -226,6 +226,17 @@ class MainWindow(QMainWindow):lay.addLayout(self.stages_container)def _build_log(self) -> None:+ head = QHBoxLayout()+ head.setSpacing(6)+ self.log_path_label = QLabel('')+ self.log_path_label.setObjectName('note')+ self.log_path_label.setTextInteractionFlags(Qt.TextSelectableByMouse)+ self.log_path_label.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Preferred)+ head.addWidget(self.log_path_label, 1)+ self.export_btn = QPushButton(self.m.t('log.export'))+ self.export_btn.clicked.connect(self._export_log)+ head.addWidget(self.export_btn)+ self.body.addLayout(head)self.log = QTextEdit()self.log.setReadOnly(True)self.log.setFont(self._mono)@@ -282,6 +293,8 @@ class MainWindow(QMainWindow):busy = self.m.repo_busy or self.m.runningfor b in (self.download_btn, self.check_btn, self.pull_btn, self.choose_btn):b.setEnabled(not busy)+ if getattr(self.m, 'log_path', None):+ self.log_path_label.setText(self.m.t('log.at', str(self.m.log_path)))self._refresh_inputs()self._refresh_deps()@@ -477,6 +490,26 @@ class MainWindow(QMainWindow):self.m.dlc_paths.append(path)self.m.repoChanged.emit()+ def _export_log(self) -> None:+ """Save the log to a file the user picks, defaulting to the Desktop.++ The window's log is also written to disk as it grows (m.model.log_path); this is for+ sending a copy somewhere, e.g. attaching it to an issue from a handheld where copying text+ out of the window is awkward.+ """+ default = str(Path.home() / 'Desktop' / 'ns-port-builder-log.txt')+ path, _ = QFileDialog.getSaveFileName(self, self.m.t('log.export'), default,+ 'Text (*.txt);;All files (*)')+ if not path:+ return+ try:+ Path(path).write_text(self.log.toPlainText(), encoding='utf-8')+ self.footer.setText(self.m.t('log.exported', path))+ self.footer.setStyleSheet(f'color: {GREEN};')+ except OSError as e:+ self.footer.setText(self.m.t('log.exportFail', str(e)))+ self.footer.setStyleSheet(f'color: {RED};')+def _choose_out(self) -> None:d = QFileDialog.getExistingDirectory(self, self.m.t('build.outDir'))if d:diff --git a/frontend-qt/nspb_qt/win/sdk_fetch.py b/frontend-qt/nspb_qt/win/sdk_fetch.pyindex 1c30a0da..6922346c 100644--- a/frontend-qt/nspb_qt/win/sdk_fetch.py+++ b/frontend-qt/nspb_qt/win/sdk_fetch.py@@ -47,7 +47,11 @@ def clone_sdk(version: str = tc.SDK_PINNED, dest: Path | None = None,set` pulls only the requested SDK. That is what makes this practical on a normal connection."""log = log or (lambda s: None)- git = shutil.which('git')+ # toolchain.git_exe() first: the app may have downloaded its own PortableGit, which is not on+ # PATH. `shutil.which` alone missed it, so the SDK step failed right after a successful git+ # install (the same "installed but invisible" bug as llvm_dir had).+ found = tc.git_exe() or shutil.which('git')+ git = str(found) if found else Noneif not git:raise SdkError('git is not installed: get it from https://git-scm.com/download/win, or ''download an Xcode .xip and use the xip route instead')diff --git a/frontend-qt/nspb_qt/win/toolchain.py b/frontend-qt/nspb_qt/win/toolchain.pyindex d27e5448..fa835ee8 100644--- a/frontend-qt/nspb_qt/win/toolchain.py+++ b/frontend-qt/nspb_qt/win/toolchain.py@@ -77,6 +77,20 @@ GIT_RELEASE_TAG = 'v2.56.0.windows.4'GIT_RELEASE_URL = f'https://github.com/git-for-windows/git/releases/download/{GIT_RELEASE_TAG}'+def bundled_tools_dir() -> Path:+ """Where the app keeps tools it downloaded for itself.++ A frozen build runs from a directory PyInstaller made; `sys._MEIPASS` is that directory+ (`<app>/_internal` on Windows). A source run uses the frontend-qt folder. Either way this is+ the same base that fetch.install_llvm unpacks into, which is what keeps the installer and the+ detector looking at one place.+ """+ base = getattr(sys, '_MEIPASS', None)+ if base:+ return Path(base) / '.tools'+ return Path(__file__).resolve().parents[2] / '.tools'++def git_dir() -> Path:"""Where the app keeps its own PortableGit, if it downloaded one."""return Path(os.environ.get('LOCALAPPDATA', Path.home() / 'AppData' / 'Local')) / \@@ -212,6 +226,10 @@ def llvm_dir() -> Path | None:if base:cands += sorted(glob.glob(os.path.join(base, 'Programs', 'LLVM')), reverse=True)cands += sorted(glob.glob(os.path.join(base, 'llvm-mingw*')), reverse=True)+ # the app's own download location first: install_llvm() unpacks under+ # <app>/_internal/.tools, and without this the freshly installed toolchain was invisible to+ # the next dependency check (the report: "installed, then Check again changed nothing").+ cands.insert(0, bundled_tools_dir() / f'llvm-mingw-{LLVM_MINGW_VERSION}')# a clang already on PATH, if it came from a toolchain with lld beside itif w := shutil.which('clang'):cands.append(Path(w).parent.parent)diff --git a/frontend/Sources/NSPortBuilder/Localization.swift b/frontend/Sources/NSPortBuilder/Localization.swiftindex 3a836026..8ece5a5c 100644--- a/frontend/Sources/NSPortBuilder/Localization.swift+++ b/frontend/Sources/NSPortBuilder/Localization.swift@@ -155,6 +155,8 @@ enum L10n {"dep.optionalMissing": ("可选,未安装", "optional, not installed"),"dep.glslang": ("glslangValidator(可选)", "glslangValidator (optional)"),"dep.glslang.hint": ("仅 OpenGL 游戏需要", "only needed for OpenGL games"),+ "dep.installTimeout": ("安装超时(30 分钟)——网络太慢或卡住了",+ "Install timed out (30 minutes) — the network is slow or stuck"),"dep.installAll": ("一键安装全部缺失项", "Install all missing"),"dep.recheck": ("重新检测", "Check again"),"dep.install": ("安装", "Install"),@@ -195,6 +197,10 @@ enum L10n {"prog.noRomfs": ("找不到解出的 RomFS", "no extracted RomFS found"),// ---- log ----+ "log.export": ("导出日志…", "Export log…"),+ "log.exported": ("日志已保存:%@", "Log saved: %@"),+ "log.exportFail": ("保存失败:%@", "Could not save: %@"),+ "log.at": ("日志同时写入 %@", "The log is also written to %@"),"log.placeholder": ("构建日志会显示在这里", "The build log appears here"),// ---- footer ----