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: the Metal zip the player downloads is installed by the app
LNPANDY6383796bc6c2
diff --git a/frontend-qt/nspb_qt/localization.py b/frontend-qt/nspb_qt/localization.pyindex 7645a951..b41eb245 100644--- a/frontend-qt/nspb_qt/localization.py+++ b/frontend-qt/nspb_qt/localization.py@@ -611,7 +611,11 @@ TABLE: dict[str, tuple[str, str, str]] = {'dep.show': ('展开', 'Show', 'Show'),'dep.pick': ('选择文件夹…', 'Choose folder…', 'Choose folder…'),'dep.pick.ios_sdk.title': ('选择 iPhoneOS SDK 文件夹', 'Choose the iPhoneOS SDK folder', 'Choose the iPhoneOS SDK folder'),- 'dep.pick.metal_dir.title': ('选择 Metal Developer Tools 文件夹', 'Choose the Metal Developer Tools folder', 'Choose the Metal Developer Tools folder'),+ 'dep.pick.metal_dir.title': ('选择 Metal Developer Tools(下载的 zip 或解压后的文件夹)', 'Choose Metal Developer Tools (the downloaded zip, or the unpacked folder)', 'Choose Metal Developer Tools (the downloaded zip, or the unpacked folder)'),+ 'dep.pick.metal': ('选择 zip / 文件夹…', 'Choose zip / folder…', 'Choose zip / folder…'),+ 'dep.metal.unpacking': ('正在解压 %@…', 'Unpacking %@…', 'Unpacking %@…'),+ 'dep.metal.done': ('Metal Developer Tools 已安装:%@', 'Metal Developer Tools installed: %@', 'Metal Developer Tools installed: %@'),+ 'dep.pick.metal.invalid': ('“%@”里没有 metal.exe(需要 bin\\\\metal.exe 或 ios\\\\bin\\\\metal.exe):确认下载的是 “Metal Developer Tools for Windows”。', 'No metal.exe inside "%@" (needs bin\\\\metal.exe or ios\\\\bin\\\\metal.exe): check that the download is "Metal Developer Tools for Windows".', 'No metal.exe inside "%@" (needs bin\\\\metal.exe or ios\\\\bin\\\\metal.exe): check that the download is "Metal Developer Tools for Windows".'),'dep.pick.saved': ('已记住:%@', 'Remembered: %@', 'Remembered: %@'),'dep.pick.iossdk.saved': ('SDK 已记住:%@', 'SDK remembered: %@', 'SDK remembered: %@'),'dep.pick.iossdk.version': ('SDK 版本:%@', 'SDK version: %@', 'SDK version: %@'),diff --git a/frontend-qt/nspb_qt/model.py b/frontend-qt/nspb_qt/model.pyindex c1e0e53a..0c36cda9 100644--- a/frontend-qt/nspb_qt/model.py+++ b/frontend-qt/nspb_qt/model.py@@ -81,6 +81,9 @@ class Model(QObject):#: Set by the window: asks for a folder (QFileDialog lives in the UI layer) and returns the#: path, or '' when the user cancelled. `pick_dep_folder` calls it, so the model stays UI-free.ask_folder: Callable[[str], str] | None = None+ #: Same, for a file ('Metal Developer Tools*.zip' the user downloaded from Apple).+ ask_file: Callable[[str], str] | None = None+ _metal_zip: Path | None = Nonedef __init__(self) -> None:super().__init__()@@ -754,6 +757,16 @@ class Model(QObject):path = sf.clone_sdk(log=lambda s: self.log(str(s) + '\n'))self.log(self.t('dep.iossdk.done', str(path)) + '\n')ok = True+ elif what == 'metal_zip':+ # Apple's tools are Apple-ID-gated: the browser download is the licensed+ # path, the app does the unpack and remembers the folder.+ self.log(self.t('dep.metal.unpacking', self._metal_zip.name) + '\n')+ from .win import fetch as wf+ dest = wf.install_metal_from_zip(self._metal_zip,+ log=lambda s: self.log(str(s) + '\n'))+ wtc.save_config('metal_dir', str(dest))+ self.log(self.t('dep.metal.done', str(dest)) + '\n')+ ok = Trueelse:self.log(f'unknown Windows install target: {what}\n')except Exception as e:@@ -803,6 +816,19 @@ class Model(QObject):if not dep.pick_key:returnfrom .win import toolchain as wtc+ if dep.pick_key == 'metal_dir':+ # The Metal zip is a file, not a folder: the ask_file callback (the window's file+ # dialog filters *.zip) takes the browser download straight away. An already+ # unpacked folder is equally accepted.+ ask_file = self.ask_file+ if ask_file is None:+ return+ picked = ask_file(self.t('dep.pick.metal_dir.title'))+ if not picked:+ return+ if picked.lower().endswith('.zip'):+ return self.install_metal_zip(Path(picked))+ return self._save_metal_folder(Path(picked))ask = self.ask_folderif ask is None:return # no window attached (tests): nothing to ask with@@ -826,6 +852,29 @@ class Model(QObject):self.log(self.t('dep.pick.saved', folder) + '\n')self.check_deps()+ def _save_metal_folder(self, folder: Path) -> None:+ """A folder the user already unpacked: validate the two layouts metal_dir() accepts."""+ from .win import toolchain as wtc+ if not (folder / 'bin' / 'metal.exe').is_file() and \+ not (folder / 'ios' / 'bin' / 'metal.exe').is_file():+ self.log(self.t('dep.pick.metal.invalid', str(folder)) + '\n')+ return+ wtc.save_config('metal_dir', str(folder))+ self.log(self.t('dep.pick.saved', str(folder)) + '\n')+ self.check_deps()++ def install_metal_zip(self, zip_path: Path) -> None:+ """Unpack the Apple zip the player downloaded and remember the folder (the one manual+ dependency on Windows: Apple-ID-gated, so the app cannot fetch it itself)."""+ if not zip_path.is_file():+ self.log(self.t('dep.pick.metal.invalid', str(zip_path)) + '\n')+ return+ self._metal_zip = zip_path+ dep = next((d for d in self.deps if d.id == 'metal'), None)+ if dep is None:+ return+ self._install_win(dep, 'metal_zip')+def _progress_logger(self, label: str):"""A progress callback that logs at 5% steps, not on every chunk.diff --git a/frontend-qt/nspb_qt/ui.py b/frontend-qt/nspb_qt/ui.pyindex 40214792..8212a3bb 100644--- a/frontend-qt/nspb_qt/ui.py+++ b/frontend-qt/nspb_qt/ui.py@@ -77,6 +77,8 @@ class MainWindow(QMainWindow):self.m.finished.connect(self._on_finished)self._refresh_all()+ self.m.ask_folder = lambda title: self._ask_folder(title)+ self.m.ask_file = lambda title: self._ask_file(title)self.m.check_deps()# ---------------------------------------------------------------- header@@ -515,8 +517,9 @@ class MainWindow(QMainWindow):h.addWidget(btn)if d.pick_key:# Apple-licensed pieces cannot be downloaded by the app: Choose points at a- # copy the user already has (validated, remembered in toolchain.json).- pick = QPushButton(self.m.t('dep.pick'))+ # copy the user already has — an unpacked folder, or (Metal) the downloaded+ # zip, which the app unpacks and remembers.+ pick = QPushButton(self.m.t('dep.pick.metal' if d.pick_key == 'metal_dir' else 'dep.pick'))pick.clicked.connect(lambda _=False, dep=d: self.m.pick_dep_folder(dep))h.addWidget(pick)if not d.install and not d.pick_key:@@ -690,6 +693,14 @@ class MainWindow(QMainWindow):self.failure_box.hide()self.m.start_build()+ def _ask_folder(self, title: str) -> str:+ d = QFileDialog.getExistingDirectory(self, title)+ return d or ''++ def _ask_file(self, title: str) -> str:+ d, _ = QFileDialog.getOpenFileName(self, title, '', 'Metal tools zip (*.zip)')+ return d or ''+def _choose_repo(self) -> None:d = QFileDialog.getExistingDirectory(self, self.m.t('repo.pickMessage'))if d:diff --git a/frontend-qt/nspb_qt/win/fetch.py b/frontend-qt/nspb_qt/win/fetch.pyindex 3014969b..9750d0a3 100644--- a/frontend-qt/nspb_qt/win/fetch.py+++ b/frontend-qt/nspb_qt/win/fetch.py@@ -558,3 +558,51 @@ def _download_unverified(url: str, dest: Path, log: Callable[[str], None],except (urllib.error.URLError, OSError) as e:tmp.unlink(missing_ok=True)raise DownloadError(f'download failed: {url}: {e}') from e+++def install_metal_from_zip(zip_path: Path, dest: Path | None = None,+ log: Callable[[str], None] | None = None) -> Path:+ """Unpack a "Metal Developer Tools for Windows" zip the user downloaded from Apple, and+ return the folder to write into `toolchain.json` as `metal_dir`.++ Apple's tools are Apple-ID-gated and cannot be downloaded by the app; the browser download+ is the licensed path, and this is the app doing the unpack the user would otherwise do by+ hand — into `tools_dir()`, the same place the other toolchains live, surviving app updates.+ The zip is validated before anything is remembered: it must contain `metal.exe` (5.x/6.x in+ `bin/`, 4.x in `ios/bin/`), matching `toolchain.metal_dir()`'s two accepted layouts.+ """+ import zipfile as _zf+ src = Path(zip_path)+ if not src.is_file():+ raise DownloadError(f'{src} does not exist')+ if log:+ log(f'unpacking {src.name} …')+ dest = Path(dest) if dest else tc.tools_dir() / 'metal-developer-tools'+ staging = dest.parent / (dest.name + '-staging')+ shutil.rmtree(staging, ignore_errors=True)+ staging.mkdir(parents=True)+ try:+ with _zf.ZipFile(src) as z:+ bad = [i.filename for i in z.infolist() if i.filename.startswith('/') or '..' in Path(i.filename).parts]+ if bad:+ raise DownloadError(f'unsafe paths inside {src.name}: {bad[:3]}')+ z.extractall(staging)+ except _zf.BadZipFile as e:+ shutil.rmtree(staging, ignore_errors=True)+ raise DownloadError(f'{src.name} is not a zip file ({e})') from e++ def has_metal(root: Path) -> bool:+ return (root / 'bin' / 'metal.exe').is_file() or (root / 'ios' / 'bin' / 'metal.exe').is_file()++ roots = [staging] + [p for p in staging.iterdir() if p.is_dir()] # zip may or may not carry a top folder+ hit = next((r for r in roots if has_metal(r)), None)+ if hit is None:+ shutil.rmtree(staging, ignore_errors=True)+ raise DownloadError(f'{src.name} does not look like Metal Developer Tools '+ '(no metal.exe in bin/ or ios/bin/)')+ shutil.rmtree(dest, ignore_errors=True)+ hit.rename(dest)+ shutil.rmtree(staging, ignore_errors=True)+ if log:+ log(f'Metal Developer Tools unpacked to {dest}')+ return destdiff --git a/frontend-qt/tests/test_win.py b/frontend-qt/tests/test_win.pyindex 4b6a150e..0d297f82 100644--- a/frontend-qt/tests/test_win.py+++ b/frontend-qt/tests/test_win.py@@ -1706,6 +1706,75 @@ class LinkProbeStrategyTest(unittest.TestCase):self.assertIn('dep.fix.nonascii', hinted)+class MetalPickFlowShapeTest(unittest.TestCase):+ """The model wiring (source-shape, since model.py needs PySide6): the metal row asks for a+ file, takes a zip to install_metal_zip, a folder to _save_metal_folder."""++ def test_the_metal_row_routes_zip_and_folder(self) -> None:+ src = (QT / 'nspb_qt' / 'model.py').read_text()+ body = src[src.index("if dep.pick_key == 'metal_dir':"):]+ self.assertIn('ask_file', body, 'the metal row must ask for a file (the zip)')+ self.assertIn('install_metal_zip', body)+ self.assertIn('_save_metal_folder', body)+ self.assertIn("endswith('.zip')", body)+++class MetalZipInstallTest(unittest.TestCase):+ """The one manual dependency (Apple-ID-gated Metal tools) handed a downloaded zip: the app+ unpacks, validates both shipped layouts, and refuses anything else."""++ def setUp(self) -> None:+ self.tmp = tempfile.TemporaryDirectory()+ self.addCleanup(self.tmp.cleanup)+ self.root = Path(self.tmp.name)++ @staticmethod+ def _fake_tools(root: Path, layout: str) -> Path:+ bin_ = root / ('ios/bin' if layout == '4.x' else 'bin')+ bin_.mkdir(parents=True)+ (bin_ / 'metal.exe').write_bytes(b'MZ')+ (bin_ / 'metallib.exe').write_bytes(b'MZ')+ return root++ def test_a_zip_with_the_tools_unpacks_to_the_tools_dir(self) -> None:+ from nspb_qt.win import fetch as wf+ tools = self.root / 'tools'+ src = self._fake_tools(self.root / 'unpacked', '6.x')+ zip_path = self.root / 'Metal Developer Tools 6.0.zip'+ import zipfile+ with zipfile.ZipFile(zip_path, 'w') as z:+ for f in src.rglob('*'):+ z.write(f, f.relative_to(src.parent))+ dest = wf.install_metal_from_zip(zip_path, dest=tools / 'metal-developer-tools')+ self.assertTrue((dest / 'bin' / 'metal.exe').is_file())+ self.assertFalse((tools / 'metal-developer-tools-staging').exists(), 'staging is cleaned up')++ def test_a_4x_layout_zip_is_accepted_by_its_ios_folder(self) -> None:+ from nspb_qt.win import fetch as wf+ src = self._fake_tools(self.root / 'u4', '4.x')+ zip_path = self.root / 'metal4.zip'+ import zipfile+ with zipfile.ZipFile(zip_path, 'w') as z:+ for f in src.rglob('*'):+ z.write(f, f.relative_to(src.parent))+ dest = wf.install_metal_from_zip(zip_path, dest=self.root / 'tools' / 'm4')+ self.assertTrue((dest / 'ios' / 'bin' / 'metal.exe').is_file())++ def test_a_zip_without_metal_exe_is_refused_and_leaves_nothing_behind(self) -> None:+ from nspb_qt.win import fetch as wf+ zip_path = self.root / 'not-metal.zip'+ import zipfile+ with zipfile.ZipFile(zip_path, 'w') as z:+ (self.root / 'junk').mkdir()+ (self.root / 'junk' / 'readme.txt').write_text('x', encoding='utf-8')+ z.write(self.root / 'junk' / 'readme.txt', 'stuff/readme.txt')+ tools = self.root / 'tools'+ with self.assertRaises(wf.DownloadError):+ wf.install_metal_from_zip(zip_path, dest=tools / 'm')+ self.assertFalse((tools / 'm').exists())+ self.assertFalse((tools / 'm-staging').exists())++class InstallFailureHintTest(unittest.TestCase):"""The row's fix hint after a failed install (Mac parity: name the fix, not the traceback)."""diff --git a/frontend/Sources/NSPortBuilder/Localization.swift b/frontend/Sources/NSPortBuilder/Localization.swiftindex 69b22fe2..925e8ebe 100644--- a/frontend/Sources/NSPortBuilder/Localization.swift+++ b/frontend/Sources/NSPortBuilder/Localization.swift@@ -706,7 +706,11 @@ enum L10n {"dep.show": ("展开", "Show"),"dep.pick": ("选择文件夹…", "Choose folder…"),"dep.pick.ios_sdk.title": ("选择 iPhoneOS SDK 文件夹", "Choose the iPhoneOS SDK folder"),- "dep.pick.metal_dir.title": ("选择 Metal Developer Tools 文件夹", "Choose the Metal Developer Tools folder"),+ "dep.pick.metal_dir.title": ("选择 Metal Developer Tools(下载的 zip 或解压后的文件夹)", "Choose Metal Developer Tools (the downloaded zip, or the unpacked folder)"),+ "dep.pick.metal": ("选择 zip / 文件夹…", "Choose zip / folder…"),+ "dep.metal.unpacking": ("正在解压 %@…", "Unpacking %@…"),+ "dep.metal.done": ("Metal Developer Tools 已安装:%@", "Metal Developer Tools installed: %@"),+ "dep.pick.metal.invalid": ("“%@”里没有 metal.exe(需要 bin\\metal.exe 或 ios\\bin\\metal.exe):确认下载的是 “Metal Developer Tools for Windows”。", "No metal.exe inside \"%@\" (needs bin\\metal.exe or ios\\bin\\metal.exe): check that the download is \"Metal Developer Tools for Windows\"."),"dep.pick.saved": ("已记住:%@", "Remembered: %@"),"dep.pick.iossdk.saved": ("SDK 已记住:%@", "SDK remembered: %@"),"dep.pick.iossdk.version": ("SDK 版本:%@", "SDK version: %@"),