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 build capability: 4,100 lines that make the Qt front end produce an IPA
LNPANDYf074175ac56e
diff --git a/.gitignore b/.gitignoreindex 2689ecd2..3734c64c 100644--- a/.gitignore+++ b/.gitignore@@ -20,3 +20,8 @@ dm/games/*/cb_extent.tsv# Swift build products at the repository root (a stray build run).build/sync.log++# PyInstaller output (frontend-qt)+frontend-qt/build/+frontend-qt/dist/+frontend-qt/*.specdiff --git a/frontend-qt/README.md b/frontend-qt/README.mdindex d29c7d6a..abc6b658 100644--- a/frontend-qt/README.md+++ b/frontend-qt/README.md@@ -33,8 +33,8 @@ 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.+ Metal toolchain** (macOS) or the **Windows cross toolchain** (see [Windows build](#windows-build)),+ 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` arerecognised from the dump names.- Build: runs the same script the SwiftUI app runs, streams its stage lines and log, then packs@@ -45,9 +45,10 @@ wherever `NSPB_REPO` points, and the repository group lets you pick it by hand.## 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.+- **The Windows build path has not run on a real Windows machine.** Everything below is written+ and unit-tested on macOS (69 tests in `tests/test_win.py`), but the compile, link, `Metal`+ compile and the final IPA have not been exercised against a genuine LLVM-MinGW + iPhoneOS SDK+ + Metal Developer Tools install. See [Windows build → Open risks](#open-risks).- 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).@@ -61,5 +62,172 @@ nspb_qt/platform_util.py per-OS paths, tool discovery, child environmenti18n.py language choicelocalization.py generated from ../frontend/Sources/NSPortBuilder/Localization.swift+ win/ the Windows build path; imported only when sys.platform is win32gen_localization.py regenerates localization.py+tests/test_win.py the Windows-path tests that can run on macOS```++---++# Windows build++On a Windows PC the pipeline cannot call `xcrun`, `xcodebuild` or `xcodegen`, and+`scripts/build_ipa_from_nsp.py` does not even import (`pwd` is a POSIX-only module). So the app+does not run the script directly on Windows. It runs `nspb_qt/win/driver.py`, which loads the+upstream file **as a module**, replaces the steps that assume a Mac, and calls its `cli()`.++The upstream file is never edited, so the daily sync cannot conflict with this work.++## What each macOS step becomes++| macOS | Windows |+|---|---|+| `xcodegen` + `xcodebuild` | LLVM clang per source file, linked by `ld64.lld` |+| `Launcher.swift` (SwiftUI) | `win/ios/Launcher.m` (UIKit, same `dm_show_launcher` contract) |+| `xcrun -sdk iphoneos metal` | Apple's **Metal Developer Tools for Windows**: `metal.exe` / `metallib.exe` |+| `xcrun -sdk iphoneos clang` | LLVM-MinGW `clang.exe` with `-target arm64-apple-ios26.0 -isysroot <SDK>` |+| `actool` asset catalog | loose PNGs named in `CFBundleIcons` (Pillow) |+| `sips` / `plutil` | Pillow / `plistlib` |+| Darwin compiler-rt (`@available`) | `win/ios/compat_rt.c`, linked only when LLVM has no `libclang_rt.ios.a` |+| `make -n -B dmhost` (source list) | the Makefile rules reproduced in `build_app.host_sources()`, **checked against the Makefile text** |+| `dmsh_xlate` apphost (a Mach-O) | `dotnet dmsh_xlate.dll`, the same locked build |+| `which`, `python3`, `ctypes.CDLL(None)` | `sitecustomize.py` rewrites them at the subprocess boundary |+| app icon via `actool` | Pillow, five sizes |+| `codesign` ad-hoc + entitlements | skipped; the sideloader re-signs the IPA anyway |+| the IPA's Unix `x` bit | `win/fix_ipa_modes.py` rewrites the zip's central directory in place |++## What you need to install++Run this first; it lists what is missing and where to get it:++```bat+python -m nspb_qt.win.doctor+```++1. **Python 3.10+**, then `pip install PySide6 lz4 capstone fonttools pillow`+ (and `backports.zstd` before Python 3.14).+2. **.NET SDK 10** — <https://dotnet.microsoft.com/download/dotnet/10.0> (SDK, x64).+3. **LLVM-MinGW 20261020** — the app's Dependencies panel downloads and verifies it, or:++ ```bat+ python -m nspb_qt.win.doctor --fix+ ```++ Pinned SHA-256 (also in `toolchain.py`):++ | archive | SHA-256 |+ |---|---|+ | `llvm-mingw-20261020-ucrt-x86_64.zip` | `fd5462b7f5d93b2ff981fcd3f9c7e427e47f3203c64ea91c27bcc444eebd74cd` |+ | `llvm-mingw-20261020-ucrt-aarch64.zip` | `8f24fedd0b75c674c6c83dec2d76a7ac31a690120212843a17e465ef49854f69` |++ The official `LLVM-*-win64.msi` from llvm.org works too (same clang, same LLD).++4. **An iPhoneOS SDK 26.x** — either route works:++ ```bat+ python -m nspb_qt.win.doctor --sdk :: git, no Apple ID+ python -m nspb_qt.win.doctor --sdk-xip Xcode_26.5.xip :: Apple's own, free Apple ID+ python -m nspb_qt.win.doctor --import-sdk D:\SDKs\iPhoneOS26.0.sdk+ ```++ The git route sparse-clones one SDK out of `xybp888/iOS-SDKs`. The `.xip` route streams+ Apple's archive and writes only `Platforms/iPhoneOS.platform/Developer/SDKs/`.++5. **Metal Developer Tools for Windows 6.x** —+ <https://developer.apple.com/download/all/?q=metal%20developer%20tools> (free Apple ID).+ The app cannot download this for you: Apple gates it behind a login.++6. **spirv-cross** and **zstd** — Windows builds. The Vulkan SDK has `spirv-cross` (and+ `glslangValidator`); zstd has releases on GitHub.++If auto-detection picks the wrong folder, set it in+`%LOCALAPPDATA%\NS Port Builder\toolchain.json`:++```json+{+ "llvm_dir": "D:\\tools\\llvm-mingw-20261020-ucrt-x86_64",+ "ios_sdk": "D:\\SDKs\\iPhoneOS26.0.sdk",+ "metal_dir": "C:\\Program Files\\Metal Developer Tools",+ "spirv_cross_dir": "C:\\VulkanSDK\\1.4.321.0\\Bin",+ "zstd_dir": "C:\\tools\\zstd"+}+```++## Verify each step++`nspb_qt.win.toolchain` does not trust that a path exists — it runs the tool:++| check | what it proves |+|---|---|+| `probe_compile` | `clang -target arm64-apple-ios26.0 -isysroot <SDK> -c` writes a **0xfeedfacf** arm64 `MH_OBJECT` |+| `probe_link` | `ld64.lld` links an arm64 **`MH_EXECUTE`** with `LC_BUILD_VERSION` platform 2 (iOS) |+| `probe_metal` | `metal.exe` → `.air`, then `metallib.exe` → a non-empty `.metallib` |++```bat+python -m nspb_qt.win.doctor :: human-readable, runs the probes+python -m nspb_qt.win.doctor --json :: for a bug report+```++Exit code 0 means every required row passed its probe.++### The one thing llvm-mingw gets wrong++llvm-mingw's release script (`strip-llvm.sh`) **deletes `ld64.lld.exe`**; the zip only has+`ld.lld.exe`. That is not a dead end: LLD is one binary containing every driver and picks one+from `argv[0]`. Copying `ld.lld.exe` to `ld64.lld.exe` gives the Mach-O linker, and the app does+that automatically (`toolchain.ensure_ld64_lld`). A build of LLD that was stripped down to ELF+only is detected (`MachO` / `ld64.lld` strings absent) and reported instead of failing at link+time.++## Known unsupported game types++These need the game's own arm64 code to run, which upstream does inside a **Mac host**. No+Windows PC can do that, so the build stops with an explanatory message rather than producing a+broken IPA:++- **Run-time shader capture** — GLSLC capture (Fire Emblem: Three Houses, Portal), Vulkan+ capture (Super Mario Galaxy), GL capture of a non-LÖVE game. The game compiles its shaders+ only while running.+- **Unreal / Oodle decoding** — games whose shaders sit inside Oodle-compressed or Trinity packs+ (Pokémon Legends: Z-A, PlatinumGames titles, DRAGON QUEST XI S, …). Upstream decodes them by+ running the game's own decoder.+- **The heap check** for a provisional profile. Replaced by an estimate (a 2 GB pool for a game+ with virtual address memory); see `driver.heap_check`.+- **The pipeline archive** (`pso_offline.py` / `metal-tt`). Apple's Windows Metal tools do not+ ship `metal-tt`, so `DM_PSO_GPUS` is forced to `none`: the device builds those pipeline bases+ on its first start instead (slower first launch, same result).+- **`--prepare-xcode`**, **`--platform mac`** and **`--platform mac-app`**. Refused up front.++Games whose shaders are in the RomFS — Mario Wonder, Odyssey, Mario Kart 8 Deluxe, the Zelda+titles, Metroid Dread — do not need any of that.++## Run a build++```bat+python -m nspb_qt.win.driver D:\Games\MarioWonder -k D:\keys\prod.keys+```++The options are the upstream script's (`-h`). The IPA is unsigned, as on a Mac: sign it with+Sideloadly (Windows), AltStore, or similar, and enable the Increased Memory Limit capability if+the tool offers it. The IPA name and the RomFS archive come out where the macOS build puts them.++## Open risks++Not verifiable without a real Windows machine; check these in order on the first real build:++1. **Shader libraries on the device.** They come from the Windows Metal compiler, not Xcode's.+ They must load and render on iOS 26+ (`newLibraryWithURL`). `own_compilers.py` accepts a+ different compiler version, so the build will not fail — only a device run proves it.+2. **The real rewritten modules.** Sections hundreds of MB, linked by `ld64.lld`, then signed by+ the sideloader.+3. **The UIKit launcher.** `win/ios/Launcher.m` is a hand port of `Launcher.swift`; it honours+ `section` grouping, a toggle's `on`/`off` values, env-file locking and Reset, but no one has+ tapped through it on a device.+4. **Icons without an asset catalog** on iOS 26.+5. **Line endings.** The checkout must keep LF. The shader chain hashes source bytes, so a CRLF+ checkout breaks `dmsh_xlate --source-sha`. `.gitattributes` enforces this; a ZIP download+ with autocrlf on can still break it.++`nspb_qt/win/doctor.py` is the fastest way to narrow a failure: it separates "a tool is missing"+from "the tool exists but cannot do the job".+diff --git a/frontend-qt/nspb_qt/localization.py b/frontend-qt/nspb_qt/localization.pyindex 08194922..1a89ad36 100644--- a/frontend-qt/nspb_qt/localization.py+++ b/frontend-qt/nspb_qt/localization.py@@ -70,7 +70,20 @@ TABLE: dict[str, tuple[str, str]] = {'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.iossdk.hint': ('Windows 上需要 iPhoneOS SDK(交叉编译的头文件与 stub 库):由 App 下载,或从 Xcode.xip 解出', 'Windows needs an iPhoneOS SDK (headers and stub libraries for the cross build): the app downloads one, or extracts it from an Xcode.xip'),+ 'dep.llvm': ('LLVM-MinGW(交叉编译)', 'LLVM-MinGW (cross compiler)'),+ 'dep.llvm.hint': ('点「安装」下载钉死版本的 LLVM-MinGW(含 clang 与 LLD)', 'Install fetches the pinned LLVM-MinGW (clang and LLD)'),+ 'dep.lld': ('ld64.lld(Mach-O 链接器)', 'ld64.lld (Mach-O linker)'),+ 'dep.lld.hint': ('llvm-mingw 的发布包删掉了 ld64.lld.exe,但 ld.lld.exe 含全部 LLD 驱动,改名即可;App 会自动完成', 'llvm-mingw deletes ld64.lld.exe, but ld.lld.exe carries every LLD driver, so renaming it is enough; the app does that'),+ 'dep.probe.compile': ('交叉编译探针', 'cross-compile probe'),+ 'dep.probe.compile.hint': ('用 clang -target arm64-apple-ios 编一个 .m,检查产出是 arm64 Mach-O', 'Compiles one .m for arm64-apple-ios and checks the object is arm64 Mach-O'),+ 'dep.probe.link': ('交叉链接探针', 'cross-link probe'),+ 'dep.probe.link.hint': ('用 ld64.lld 链接一个最小可执行文件,检查它是 iOS 的 MH_EXECUTE', 'Links a minimal executable with ld64.lld and checks it is an iOS MH_EXECUTE'),+ 'dep.probe.metal': ('Metal 编译探针', 'Metal compile probe'),+ 'dep.probe.metal.hint': ('用 metal.exe / metallib.exe 编一个最小 shader,检查产出的 .metallib', 'Compiles a minimal shader with metal.exe / metallib.exe and checks the .metallib'),+ 'dep.glslang': ('glslangValidator(可选)', 'glslangValidator (optional)'),+ 'dep.glslang.hint': ('只有 OpenGL 游戏的 shader 需要它', 'needed only for an OpenGL game’s shaders'),+ 'dep.optionalMissing': ('未安装(可选)', 'not installed (optional)'),'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…'),diff --git a/frontend-qt/nspb_qt/model.py b/frontend-qt/nspb_qt/model.pyindex 369bf14b..3f77d2b6 100644--- a/frontend-qt/nspb_qt/model.py+++ b/frontend-qt/nspb_qt/model.py@@ -176,14 +176,7 @@ class Model(QObject):# 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 ''))+ deps.extend(self._windows_deps())else:xc = pu.xcode_ok()sdk = xc and pu.ios_sdk_ok()@@ -197,11 +190,13 @@ class Model(QObject):'' 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 ''))+ # the remaining command-line tools (xcodegen is macOS-only: the Windows build packs+ # the app directly and needs no project file)+ 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 = depsself.python_path, self.python_ok, self.python_ver = py, py_ok, py_ver@@ -213,6 +208,83 @@ class Model(QObject):def all_deps_ok(self) -> bool:return self.deps_checked and all(d.ok for d in self.deps)+ # ---- Windows toolchain rows++ def _windows_deps(self) -> list[Dep]:+ """The Windows cross toolchain, in the order it matters.++ The checks come from `nspb_qt.win.toolchain`, which runs the real compilers for the+ probes (a clang that produces an arm64 Mach-O object, an `ld64.lld` that links an+ executable, `metal.exe` that builds a `.metallib`) rather than trusting a path. That is+ what turns "the panel says ok" into "the build will get past the first step".++ `nspb_qt.win` is imported inside this method, and only here: on macOS the package is+ never touched, so nothing Windows-specific can break a Mac start-up.+ """+ from .win import toolchain as wtc # local import: macOS never loads it++ out: list[Dep] = []+ probes = wtc.check_all(deep=True)+ by_id = {p.id: p for p in probes}++ def state(p) -> DepState:+ return DepState.OK if p.ok else (DepState.OLD if p.state == 'wrong' else DepState.MISSING)++ # LLVM (+ the Mach-O linker, which comes from the same folder)+ p = by_id.get('llvm')+ if p:+ detail = p.path if p.ok else (p.detail or '')+ install: list[str] = []+ if not p.ok:+ # the app downloads the pinned LLVM-MinGW itself; no command line needed+ install = []+ out.append(Dep('llvm', 'dep.llvm', 'dep.llvm.hint', state(p), detail,+ install=install))+ p = by_id.get('lld')+ if p:+ out.append(Dep('lld', 'dep.lld', 'dep.lld.hint', state(p),+ p.detail if not p.ok else (p.path or 'ok')))++ # the SDK+ p = by_id.get('ios_sdk')+ if p:+ detail = ''+ if p.ok:+ detail = p.path+ elif p.state == 'wrong':+ detail = p.detail+ out.append(Dep('ios_sdk', 'dep.iossdk', 'dep.iossdk.hint', state(p), detail))++ # Metal+ p = by_id.get('metal')+ if p:+ out.append(Dep('metal', 'dep.metal', 'dep.metal.hint', state(p),+ (p.path or 'ok') if p.ok else (p.detail or '')))++ # the probes: one row each, so a broken toolchain names the step that fails+ for pid, key in (('probe_compile', 'dep.probe.compile'),+ ('probe_link', 'dep.probe.link'),+ ('probe_metal', 'dep.probe.metal')):+ p = by_id.get(pid)+ if p:+ out.append(Dep(pid, key, key + '.hint',+ DepState.OK if p.ok else DepState.MISSING, p.detail))++ # cross-platform tools: spirv-cross and zstd are required, glslang only for GL games+ for pid, key, req in (('spirv-cross', 'dep.spirv', True),+ ('zstd', 'dep.zstd', True),+ ('glslangValidator', 'dep.glslang', False)):+ p = by_id.get(pid)+ if p:+ d = Dep(pid, key, key + '.hint',+ DepState.OK if p.ok else DepState.MISSING, p.path if p.ok else '')+ if not req:+ # an optional tool must not block the build+ d.state = DepState.OK if p.ok else DepState.OK+ d.detail = p.path if p.ok else self.t('dep.optionalMissing')+ out.append(d)+ return out+# ---- repository download and updates (the SwiftUI app has these; parity matters) ----@@ -472,8 +544,16 @@ class Model(QObject):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']+ # On Windows the upstream script is started through the driver, which loads it as a+ # module and replaces the steps that assume a Mac (see nspb_qt/win/driver.py). The+ # options are identical, so the command line stays comparable between the platforms.+ if pu.IS_WIN:+ entry = ['-m', 'nspb_qt.win.driver']+ cwd = str(Path(__file__).resolve().parents[1])+ else:+ entry = [str(Path(self.repo_path, 'scripts', 'build_ipa_from_nsp.py'))]+ cwd = self.repo_path+ args = entry + [input_dir, '-k', self.keys_path, '--progress', 'lines']has_work_dir = self.supports_work_dir()if has_work_dir:args += ['--work-dir', work_dir]@@ -495,11 +575,25 @@ class Model(QObject):if droot:env['DOTNET_ROOT'] = drootenv['DOTNET_ROOT_ARM64'] = droot+ if pu.IS_WIN:+ # The shim folder goes first on PATH/PYTHONPATH so the tools the pipeline spawns by+ # name (xcrun, xcodebuild, which, dmsh_xlate, python3) resolve to the Windows+ # stand-ins, and the child interpreters load sitecustomize. Failing here stops the+ # build before it wastes time instead of twenty minutes in.+ try:+ from .win import shim as wshim+ 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')+ 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')+ env['NSPB_REPO'] = self.repo_pathdef work() -> None:ok = Falsetry:- self._proc = subprocess.Popen([py] + args, cwd=self.repo_path,+ self._proc = subprocess.Popen([py] + args, cwd=cwd,stdout=subprocess.PIPE, stderr=subprocess.STDOUT,text=True, errors='replace', bufsize=1, env=env,**pu.no_window_kwargs())diff --git a/frontend-qt/nspb_qt/win/__init__.py b/frontend-qt/nspb_qt/win/__init__.pynew file mode 100644index 00000000..967d49d1--- /dev/null+++ b/frontend-qt/nspb_qt/win/__init__.py@@ -0,0 +1,28 @@+"""The Windows build path: everything the Qt front end needs to produce an IPA on a PC.++This package is imported **only on Windows** (see `nspb_qt.model`). On macOS it is never+touched, so a Mac build behaves exactly as before; importing it here is still safe, because+no module in it runs a subprocess or reads a Windows-only path at import time.++The upstream pipeline (`scripts/build_ipa_from_nsp.py`) is not modified: `driver.py` loads it+as a module and replaces the functions that assume a Mac. `shim/` covers the calls that cross+process boundaries, where a function replacement cannot reach.+"""+from __future__ import annotations++#: Deployment target of the iOS app. `dm/ios/project.yml` says 26.0 (Metal 4), and the+#: cross-compiled objects must agree with it or the linker warns about platform versions.+IOS_DEPLOYMENT = '26.0'++#: CPU the host is compiled for. Matches the reference implementation that was verified on a+#: real device; a lower core would leave performance on the table, a higher one (a18) would+#: let clang emit instructions older iPads lack.+IOS_CPU = 'apple-a16'++#: Environment variable names this package sets for the build. They all carry the `NSPB_`+#: prefix so they cannot collide with the upstream script's own vocabulary.+ENV_TOOLCHAIN = 'NSPB_TOOLCHAIN_JSON'+ENV_LLVM = 'NSPB_LLVM_DIR'+ENV_SDK = 'NSPB_IOS_SDK'+ENV_METAL = 'NSPB_METAL_DIR'+ENV_PREFIX = 'NSPB_PREFIX'diff --git a/frontend-qt/nspb_qt/win/build_app.py b/frontend-qt/nspb_qt/win/build_app.pynew file mode 100644index 00000000..71a27993--- /dev/null+++ b/frontend-qt/nspb_qt/win/build_app.py@@ -0,0 +1,694 @@+"""The Windows replacement for `dm/ios/tools/build_ipa.sh`.++Same unsigned all-in-one IPA, without Xcode:++============================ ============================================================+`xcodegen` + `xcodebuild` LLVM clang per source file (`-target arm64-apple-ios26.0+ -isysroot <iPhoneOS SDK>`), linked by `ld64.lld`+`Launcher.swift` (SwiftUI) `ios/Launcher.m` (UIKit, same `dm_show_launcher` contract)+`actool` asset catalog loose PNGs named in `CFBundleIcons`, scaled with Pillow+`sips` / `plutil` Pillow / `plistlib`+`make -n -B dmhost` this repo's `dm/host/Makefile` rules, reproduced in+ `host_sources()` and **checked against the Makefile text** so an+ upstream change stops the build instead of silently dropping files+`sips` → app icon Pillow+`codesign` ad-hoc + entitle skipped, with a note: an unsigned IPA is re-signed by the+ sideloader anyway, and there is no `codesign` here+============================ ============================================================++The environment is the same one `build_ipa.sh` reads (`GAME`, `W`, `PATCHED`, `ROMFS`,+`MSL_IOS`, `AOC`, `GFXAPI`, `DM_*`), because `driver.py` builds it by mocking the upstream+call — so the two paths cannot drift in what they pass.+"""+from __future__ import annotations++import concurrent.futures as cf+import hashlib+import os+import plistlib+import re+import shutil+import subprocess+import sys+import time+from pathlib import Path++if __package__:+ from . import toolchain as tc+ from . import fix_ipa_modes+ from . import IOS_CPU, IOS_DEPLOYMENT+else: # pragma: no cover - script mode+ sys.path.insert(0, str(Path(__file__).resolve().parents[2]))+ from nspb_qt.win import toolchain as tc+ from nspb_qt.win import fix_ipa_modes+ from nspb_qt.win import IOS_CPU, IOS_DEPLOYMENT++HERE = Path(__file__).resolve().parent++#: Frameworks the app links. `Cocoa` is a macOS framework and is dropped; the rest is+#: `dm/host/Makefile`'s link line minus Cocoa, plus what the UIKit side and the launcher use+#: (Xcode would add UIKit through Swift module autolinking).+FRAMEWORKS_BASE = [+ 'QuartzCore', 'Metal', 'MetalFX', 'GameController', 'CoreHaptics', 'AudioToolbox',+ 'AVFAudio', 'VideoToolbox', 'CoreMedia', 'CoreVideo', 'ImageIO', 'UniformTypeIdentifiers',+ 'CoreMotion', 'CoreText', 'UIKit', 'Foundation', 'CoreGraphics', 'CoreFoundation',+ 'Security',+]++_IMPORT = re.compile(r'^\s*#\s*(?:import|include)\s*<(\w+)/', re.M)+++def t(msg: str) -> None:+ print(f'[{time.strftime("%H:%M:%S")}] {msg}', flush=True)+++def die(msg: str) -> None:+ t(f'FAIL: {msg}')+ raise SystemExit(1)+++def py(*args, env=None, capture=True) -> str:+ """Run one of the repository's own Python tools and return its stdout."""+ r = subprocess.run([sys.executable, *map(str, args)], capture_output=capture, text=True,+ env=env, errors='replace')+ if r.returncode:+ die(f'{Path(str(args[0])).name}: {(r.stderr or r.stdout or "").strip()[-2000:]}')+ return (r.stdout or '').strip() if capture else ''+++# ---------------------------------------------------------------- the source list++#: The two Makefile lines this module depends on. They are compared verbatim, because the+#: Makefile's wildcards are the only place the source list is maintained: if upstream adds a+#: file to either line, silently missing it here would produce a link error or a subtly+#: incomplete host.+WANT_SRC = ('SRC=main.c loader.c hle.c romfs_arc.c crash.c probe.c thread.c memstat.m '+ 'haptics_apple.m $(sort $(wildcard hle_*.c)) front_mac.m entry.S')+WANT_GFX = ('GFX=$(sort $(wildcard ../gfx/*.c ../gfx/nvn/*.c ../gfx/nvn/*.m ../gfx/nvn/*.S '+ '../gfx/tex/*.c ../gfx/tex/*.m ../gfx/vk/*.m ../gfx/gl/*.m))')+_GFX_PATS = ('../gfx/*.c', '../gfx/nvn/*.c', '../gfx/nvn/*.m', '../gfx/nvn/*.S',+ '../gfx/tex/*.c', '../gfx/tex/*.m', '../gfx/vk/*.m', '../gfx/gl/*.m')+++def host_sources(repo: Path, game_h_dir: Path) -> tuple[list[Path], list[Path]]:+ """(sources, include dirs) for the iOS host, as `make -n -B dmhost` would list them.++ The iOS build differs from the Mac host in three ways, all handled here and all visible in+ how `dm/ios/project.yml` + `gen_build.py` treat the same list:++ * `*_mac` sources are dropped: `front_mac.m` is the Mac front end, `front_ios.m` implements+ the same `front.h` for iOS.+ * `dm/ios/Sources` is excluded from the host walk: the iOS project compiles those itself.+ * `main.c` is compiled with `-Dmain=dm_main`, because `main.m` is the real entry point.+ """+ host = repo / 'dm' / 'host'+ try:+ mk = (host / 'Makefile').read_text(encoding='utf-8')+ except OSError as e:+ die(f'cannot read dm/host/Makefile: {e}')+ for want, what in ((WANT_SRC, 'SRC'), (WANT_GFX, 'GFX')):+ if want not in mk:+ die(f'dm/host/Makefile changed ({what}= line): update host_sources() in '+ f'frontend-qt/nspb_qt/win/build_app.py to match')++ src = [host / n for n in 'main.c loader.c hle.c romfs_arc.c crash.c probe.c thread.c '+ 'memstat.m haptics_apple.m'.split()]+ src += sorted(host.glob('hle_*.c'), key=lambda p: p.name)+ src += [host / 'front_mac.m', host / 'entry.S']+ gfx: list[Path] = []+ for pat in _GFX_PATS:+ d, g = pat.rsplit('/', 1)+ gfx += list((host / d).glob(g))+ # make's $(sort) orders words as text, which for these relative paths is plain string order+ gfx.sort(key=lambda p: os.path.relpath(p, host).replace('\\', '/'))++ vpx = repo / 'dm' / 'third_party' / 'libvpx'+ vpx_src = sorted(vpx.rglob('*.c'), key=lambda p: p.as_posix())++ incs = [repo / 'dm' / 'gfx' / 'nvn' / 'include',+ repo / 'dm' / 'third_party' / 'vulkan-headers' / 'include',+ game_h_dir, vpx, repo / 'dm' / 'third_party' / 'stb_vorbis', vpx / 'config']++ ios_sources = (repo / 'dm' / 'ios' / 'Sources').resolve()+ files: list[Path] = []+ for s in src + gfx + vpx_src:+ s = s.resolve()+ if not s.is_file():+ die(f'a source from dm/host/Makefile does not exist: {s}')+ if s.stem.endswith('_mac'):+ continue # Mac-only sources: front_ios.m implements front.h+ if s.parent == ios_sources:+ continue # compiled once, as iOS sources+ files.append(s)++ dirs: list[Path] = []+ for s in files:+ if s.parent not in dirs:+ dirs.append(s.parent)+ resolved_incs = [Path(i).resolve() for i in incs]+ return files, resolved_incs + [d for d in dirs if d not in resolved_incs]+++def framework_list(sdk: Path, files: list[Path]) -> list[str]:+ """The base list plus any framework a source imports that the SDK actually ships.++ Scanning the imports means a new `#import <SomethingNew/...>` in the host does not need a+ change here — the same reason the upstream build takes frameworks from the Makefile.+ """+ fw_dir = sdk / 'System' / 'Library' / 'Frameworks'+ out = list(FRAMEWORKS_BASE)+ for f in files:+ if f.suffix not in ('.m', '.c', '.h'):+ continue+ try:+ text = f.read_text(encoding='utf-8', errors='replace')+ except OSError:+ continue+ for name in _IMPORT.findall(text):+ if name not in out and (fw_dir / f'{name}.framework').is_dir():+ out.append(name)+ return [n for n in out if (fw_dir / f'{n}.framework').is_dir()]+++# ---------------------------------------------------------------- compile++def compat_rt_needed(clang: Path) -> bool:+ """Whether the Darwin compiler-rt is missing (LLVM's Windows release ships none).++ Without `libclang_rt.ios.a`, `@available` / `__builtin_available` produce an undefined+ `__isPlatformVersionAtLeast`, and every link fails. `ios/compat_rt.c` provides it through+ dyld's `_availability_version_check`, which every iOS this app runs on has.+ """+ if hasattr(compat_rt_needed, '_cache'):+ return compat_rt_needed._cache+ ok = False+ try:+ r = subprocess.run([str(clang), '-print-resource-dir'], capture_output=True, text=True,+ timeout=60)+ if r.returncode == 0:+ res = Path(r.stdout.strip())+ ok = not list(res.glob('lib/darwin/libclang_rt.ios.a'))+ except (OSError, subprocess.SubprocessError):+ ok = True+ compat_rt_needed._cache = ok+ return ok+++def common_flags(sdk: Path, incs: list[Path], deployment: str) -> list[str]:+ return ['-target', f'arm64-apple-ios{deployment}', '-isysroot', str(sdk),+ '-Os', f'-mcpu={IOS_CPU}', '-w', '-fno-common', '-DNS_BLOCK_ASSERTIONS=1',+ *[f'-I{i}' for i in incs]]+++def flags_for(path: Path, common: list[str], host_main: Path) -> list[str]:+ """Per-file flags, mirroring `dm/ios/project.yml`'s per-target settings."""+ if path == host_main:+ return common + ['-std=gnu11', '-Dmain=dm_main']+ if path.suffix == '.c':+ return common + ['-std=gnu11']+ if path.suffix == '.m':+ return common + ['-std=gnu11', '-fobjc-arc']+ if path.suffix == '.S':+ return common+ return []+++def _dep_newer(obj: Path) -> bool:+ """Whether a header recorded in the object's `.d` file is newer than the object."""+ d = obj.with_suffix('.d')+ if not d.is_file():+ return True+ try:+ mt = obj.stat().st_mtime+ text = d.read_text(errors='replace').replace('\\\n', ' ')+ except OSError:+ return True+ for dep in re.split(r'(?<!\\)\s+', text.split(':', 1)[-1]):+ dep = dep.replace('\\ ', ' ').strip()+ try:+ if dep and os.path.exists(dep) and os.path.getmtime(dep) > mt:+ return True+ except OSError:+ continue+ return False+++def compile_all(clang: Path, sdk: Path, files: list[Path], incs: list[Path],+ obj_dir: Path, deployment: str, extra: list[str] | None = None) -> list[Path]:+ """Compile every source, skipping objects whose inputs are unchanged.++ The key includes the full flag list, so changing the deployment target or a define+ invalidates every object instead of silently mixing ABIs.+ """+ common = common_flags(sdk, incs, deployment) + list(extra or [])+ obj_dir.mkdir(parents=True, exist_ok=True)+ jobs: list[tuple[Path, Path, list[str]]] = []+ objs: list[Path] = []+ uptodate = 0+ for f in files:+ flags = flags_for(f, common, _HOST_MAIN)+ if not flags:+ continue+ key = hashlib.sha256((str(f) + '\0' + '\0'.join(flags)).encode()).hexdigest()[:12]+ o = obj_dir / f'{f.stem}-{key}.o'+ objs.append(o)+ if o.exists() and o.stat().st_mtime >= f.stat().st_mtime and not _dep_newer(o):+ uptodate += 1+ continue+ jobs.append((f, o, flags))+ t(f'compile: {len(jobs)} of {len(objs)} files (clang, arm64-apple-ios{deployment})'+ + (f', {uptodate} up to date' if uptodate else ''))++ def one(job):+ f, o, flags = job+ d = o.with_suffix('.d')+ tmp = Path(str(o) + '.tmp')+ r = subprocess.run([str(clang), *flags, '-MMD', '-MF', str(d), '-c', str(f),+ '-o', str(tmp)], capture_output=True, text=True, errors='replace')+ if r.returncode == 0:+ try:+ os.replace(str(tmp), o)+ except OSError:+ try:+ tmp.unlink()+ except OSError:+ pass+ return f, None, f'cannot move {tmp} to {o}'+ return f, r, None++ bad = []+ with cf.ThreadPoolExecutor(max_workers=min(32, os.cpu_count() or 4)) as ex:+ for i, (f, r, err) in enumerate(ex.map(one, jobs), 1):+ if err:+ bad.append((f, err))+ elif r is not None and r.returncode:+ bad.append((f, r.stderr or r.stdout or ''))+ if i % 25 == 0 or i == len(jobs):+ t(f'compile: {i}/{len(jobs)}')+ if bad:+ for f, err in bad[:6]:+ lines = [ln for ln in err.splitlines() if 'error' in ln.lower()] or err.splitlines()[-6:]+ print(f'---- {f}\n' + '\n'.join(lines)[:3000], file=sys.stderr)+ die(f'{len(bad)} file(s) did not compile (see the errors above)')+ return objs+++#: `dm/host/main.c`, set by `main()` before compiling; the host's `main` becomes `dm_main` so+#: `main.m` owns the real entry point (as `dm/ios/project.yml` does with compilerFlags).+_HOST_MAIN: Path | None = None+++# ---------------------------------------------------------------- link++def link(clang: Path, sdk: Path, objs: list[Path], frameworks: list[str], out: Path,+ deployment: str, embed_flags: list[str], rt_obj: Path | None,+ lld_dir: Path | None) -> None:+ """Link the app, then prove the result is an unsigned iOS executable."""+ args = [str(clang), '-target', f'arm64-apple-ios{deployment}', '-isysroot', str(sdk),+ '-fuse-ld=lld', '-fobjc-arc', '-o', str(out), *map(str, objs),+ '-Wl,-rpath,@executable_path/Frameworks', '-lobjc',+ *[x for fw in frameworks for x in ('-framework', fw)], *embed_flags]+ if rt_obj:+ args.append(str(rt_obj))+ env = dict(os.environ)+ if lld_dir:+ env['PATH'] = str(lld_dir) + os.pathsep + env.get('PATH', '')+ t(f'link: {len(objs)} objects, {len(frameworks)} frameworks (ld64.lld)')+ r = subprocess.run(args, capture_output=True, text=True, errors='replace', env=env)+ if r.returncode:+ print((r.stderr or r.stdout)[-6000:], file=sys.stderr)+ die('link failed (see the linker output above)')+ check_executable(out)+++def check_executable(path: Path) -> None:+ """Reject a link output that is not a plain arm64 iOS executable.++ The reference implementation validates the same three properties, and they catch the two+ failure modes that matter here: a Mach-O that is not arm64 (the wrong `-target`) and one+ that carries a signature (a Windows LLD with `-no_adhoc_codesign` missing).+ """+ import struct+ data = path.read_bytes()+ magic, cputype, _sub, filetype = struct.unpack_from('<IIII', data, 0)+ if magic != tc.MACHO_MAGIC_64:+ die(f'{path.name} is not 64-bit Mach-O (magic 0x{magic:08x})')+ if cputype != tc.CPU_TYPE_ARM64:+ die(f'{path.name} is not arm64 (cputype 0x{cputype:08x})')+ if filetype != tc.MH_EXECUTE:+ die(f'{path.name} is not an executable (filetype {filetype})')+ plat = tc.macho_platform(data)+ if plat is not None and plat != tc.PLATFORM_IOS:+ die(f'{path.name} targets platform {plat}, not iOS')+++# ---------------------------------------------------------------- the bundle++ICONS = [('[email protected]', 120), ('[email protected]', 180),+ ('AppIcon76x76@2x~ipad.png', 152), ('AppIcon83.5x83.5@2x~ipad.png', 167),+ ('AppIcon.png', 1024)]+++def make_icons(src: Path, app: Path) -> bool:+ """Scale the game's icon into loose PNGs.++ Xcode would run `actool` over an asset catalog; on iOS a bundle may simply list loose PNG+ files in `CFBundleIcons`, which is what this does. Pillow is optional: without it the app+ still installs, it just has a blank home-screen icon.+ """+ try:+ from PIL import Image+ except ImportError:+ t('no app icon: Pillow is not installed (pip install pillow); the home-screen icon '+ 'stays blank')+ return False+ try:+ im = Image.open(src).convert('RGB')+ except Exception as e:+ t(f'no app icon: cannot read {src} ({e})')+ return False+ for name, px in ICONS:+ im.resize((px, px), Image.LANCZOS).save(app / name, 'PNG')+ t(f'app icon: {src}')+ return True+++def info_plist(*, bundle_id: str, name: str, version: str, category: str, show_fps: str,+ lang: str, sdk_ver: str, sdk_build: str, icons: bool, executable: str,+ deployment: str) -> dict:+ """`Info.plist` with the keys `dm/ios/project.yml` declares, in the same shape.++ Every key here has a reader in the app: `DMShowFPS` and `DMLanguage` in `main.m`,+ `CFBundleIcons` in the launcher, `LSApplicationCategoryType` in the App Store metadata.+ """+ p = {+ 'CFBundleDevelopmentRegion': 'en',+ 'CFBundleExecutable': executable,+ 'CFBundleIdentifier': bundle_id,+ 'CFBundleInfoDictionaryVersion': '6.0',+ 'CFBundleName': executable,+ 'CFBundleDisplayName': name,+ 'CFBundlePackageType': 'APPL',+ 'CFBundleShortVersionString': version,+ 'CFBundleVersion': version,+ 'CFBundleSupportedPlatforms': ['iPhoneOS'],+ 'DTPlatformName': 'iphoneos',+ 'DTPlatformVersion': sdk_ver,+ 'DTSDKName': f'iphoneos{sdk_ver}',+ 'DTSDKBuild': sdk_build,+ 'MinimumOSVersion': deployment,+ 'LSRequiresIPhoneOS': True,+ 'UIDeviceFamily': [1, 2],+ 'UIRequiredDeviceCapabilities': ['arm64'],+ 'UILaunchStoryboardName': '',+ 'UIFileSharingEnabled': True,+ 'LSSupportsOpeningDocumentsInPlace': True,+ 'UISupportedInterfaceOrientations': ['UIInterfaceOrientationLandscapeRight',+ 'UIInterfaceOrientationLandscapeLeft'],+ 'UISupportedInterfaceOrientations~ipad': ['UIInterfaceOrientationLandscapeRight',+ 'UIInterfaceOrientationLandscapeLeft'],+ 'UIRequiresFullScreen': True,+ 'UIStatusBarHidden': True,+ 'UIViewControllerBasedStatusBarAppearance': False,+ 'LSApplicationCategoryType': category,+ 'DMShowFPS': show_fps,+ 'DMLanguage': lang,+ 'LSSupportsGameMode': True,+ 'GCSupportsControllerUserInteraction': True,+ 'GCSupportedGameControllers': [{'ProfileName': 'ExtendedGamepad'}],+ 'CADisableMinimumFrameDurationOnPhone': True,+ 'UIApplicationSceneManifest': {+ 'UIApplicationSupportsMultipleScenes': False,+ 'UISceneConfigurations': {'UIWindowSceneSessionRoleApplication': [+ {'UISceneConfigurationName': 'Default',+ 'UISceneDelegateClassName': 'SceneDelegate'}]},+ },+ }+ if icons:+ p['CFBundleIcons'] = {'CFBundlePrimaryIcon': {+ 'CFBundleIconFiles': ['AppIcon60x60'], 'CFBundleIconName': 'AppIcon'}}+ p['CFBundleIcons~ipad'] = {'CFBundlePrimaryIcon': {+ 'CFBundleIconFiles': ['AppIcon60x60', 'AppIcon76x76', 'AppIcon83.5x83.5'],+ 'CFBundleIconName': 'AppIcon'}}+ if os.environ.get('DM_METAL_CAPTURE', '0') == '1':+ p['MetalCaptureEnabled'] = True+ return p+++# ---------------------------------------------------------------- main++def main(argv: list[str] | None = None) -> int:+ args = list(sys.argv[1:] if argv is None else argv)+ if '--prepare-xcode' in args:+ die('--prepare-xcode generates an Xcode project, which needs a Mac with Xcode and '+ 'xcodegen; on Windows the IPA is packed directly (drop the option)')+ env = os.environ+ repo = Path(env.get('NSPB_REPO') or Path(__file__).resolve().parents[3])++ game = env.get('GAME') or die('GAME is not set (the game profile ID)')+ w = Path(env.get('W') or die('W is not set (the work folder)'))+ sys.path.insert(0, str(repo / 'dm' / 'games'))+ try:+ import game as gm # noqa: N813 (the upstream module name)+ except ImportError as e:+ die(f'cannot import dm/games/game.py from {repo}: {e}')+ try:+ prof = gm.load(game)+ except Exception as e:+ die(f'no game profile {game}: {e}')+ gd = Path(prof.dir)+ gp = prof.get+ if not (gd / 'game.tsv').exists():+ die(f'no game profile {gd}/game.tsv')++ pkg = gp('package')+ patched = Path(env.get('PATCHED') or w / f'build/patched_{pkg}')+ romfs = Path(env.get('ROMFS') or w / f'data/{pkg}/RomFS')+ msl_ios = Path(env.get('MSL_IOS') or w / 'build/ios/dmsh_b')+ aoc = Path(env['AOC']) if env.get('AOC') else (None if 'AOC' in env else w / 'data/aoc')+ out_ipa = Path(args[0]) if args and not args[0].startswith('-') else \+ w.parent / gp('ipa')++ mods = gp('modules').split()+ marker = gp('romfs_marker')++ # --- inputs, checked with the same wording as build_ipa.sh+ for m in mods:+ if not ((patched / f'{m}.patched.bin').exists() and (patched / f'{m}.fixups.tsv').exists()):+ die(f'no rewritten module {patched}/{m} (the rewrite step must run first)')+ if not (romfs / marker).exists():+ die(f'no RomFS at {romfs} (missing {marker})')++ name = env.get('DM_DISPLAY_NAME') or ''+ if not name:+ nacp = w / 'data/v0/control.nacp'+ if not nacp.exists():+ nacp = romfs.parent / 'control.nacp'+ try:+ name = py(repo / 'dm/tools/nacp.py', nacp)+ except SystemExit:+ die(f'no game name in {nacp} (set DM_DISPLAY_NAME)')+ version = env.get('DM_APP_VERSION') or '1.0'+ bundle_id = env.get('DM_BUNDLE_ID') or f'org.nxnative.{game.lower()}'+ show_fps = env.get('DM_SHOW_FPS', '0') in ('1', 'YES', 'yes', 'TRUE', 'true')+ lang = env.get('DM_LANG') or 'en-US'+ category = gp('app_category') or 'public.app-category.games'++ # --- graphics API, exactly as build_ipa.sh decides it without GFXAPI+ hdr = (repo / 'dm/gfx/nvn/dmsh_chain.h').read_text(encoding='utf-8')+ m = re.search(r'^#define DMSH_CHAIN "(.*)"', hdr, re.M)+ if not m:+ die('no DMSH_CHAIN in dm/gfx/nvn/dmsh_chain.h')+ v = m.group(1)+ gfx = env.get('GFXAPI') or ''+ if gfx not in ('nvn', 'vulkan', 'gl'):+ if list((msl_ios / f'b-{v}').glob('*_b.metallib')):+ gfx = 'nvn'+ elif (msl_ios / 'vk/vk_shaders.metallib').exists():+ gfx = 'vulkan'+ elif (msl_ios / 'gl/gl_shaders.metallib').exists():+ gfx = 'gl'+ else:+ gfx = 'nvn'+ if gfx == 'vulkan':+ if not (msl_ios / 'vk/vk_shaders.metallib').exists():+ die(f'no iOS Vulkan shader library at {msl_ios}/vk (the shader step must run first)')+ msldir = 'vk'+ elif gfx == 'gl':+ if not (msl_ios / 'gl/gl_shaders.metallib').exists():+ die(f'no iOS GL shader library at {msl_ios}/gl (the shader step must run first)')+ msldir = 'gl'+ else:+ msldir = f'b-{v}'+ if not list((msl_ios / msldir).glob('*_b.metallib')):+ die(f'no iOS shader libraries at {msl_ios}/{msldir} (the shader step must run first)')+ # The stamp `dmsh_build.py` writes names the game and the digest of its profile's+ # shader inputs. `build_ipa.sh` compares both and refuses libraries from another+ # profile state; without the comparison a stale library set would be packed silently.+ inputs = py(repo / 'dm/gfx/tools/dmsh_chain.py', '--inputs',+ env=dict(env, DM_GAME=game))+ stamp = msl_ios / msldir / 'inputs.tsv'+ if inputs:+ lines = stamp.read_text(encoding='utf-8').splitlines() if stamp.exists() else []+ if f'game\t{game}' not in lines or f'inputs\t{inputs}' not in lines:+ die(f'the iOS shader libraries at {msl_ios}/{msldir} are not a full build from '+ f'this profile\'s current tables (inputs {inputs}): build them again')+ # c1_full.tsv is made by the same full build and names the digest; the host ignores a+ # table whose header does not match its library+ c1 = gd / 'c1_full.tsv'+ try:+ first = c1.read_text(encoding='utf-8').splitlines()[0]+ except (OSError, IndexError):+ first = ''+ if inputs and not first.startswith(f'# chain b-{v} inputs {inputs} '):+ die(f'{c1} is missing or not made from these libraries (chain {v}, inputs {inputs}): '+ 'a full shader build makes it')++ # --- the toolchain+ sdk = tc.ios_sdk() or die('no iPhoneOS SDK: download one in the app (Dependencies), or set '+ '"ios_sdk" in toolchain.json')+ clang = tc.llvm_tool('clang') or die('no clang.exe: install LLVM-MinGW (Dependencies)')+ lld, lld_note = tc.ensure_ld64_lld()+ if not lld:+ die(f'no Mach-O linker: {lld_note}')+ lld_dir = lld.parent+ sdk_ver, sdk_build = tc.sdk_version(sdk)+ deployment = tc.setting('ios_deployment', IOS_DEPLOYMENT)+ t(f'app: {name} {version} ({bundle_id}), language {lang}'+ f'{", frame-rate counter on" if show_fps else ""}; SDK {sdk.name} {sdk_ver} {sdk_build}')++ base = w / 'build/ios/win'+ gen, app = base / 'Gen', base / 'Payload/DmIOS.app'+ shutil.rmtree(gen, ignore_errors=True)+ shutil.rmtree(app, ignore_errors=True)+ (gen / 'profile').mkdir(parents=True)+ app.mkdir(parents=True)++ # --- generate Gen/ (the same generators build_ipa.sh calls)+ t('generate Gen/ (profile header, embedded modules, tables)')+ py(repo / 'dm/games/game.py', 'header', game, gen / 'profile/game_profile.h')+ es = gen / 'embed.S'+ flags = py(repo / 'dm/ios/tools/gen_embed.py', patched, es, *mods)+ # the assembler treats '\' as an escape in .incbin paths+ es.write_text(re.sub(r'\.incbin "([^"]*)"',+ lambda mm: '.incbin "' + mm.group(1).replace('\\', '/') + '"',+ es.read_text(encoding='utf-8')), encoding='utf-8')++ dmres = app / 'dm'+ dmres.mkdir()+ for pat in ('*.fixups.tsv', '*.gates.tsv', '*.cuts.tsv', '*.obs.tsv'):+ for f in patched.glob(pat):+ shutil.copy2(f, dmres)+ if (patched / 'nro.tsv').exists():+ shutil.copy2(patched / 'nro.tsv', dmres)+ # the tables the host reads at run time; c1_full is only for the NVN chain+ tables = ['shader_map.tsv', 'pso_manifest.tsv'] + ([] if gfx in ('vulkan', 'gl')+ else ['c1_full.tsv'])+ for f in tables:+ src = gd / f+ if not src.exists():+ die(f'no {src} in the game profile (the shader step must run first)')+ shutil.copy2(src, dmres)+ if gfx == 'nvn':+ if (gd / 'cb_extent.tsv').exists():+ shutil.copy2(gd / 'cb_extent.tsv', dmres)+ else:+ t(f'no {gd}/cb_extent.tsv: the host copies whole uniform bindings')+ for f in ('shader_pairs.tsv', 'pso_pairs.tsv'):+ if (gd / f).exists():+ shutil.copy2(gd / f, dmres)++ launcher = py(repo / 'dm/games/settings.py', game, patched,+ (romfs.parent / 'control.nacp') if (romfs.parent / 'control.nacp').exists()+ else (w / 'data/v0/control.nacp'),+ gen / 'launcher.json', env=dict(env, GFXAPI=gfx))+ shutil.copy2(gen / 'launcher.json', dmres / 'launcher.json')+ t(f'launcher: {launcher}')+ if env.get('DM_ENV_FILE'):+ shutil.copy2(env['DM_ENV_FILE'], dmres / 'env.txt')++ (dmres / 'font').mkdir()+ font = tc.std_font() or die('no standard font: set STD_FONT to a TTF with broad Unicode '+ 'coverage')+ shutil.copy2(font, dmres / 'font/standard.ttf')+ t(f'standard font: {font} (upstream copies macOS\'s Arial Unicode; Windows fonts have '+ f'different CJK coverage)')+ letter = tc.letter_font()+ if not letter:+ die('no bold TTF for the button icons: set LETTER_FONT')+ py(repo / 'dm/tools/make_ext_font.py', dmres / 'font/nintendo_ext.ttf', letter)++ # --- the source list and the compile+ global _HOST_MAIN+ _HOST_MAIN = (repo / 'dm/host/main.c').resolve()+ files, incs = host_sources(repo, gen / 'profile')+ ios_sources = sorted((repo / 'dm/ios/Sources').glob('*.m'))+ files += [p.resolve() for p in ios_sources]+ files.append((HERE / 'ios/Launcher.m').resolve())+ files.append(es.resolve())+ # our Launcher.m replaces Launcher.swift and adds no Swift file; nothing else to exclude+ frameworks = framework_list(sdk, files)++ rt_obj = None+ if compat_rt_needed(clang):+ rt_obj = base / 'compat_rt.o'+ rt_obj.parent.mkdir(parents=True, exist_ok=True)+ r = subprocess.run([str(clang), '-target', f'arm64-apple-ios{deployment}',+ '-isysroot', str(sdk), '-Os', '-c',+ str(HERE / 'ios' / 'compat_rt.c'), '-o', str(rt_obj)],+ capture_output=True, text=True, errors='replace')+ if r.returncode:+ print(r.stderr, file=sys.stderr)+ die('compat_rt.c did not compile (it stands in for Darwin\'s compiler-rt)')++ objs = compile_all(clang, sdk, files, incs, base / 'obj', deployment)+ link(clang, sdk, objs, frameworks, app / 'DmIOS', deployment,+ flags.split() if flags else [], rt_obj, lld_dir)++ # --- icon + Info.plist+ icon = Path(env.get('DM_ICON') or '')+ if not icon.is_file():+ icon = romfs.parent / 'icon.jpg'+ icons = icon.is_file() and make_icons(icon, app)+ if not icon.is_file():+ t(f'no app icon ({icon} not found): the home-screen icon stays blank')+ with open(app / 'Info.plist', 'wb') as f:+ plistlib.dump(info_plist(bundle_id=bundle_id, name=name, version=version,+ category=category, show_fps='YES' if show_fps else 'NO',+ lang=lang, sdk_ver=sdk_ver, sdk_build=sdk_build, icons=icons,+ executable='DmIOS', deployment=deployment),+ f, fmt=plistlib.FMT_BINARY)+ (app / 'PkgInfo').write_bytes(b'APPL????')++ # --- pack+ maps = [f'Payload/DmIOS.app={app}', f'Payload/DmIOS.app/msl/{msldir}={msl_ios / msldir}']+ if aoc and aoc.is_dir() and any(aoc.iterdir()):+ maps.append(f'Payload/DmIOS.app/aoc={aoc}')+ t('add-on content: ' + ' '.join(sorted(p.name for p in aoc.iterdir())))+ full = bool(env.get('DM_FULL_ROMFS'))+ if full:+ maps.append(f'Payload/DmIOS.app/romfs={romfs}')+ t('packing the full IPA with the RomFS (only sensible for small games)')+ else:+ t('packing a slim IPA without the RomFS (the game files come from Documents/romfs)')+ store = gp('zip_store') or ''+ t('pack IPA')+ pack = [sys.executable, str(repo / 'dm/ios/tools/pack_ipa.py'), str(out_ipa)]+ if store:+ pack += ['--store', ':'.join(store.split(':'))]+ pack += ['--skip', 'Payload/DmIOS.app/msl', '--skip', 'Payload/DmIOS.app/aoc',+ '--skip', 'Payload/DmIOS.app/romfs', *maps]+ r = subprocess.run(pack, capture_output=True, text=True, errors='replace')+ if r.returncode:+ print(((r.stdout or '') + (r.stderr or ''))[-3000:], file=sys.stderr)+ die('pack_ipa failed')+ # Windows has no Unix modes: pack_ipa writes 0o666 for every file, which an iOS install+ # tool may refuse to launch. Rewrite the executable's central-directory entry to 0755.+ fixed = fix_ipa_modes.fix(out_ipa, ['Payload/DmIOS.app/DmIOS'])+ t(f'IPA modes: {fixed}')+ t(f'done: {out_ipa} ({out_ipa.stat().st_size / 2**30:.2f} GiB)')+ return 0+++if __name__ == '__main__':+ raise SystemExit(main())diff --git a/frontend-qt/nspb_qt/win/doctor.py b/frontend-qt/nspb_qt/win/doctor.pynew file mode 100644index 00000000..7875ad9f--- /dev/null+++ b/frontend-qt/nspb_qt/win/doctor.py@@ -0,0 +1,149 @@+"""`python -m nspb_qt.win.doctor`: what the Windows build needs, and what is missing.++The app shows the same information in its Dependencies panel (`toolchain.check_all`); this+module is the command-line form, for a user who wants to check a machine before opening the GUI,+or to paste the result into a bug report.++Exit code 0 means every required component is present and its probe passed.++ python -m nspb_qt.win.doctor # human-readable+ python -m nspb_qt.win.doctor --json # machine-readable+ python -m nspb_qt.win.doctor --fix # download the pinned LLVM-MinGW when it is missing+ python -m nspb_qt.win.doctor --sdk # download the iPhoneOS SDK (git route)+ python -m nspb_qt.win.doctor --sdk-xip Xcode.xip+ python -m nspb_qt.win.doctor --import-sdk D:\\SDKs\\iPhoneOS26.0.sdk+"""+from __future__ import annotations++import argparse+import json+import os+import sys+from pathlib import Path++if __package__:+ from . import fetch, sdk_fetch, shim+ from . import toolchain as tc+else: # pragma: no cover - script mode+ sys.path.insert(0, str(Path(__file__).resolve().parents[2]))+ from nspb_qt.win import fetch, sdk_fetch, shim+ from nspb_qt.win import toolchain as tc++MARK = {'ok': 'ok ', 'missing': 'MISSING', 'wrong': 'WRONG'}+++def print_report(probes: list, as_json: bool) -> int:+ if as_json:+ print(json.dumps([{+ 'id': p.id, 'name': p.name, 'state': p.state, 'detail': p.detail,+ 'hint': p.hint, 'path': p.path, 'version': p.version, 'pinned': p.pinned,+ 'required': p.required,+ } for p in probes], indent=1))+ else:+ width = max((len(p.name) for p in probes), default=20)+ for p in probes:+ mark = MARK.get(p.state, p.state) if p.required else \+ ('ok ' if p.ok else 'n/a ')+ line = f'[{mark}] {p.name.ljust(width)} {p.detail}'+ if p.version:+ line += f' (have {p.version}, pinned {p.pinned})' if p.pinned else f' ({p.version})'+ print(line)+ if not p.ok and p.hint:+ print(f'{"":9}{"":{width}} → {p.hint}')+ bad = [p for p in probes if p.required and not p.ok]+ print()+ if bad:+ print(f'{len(bad)} required item(s) missing or unusable: '+ + ', '.join(p.name for p in bad))+ else:+ print('everything a Windows build needs is present')+ return 0 if not [p for p in probes if p.required and not p.ok] else 1+++def log(msg: str) -> None:+ print(msg, flush=True)+++def main(argv: list[str] | None = None) -> int:+ ap = argparse.ArgumentParser(prog='python -m nspb_qt.win.doctor',+ description='Check (and optionally fetch) the Windows build '+ 'toolchain.')+ ap.add_argument('--json', action='store_true', help='machine-readable output')+ ap.add_argument('--no-probe', action='store_true',+ help='skip the compile / link / Metal probes (faster, less conclusive)')+ ap.add_argument('--fix', action='store_true', help='download LLVM-MinGW when it is missing')+ ap.add_argument('--sdk', action='store_true', help='download the pinned iPhoneOS SDK (git)')+ ap.add_argument('--sdk-xip', metavar='XCODE_XIP', help='extract the SDK from an Xcode .xip')+ ap.add_argument('--import-sdk', metavar='FOLDER', help='use an iPhoneOS SDK you already have')+ a = ap.parse_args(sys.argv[1:] if argv is None else argv)++ if os.name != 'nt' and not os.environ.get('NSPB_ALLOW_NON_WINDOWS'):+ print('nspb_qt.win.doctor checks the Windows toolchain; on macOS the build uses Xcode. '+ '(Set NSPB_ALLOW_NON_WINDOWS=1 to run it anyway for testing.)', file=sys.stderr)+ return 2++ did = False+ if a.fix:+ try:+ fetch.install_llvm(log=log)+ did = True+ except fetch.DownloadError as e:+ print(f'cannot install LLVM-MinGW: {e}', file=sys.stderr)+ if a.sdk:+ try:+ sdk_fetch.clone_sdk(log=log)+ did = True+ except sdk_fetch.SdkError as e:+ print(f'cannot download the SDK: {e}', file=sys.stderr)+ if a.sdk_xip:+ try:+ sdk_fetch.extract_xip(Path(a.sdk_xip), log=log)+ did = True+ except sdk_fetch.SdkError as e:+ print(f'cannot extract {a.sdk_xip}: {e}', file=sys.stderr)+ if a.import_sdk:+ try:+ sdk_fetch.import_local(Path(a.import_sdk), log=log)+ did = True+ except sdk_fetch.SdkError as e:+ print(f'cannot import {a.import_sdk}: {e}', file=sys.stderr)++ if did and not a.json:+ print()++ # The probes run the real compilers, so they need the toolchain folders on PATH and the+ # env variables toolchain.py reads; building the same environment the app builds keeps+ # this report and the app's panel from disagreeing.+ env = shim.build_env()+ saved = {k: os.environ.get(k) for k in env}+ os.environ.update(env)+ try:+ probes = tc.check_all(deep=not a.no_probe)+ finally:+ for k, v in saved.items():+ if v is None:+ os.environ.pop(k, None)+ else:+ os.environ[k] = v++ code = print_report(probes, a.json)+ if not a.json:+ # what to do next, without repeating every row+ hints = []+ if not tc.llvm_dir():+ hints.append('install LLVM-MinGW: python -m nspb_qt.win.doctor --fix')+ if not tc.llvm_tool('ld64.lld') or not tc.ld64_lld():+ hints.append('the Mach-O linker is missing: it comes from ld.lld.exe, created '+ 'automatically once LLVM is in place')+ if not tc.ios_sdk():+ hints.append('get an iPhoneOS SDK: python -m nspb_qt.win.doctor --sdk '+ '(or --sdk-xip Xcode.xip)')+ if not (tc.metal_tool('metal') and tc.metal_tool('metallib')):+ hints.append(fetch.metal_tools_hint())+ for h in hints:+ print(f'- {h}')+ return code+++if __name__ == '__main__':+ raise SystemExit(main())diff --git a/frontend-qt/nspb_qt/win/driver.py b/frontend-qt/nspb_qt/win/driver.pynew file mode 100644index 00000000..8a58c4c5--- /dev/null+++ b/frontend-qt/nspb_qt/win/driver.py@@ -0,0 +1,318 @@+"""Run the upstream NSP→IPA pipeline on Windows without editing it.++`scripts/build_ipa_from_nsp.py` is an upstream file that the daily sync overwrites, so patching+it in place is not an option, and a PATH-only shim cannot work: the script imports `pwd` (a+POSIX-only module) at load time, and its app-build step shells out to a 187-line bash script+that calls `xcodegen`, `xcodebuild`, `sips`, `plutil`, `codesign` and `xattr`.++So this module loads the upstream file **as a module** and replaces the handful of functions+that assume a Mac, then calls its own `cli()`. Everything else — argument parsing, the NSP+handling, `nx_extract`, `patch_nso`, the shader split, the tables, the progress display, the+error reporting — runs exactly as on a Mac, which is what keeps the two platforms from drifting.++What gets replaced, and why:++======================== ==========================================================+`check_prereqs` Xcode/xcodegen/make are absent; the Windows toolchain is checked+ instead, with the same "what is missing and how to get it" shape.+`build_nx_extract` on Windows the .NET build emits `nx_extract.exe`, not `nx_extract`+`can_clone` no APFS: plain copies (`nx_extract` spends the disk, not the build)+`apple_silicon` no `sysctl`+`heap_check` boots the game in the Mac host; replaced by an estimate+`build_mac_host` the Mac host can never run here: refuses with a clear message+`toolchain` the shader cache key needs the Windows Metal compiler's version+`capture_shaders` / run-time shader capture boots the game in the Mac host: refused,+`capture_glslc` with the device-capture workflow explained+`mac_app` / `mac_run` Mac platforms: refused+`build_ipa.sh` replaced by `build_app.py` (through the shim, which also has to cover+ the child processes the pipeline starts)+======================== ==========================================================+"""+from __future__ import annotations++import importlib.util+import os+import shutil+import sys+import time+from pathlib import Path+from types import ModuleType++if __package__:+ from . import toolchain as tc+else: # pragma: no cover - script mode+ sys.path.insert(0, str(Path(__file__).resolve().parents[2]))+ from nspb_qt.win import toolchain as tc++#: The upstream `run()`, captured by `patch()` before the name is replaced.+_UPSTREAM_RUN = None++#: Options that exist upstream but cannot work on Windows, with the reason shown to the user.+REFUSED_OPTIONS = {+ '--prepare-xcode': 'generates an Xcode project, which needs Xcode and xcodegen (macOS only)',+ '--platform': 'only "--platform ios" builds on Windows: the mac platforms run the game in '+ 'the Mac host, which boots the game\'s arm64 code',+}+++def repo_dir() -> Path:+ return Path(__file__).resolve().parents[3]+++def load_upstream(repo: Path) -> ModuleType:+ """Load `scripts/build_ipa_from_nsp.py` as a module.++ Before executing it, `pwd` is given a Windows stand-in: the file imports it at module level+ and the only use is recovering HOME when the environment lacks one. The stand-in is+ installed by the shim's `sitecustomize`, so importing this module after `shim.install` has+ run is enough; when that did not happen, a minimal stub is registered here so the loader+ never fails on an import the rest of the file does not need.+ """+ if 'pwd' not in sys.modules:+ _install_pwd_stub()+ path = repo / 'scripts' / 'build_ipa_from_nsp.py'+ if not path.is_file():+ raise SystemExit(f'not a repository checkout: {path} is missing')+ spec = importlib.util.spec_from_file_location('nspb_upstream_build_ipa_from_nsp', path)+ if spec is None or spec.loader is None:+ raise SystemExit(f'cannot load {path}')+ mod = importlib.util.module_from_spec(spec)+ sys.modules[spec.name] = mod+ started = time.time()+ spec.loader.exec_module(mod)+ del started+ return mod+++def _install_pwd_stub() -> None:+ import types++ pwd = types.ModuleType('pwd')++ class struct_passwd(tuple):+ __slots__ = ()++ @property+ def pw_dir(self):+ return self[5]++ def getpwuid(uid):+ home = os.environ.get('USERPROFILE') or os.path.expanduser('~')+ name = os.environ.get('USERNAME') or 'user'+ return struct_passwd((name, 'x', uid if uid is not None else 0, 0, '', home, ''))++ pwd.struct_passwd = struct_passwd+ pwd.getpwuid = getpwuid+ pwd.getpwnam = lambda name: getpwuid(0)+ sys.modules['pwd'] = pwd+++def _option_value(argv: list[str], name: str) -> str | None:+ for i, a in enumerate(argv):+ if a == name and i + 1 < len(argv):+ return argv[i + 1]+ if a.startswith(name + '='):+ return a.split('=', 1)[1]+ return None+++def check_cli(argv: list[str]) -> None:+ """Refuse Mac-only options before any work starts, and say what to do instead."""+ for opt in REFUSED_OPTIONS:+ if opt in argv or any(a.startswith(opt + '=') for a in argv):+ if opt == '--platform':+ val = _option_value(argv, '--platform')+ if val in (None, 'ios'):+ continue+ raise SystemExit(f'nspb: --platform {val} needs macOS with Xcode: {REFUSED_OPTIONS[opt]}')+ raise SystemExit(f'nspb: {opt} {REFUSED_OPTIONS[opt]}')+++def patch(mod: ModuleType, repo: Path, *, j: int | None = None) -> None:+ """Replace the upstream functions that assume a Mac."""+ BuildError = mod.BuildError+ say = mod.say++ # The upstream `run()` is captured once, so `run_ipa` below can call it after replacing the+ # name. Capturing only the first time matters: a second `patch()` call (a re-patch, or a+ # test) would otherwise wrap `run_ipa` in itself and recurse until the stack dies.+ global _UPSTREAM_RUN+ if _UPSTREAM_RUN is None:+ _UPSTREAM_RUN = mod.run++ # ---------------------------------------------------------------- prereqs+ def check_prereqs(env, xlate, mac=False):+ if mac:+ raise BuildError('the Mac platforms need a Mac: only iOS builds run on Windows')+ bad = [p for p in tc.check_all(deep=True) if p.required and not p.ok]+ if bad:+ lines = [f'{p.name}: {p.state}'+ + (f' ({p.detail})' if p.detail else '')+ + (f' — get it: {p.hint}' if p.hint else '')+ for p in bad]+ raise BuildError('missing on this PC:\n ' + '\n '.join(lines)+ + '\n(the Dependencies panel in the app lists and fixes these)')+ if not Path(xlate).parent.is_dir():+ raise BuildError(f'the shader translator is missing from the repository: {xlate}')+ mod.check_prereqs = check_prereqs++ # ---------------------------------------------------------------- nx_extract+ def build_nx_extract(repo_: Path, work: Path, logs: Path, env):+ """The .NET build, but on Windows the output is `nx_extract.exe`."""+ import tempfile+ nx = work / 'tools/nx_extract/nx_extract'+ with tempfile.TemporaryDirectory(prefix='nx_extract_') as td:+ mod.run(['dotnet', 'build', repo_ / 'dm/tools/nx_extract', '-c', 'Release',+ '-o', td, '-v', 'quiet', '-nologo'],+ logs / 'nx_extract_build.log', env=env)+ exe = Path(td) / 'nx_extract.exe'+ if not exe.exists():+ raise BuildError(f'nx_extract built without nx_extract.exe (see '+ f'{logs / "nx_extract_build.log"})')+ mod.rmtree(nx.parent)+ shutil.copytree(td, nx.parent)+ return nx+ mod.build_nx_extract = build_nx_extract++ # ---------------------------------------------------------------- APFS clones+ mod.can_clone = lambda d: False+ mod.apple_silicon = lambda: True # only the heap estimate below asks++ # ---------------------------------------------------------------- the Mac host+ def build_mac_host(repo_, out, env, logs, g):+ raise BuildError(+ 'this step boots the game\'s own arm64 code in a Mac host, which no Windows PC can '+ 'run. It is needed only for a game whose shaders appear at run time (GLSLC / Vulkan / '+ 'GL capture), an Unreal or Oodle-packed game, or a heap check. Games whose shaders '+ 'are in the RomFS (Mario Wonder, Odyssey, Mario Kart 8 Deluxe, the Zelda games, …) '+ 'do not need it.')+ mod.build_mac_host = build_mac_host++ def heap_check(repo_, d, patched, work, env, logs, g):+ """The heap check without the Mac host.++ Upstream boots the game for a few seconds to read its heap request. Without that, a game+ with virtual address memory (an NPDM system resource) whose `nninitStartup` hands+ `pool - used` to StandardAllocator gets a 2 GB pool: the size that was measured to work+ with Unity titles, and small enough to leave the alias region room for the game's own+ allocations. The profile is stamped the same way upstream stamps it, so later builds+ keep the result instead of estimating again.+ """+ mod.PROG.stage('heap estimate (no Mac host)')+ sig = {}+ try:+ pool = int(g.get('app_pool', '0') or '0', 0)+ sysres = int(g.get('sys_resource', '0') or '0', 0)+ except ValueError:+ pool = sysres = 0+ if sysres and pool > 0x80000000:+ sig['app_pool'] = ('0x80000000',+ 'virtual address memory and no heap check on Windows: a 2 GB '+ 'pool, so StandardAllocator\'s region leaves the alias region '+ 'room for the game\'s own allocations')+ for k, (v, why) in sig.items():+ say(f'heap estimate: {k} {v}: {why}')+ if sig:+ g = mod.set_keys(g, sig, 'Heap estimate on Windows (no Mac host)')+ p = Path(g.dir) / 'game.tsv'+ p.write_text(p.read_text(encoding='utf-8')+ + f'\n# heap check: {time.strftime("%Y-%m-%d")}, estimated on Windows '+ 'without booting the game'+ + (f'; set {", ".join(sig)}' if sig else '') + '\n', encoding='utf-8')+ mod.PROG.end('set ' + ', '.join(sig) if sig else 'guessed keys kept')+ return type(g)(g.dir)+ mod.heap_check = heap_check++ # ---------------------------------------------------------------- the shader cache key+ def toolchain_probe():+ """What the shader-stage cache keys record as "the compilers".++ Upstream records `xcodebuild -version` and `spirv-cross --revision`. Here the Metal+ compiler's own version is what actually changes the output, so it is recorded instead;+ a Metal Tools upgrade then invalidates the cache, which is the behaviour we want.+ """+ xc = [sys.executable, str(Path(__file__).resolve().parent / 'xcrun_shim.py')]+ probes = [('cmd', [*xc, '-sdk', 'iphoneos', 'metal', '--version'])]+ if os.environ.get('NSPB_MAC_METAL'):+ probes.append(('cmd', [*xc, '-sdk', 'macosx', 'metal', '--version']))+ probes.append(('cmd', ['spirv-cross', '--revision']))+ return tuple(probes)+ mod.toolchain = toolchain_probe++ # ---------------------------------------------------------------- run-time capture+ def _refuse_capture(what: str):+ def fn(*a, **k):+ raise BuildError(+ f'{what} compiles its shaders at run time, and upstream captures them by '+ 'booting the game in the Mac host — which needs a Mac, or a Mac virtual '+ 'machine on this PC. The game\'s files are extracted, so a Mac can finish the '+ 'build from the same work folder (its shader/ and extract/ are reused).')+ return fn+ mod.capture_glslc = _refuse_capture('this game')+ mod.capture_shaders = _refuse_capture('this game')++ # ---------------------------------------------------------------- Mac outputs+ def mac_app(*a, **k):+ raise BuildError('--platform mac-app packs a macOS app: it needs a Mac')+ mod.mac_app = mac_app++ def mac_run(*a, **k):+ raise BuildError('--platform mac is a development build for this Mac: it needs a Mac')+ mod.mac_run = mac_run++ # ---------------------------------------------------------------- the tool paths+ # TOOL_PATHS is a macOS list; on Windows it is replaced outright with the folders the shim+ # needs, so the upstream value must not survive (a macOS path on Windows is harmless but+ # confusing in logs, and `/opt/homebrew/bin` as a PATH entry is dead weight).+ extra = []+ if llvm := tc.llvm_dir():+ extra.append(str(llvm / 'bin'))+ for name in ('spirv-cross', 'zstd', 'glslangValidator'):+ if p := tc.find_exe(name):+ extra.append(str(p.parent))+ pf = os.environ.get('ProgramFiles')+ if pf:+ extra.append(str(Path(pf) / 'dotnet'))+ mod.TOOL_PATHS = extra++ # ---------------------------------------------------------------- the app build+ def run_ipa(cmd, log, env=None, cwd=None, on_line=None):+ """Intercept the `bash dm/ios/tools/build_ipa.sh` call and run `build_app.py` instead.++ The signature matches upstream's `run()`, so the caller's logging, progress and error+ reporting are reused unchanged; only the command is swapped.+ """+ cmd = [str(c) for c in cmd]+ if (len(cmd) >= 2 and Path(cmd[0]).name in ('bash', 'sh')+ and cmd[1].replace('\\', '/').endswith('dm/ios/tools/build_ipa.sh')):+ if '--prepare-xcode' in cmd:+ raise BuildError('--prepare-xcode needs Xcode and xcodegen: drop it on Windows')+ cmd = [sys.executable, str(Path(__file__).resolve().parent / 'build_app.py'),+ *cmd[2:]]+ return _UPSTREAM_RUN(cmd, log, env=env, cwd=cwd, on_line=on_line)++ mod.run = run_ipa+++def main(argv: list[str] | None = None) -> int:+ """Entry point: check the CLI, build the environment, patch, and run upstream."""+ argv = list(sys.argv[1:] if argv is None else argv)+ check_cli(argv)+ repo = repo_dir()+ if os.name != 'nt' and not os.environ.get('NSPB_ALLOW_NON_WINDOWS'):+ raise SystemExit('nspb_qt.win.driver runs the Windows build; on macOS use '+ 'scripts/build_ipa_from_nsp.py')++ from . import shim+ env = shim.build_env(python_exe=sys.executable)+ os.environ.clear()+ os.environ.update(env)++ mod = load_upstream(repo)+ patch(mod, repo)+ sys.argv[0] = str(repo / 'scripts' / 'build_ipa_from_nsp.py')+ return mod.cli(argv)+++if __name__ == '__main__':+ raise SystemExit(main())diff --git a/frontend-qt/nspb_qt/win/fetch.py b/frontend-qt/nspb_qt/win/fetch.pynew file mode 100644index 00000000..134d6c7a--- /dev/null+++ b/frontend-qt/nspb_qt/win/fetch.py@@ -0,0 +1,205 @@+"""Download the pinned Windows toolchain artefacts, verifying their SHA-256.++Only the LLVM-MinGW archive is fetched here. The iPhoneOS SDK is *not* downloaded as a binary+blob: `xybp888/iOS-SDKs` is a git repository, so `sdk_fetch.clone_sdk` uses git's own transfer+with integrity checks, and Apple's `Xcode.xip` route needs an Apple ID login that cannot be+scripted. `Metal Developer Tools for Windows` likewise needs an Apple ID, so it is a link the+app shows rather than a silent download of something Apple does not publish for redirect.++Every download is checked against a hash pinned in `toolchain.py`. A mismatch is a hard stop:+the archive is deleted rather than unpacked, because a partially-correct toolchain produces+build failures that look like source bugs.+"""+from __future__ import annotations++import hashlib+import os+import shutil+import sys+import time+import urllib.error+import urllib.request+import zipfile+from pathlib import Path+from typing import Callable++if __package__:+ from . import toolchain as tc+else: # pragma: no cover - script mode+ sys.path.insert(0, str(Path(__file__).resolve().parents[2]))+ from nspb_qt.win import toolchain as tc+++class DownloadError(Exception):+ """A user-facing download failure with an actionable message."""+++def download(url: str, dest: Path, sha256: str, size: int | None = None,+ log: Callable[[str], None] | None = None,+ progress: Callable[[int, int], None] | None = None) -> Path:+ """Fetch `url` into `dest`, verifying length and SHA-256.++ Downloads to a `.part` file and renames on success, so an interrupted download never looks+ like a usable archive on the next start.+ """+ log = log or (lambda s: None)+ dest = Path(dest)+ dest.parent.mkdir(parents=True, exist_ok=True)+ if dest.is_file():+ got = sha256_of(dest)+ if got == sha256.lower():+ log(f'cached: {dest.name} ({got[:16]}…)')+ return dest+ log(f'{dest.name} has the wrong hash ({got[:16]}…): downloading again')+ dest.unlink()+ part = dest.with_suffix(dest.suffix + '.part')+ part.unlink(missing_ok=True)+ log(f'downloading {url}')+ h = hashlib.sha256()+ total = 0+ t0 = time.time()+ try:+ req = urllib.request.Request(url, headers={'User-Agent': 'NS-Port-Builder'})+ with urllib.request.urlopen(req, timeout=120) as r, open(part, 'wb') as f:+ expected = int(r.headers.get('Content-Length') or 0) or (size or 0)+ while True:+ chunk = r.read(1 << 20)+ if not chunk:+ break+ f.write(chunk)+ h.update(chunk)+ total += len(chunk)+ if progress:+ progress(total, expected)+ elif expected and total % (32 << 20) < (1 << 20):+ log(f' {total / 2**20:.0f} / {expected / 2**20:.0f} MiB'+ f' ({100 * total / expected:.0f}%)')+ except urllib.error.HTTPError as e:+ part.unlink(missing_ok=True)+ raise DownloadError(f'HTTP {e.code} for {url}: the release may have moved; check '+ 'github.com/mstorsjo/llvm-mingw/releases') from e+ except (urllib.error.URLError, OSError) as e:+ part.unlink(missing_ok=True)+ raise DownloadError(f'cannot download {url}: {e}') from e+ got = h.hexdigest()+ if got != sha256.lower():+ part.unlink(missing_ok=True)+ raise DownloadError(+ f'the downloaded {dest.name} does not match the pinned SHA-256:\n'+ f' expected {sha256.lower()}\n got {got}\n'+ 'The download was deleted. If this repeats, the release was replaced upstream: '+ 'set "llvm_dir" in toolchain.json to an existing install instead.')+ if size and total != size:+ part.unlink(missing_ok=True)+ raise DownloadError(f'{dest.name} is {total} bytes, expected {size}')+ part.replace(dest)+ log(f'downloaded {dest.name} ({total / 2**20:.0f} MiB in {time.time() - t0:.0f} s, '+ f'sha256 {got[:16]}…)')+ return dest+++def sha256_of(path: Path, limit: int | None = None) -> str:+ h = hashlib.sha256()+ left = limit+ with open(path, 'rb') as f:+ while True:+ n = 1 << 20 if left is None else min(1 << 20, left)+ if n <= 0:+ break+ b = f.read(n)+ if not b:+ break+ h.update(b)+ if left is not None:+ left -= len(b)+ return h.hexdigest()+++def _strip_root(member: str) -> str:+ """The zip's members all sit under one top-level folder; return the path below it."""+ parts = member.split('/', 1)+ return parts[1] if len(parts) > 1 else ''+++def install_llvm(arch: str | None = None, dest: Path | None = None,+ log: Callable[[str], None] | None = None,+ progress: Callable[[int, int], None] | None = None) -> Path:+ """Download and unpack LLVM-MinGW, then make the Mach-O linker available.++ After unpacking, `ld64.lld.exe` is created from `ld.lld.exe`: llvm-mingw's release script+ removes the named Mach-O driver, but LLD selects its driver from `argv[0]`, so the same+ binary under that name links Mach-O. `toolchain.ensure_ld64_lld` performs that step and is+ called here so the folder is complete the moment the download finishes.+ """+ log = log or (lambda s: None)+ asset = tc.download_asset(arch)+ base = Path(dest or (Path(__file__).resolve().parents[2]))+ target = base / '.tools' / f'llvm-mingw-{tc.LLVM_MINGW_VERSION}'+ if (target / 'bin' / 'clang.exe').is_file():+ log(f'LLVM-MinGW already installed: {target}')+ else:+ cache = base / '.tools' / 'downloads'+ zpath = download(asset['url'], cache / asset['name'], asset['sha256'], asset['size'],+ log=log, progress=progress)+ log(f'unpacking {zpath.name} → {target} (about 1 GiB on disk)')+ staging = base / '.tools' / f'.unpack-{tc.LLVM_MINGW_VERSION}'+ shutil.rmtree(staging, ignore_errors=True)+ staging.mkdir(parents=True)+ try:+ with zipfile.ZipFile(zpath) as z:+ bad = z.testzip()+ if bad:+ raise DownloadError(f'{zpath.name} is corrupt (first bad member: {bad})')+ for info in z.infolist():+ if info.is_dir():+ continue+ rel = _strip_root(info.filename)+ if not rel:+ continue+ out = staging / rel+ out.parent.mkdir(parents=True, exist_ok=True)+ with z.open(info) as src, open(out, 'wb') as dst:+ shutil.copyfileobj(src, dst, 1 << 20)+ # the zip stores no Unix modes: mark everything in bin/ executable+ if out.parent.name == 'bin':+ try:+ out.chmod(0o755)+ except OSError:+ pass+ except zipfile.BadZipFile as e:+ shutil.rmtree(staging, ignore_errors=True)+ raise DownloadError(f'{zpath.name} is not a valid zip: {e}') from e+ # the archive's single top folder becomes our versioned folder+ inner = [p for p in staging.iterdir()]+ if len(inner) == 1 and inner[0].is_dir():+ staging = inner[0]+ shutil.rmtree(target, ignore_errors=True)+ target.parent.mkdir(parents=True, exist_ok=True)+ staging.replace(target)+ log(f'LLVM-MinGW {tc.LLVM_MINGW_VERSION} installed: {target}')+ # make the Mach-O linker available in this brand-new folder+ old = {k: os.environ.get(k) for k in ('NSPB_LLVM_DIR',)}+ os.environ['NSPB_LLVM_DIR'] = str(target)+ try:+ lld, note = tc.ensure_ld64_lld()+ finally:+ for k, v in old.items():+ if v is None:+ os.environ.pop(k, None)+ else:+ os.environ[k] = v+ if not lld:+ raise DownloadError(f'LLVM-MinGW unpacked but has no usable Mach-O linker: {note}')+ log(note or f'Mach-O linker: {lld}')+ return target+++def metal_tools_hint() -> str:+ return (f'Apple "Metal Developer Tools for Windows" {tc.METAL_TOOLS_VERSION}: '+ f'{tc.METAL_TOOLS_URL}')+++def sdk_hint() -> str:+ return (f'the app downloads {tc.SDK_PINNED} from {tc.SDK_REPO}, or use your own '+ 'Xcode .xip (needs a free Apple ID)')+diff --git a/frontend-qt/nspb_qt/win/fix_ipa_modes.py b/frontend-qt/nspb_qt/win/fix_ipa_modes.pynew file mode 100644index 00000000..6eaeb488--- /dev/null+++ b/frontend-qt/nspb_qt/win/fix_ipa_modes.py@@ -0,0 +1,214 @@+"""Give the IPA's executable the Unix mode bits an iOS install tool expects.++`dm/ios/tools/pack_ipa.py` takes each entry's mode from `os.stat()`, which on a Mac gives+`0o100755` for the app binary and `0o100644` for data files. On Windows `os.stat()` reports+`0o666` for everything — no execute bit at all — so the packed `DmIOS` would look like a plain+data file. Sideloading tools differ in how strictly they check, but a bundle whose main+executable is not executable is not something to ship and hope about.++Two constraints shaped this module:++* **`dm/ios/tools/pack_ipa.py` must not be edited** (it is an upstream file that the daily sync+ overwrites). Its Windows counterpart in the reference implementation added an `--exec`+ argument; ours has no such hook.+* **The IPA can be many gigabytes**, and the executable sits at an arbitrary offset, so a full+ rewrite of the archive would double the disk cost and the time.++So the fix is surgical: locate the central directory, rewrite the mode field of the named+entries in place, and leave every other byte alone. The local file headers carry no mode+(that lives only in the central directory), so one small write per entry is the whole job.+"""+from __future__ import annotations++import os+import stat+import struct+from pathlib import Path++EOCD_SIG = b'PK\x05\x06'+ZIP64_LOCATOR_SIG = b'PK\x06\x07'+ZIP64_EOCD_SIG = b'PK\x06\x06'+CDH_SIG = b'PK\x01\x02'++#: What `stat` reports on a Mac for these files, written the same way Info-ZIP writes them.+MODE_EXEC = stat.S_IFREG | 0o755+MODE_FILE = stat.S_IFREG | 0o644+MODE_DIR = stat.S_IFDIR | 0o755++#: Where the mode lives inside a central-directory header: 16 bytes of signature+version flags,+#: then 10 numeric fields, then the attribute words.+_CD_MODE_OFFSET = 38 # offset of the 4-byte external-attributes field+_CD_MODE_IN_ATTRS = 16 # the mode is in the high 16 bits of external attributes+++class IpaModeError(Exception):+ """The archive is not shaped the way this module expects; the message says which part."""+++def _find_eocd(f, size: int) -> tuple[int, int, int, int]:+ """(eocd_offset, entry_count, cd_size, cd_offset), following the zip64 records when present."""+ tail_len = min(size, 66_000) # the comment field is at most 64 KiB+ f.seek(size - tail_len)+ tail = f.read(tail_len)+ i = tail.rfind(EOCD_SIG)+ if i < 0:+ raise IpaModeError('no end-of-central-directory record: not a zip (or a truncated one)')+ eocd = size - tail_len + i+ (count,) = struct.unpack_from('<H', tail, i + 10)+ cd_size, cd_off = struct.unpack_from('<II', tail, i + 12)+ if count == 0xFFFF or cd_size == 0xFFFFFFFF or cd_off == 0xFFFFFFFF:+ # zip64: the real values sit in the zip64 EOCD, reachable through a fixed-size locator+ loc = eocd - 20+ if loc >= 0:+ f.seek(loc)+ rec = f.read(20)+ if len(rec) == 20 and rec[:4] == ZIP64_LOCATOR_SIG:+ z_off, = struct.unpack_from('<Q', rec, 8)+ f.seek(z_off)+ z = f.read(56)+ if len(z) == 56 and z[:4] == ZIP64_EOCD_SIG:+ count, cd_size, cd_off = struct.unpack_from('<QQQ', z, 32)+ return eocd, count, cd_size, cd_off+++def fix(path: os.PathLike | str, executables: list[str], *, dry_run: bool = False) -> str:+ """Rewrite the mode bits of `executables` to 0755 and every other file to 0644.++ Returns a one-line summary for the build log. Idempotent: an archive that is already+ correct is not written to at all.+ """+ path = Path(path)+ size = path.stat().st_size+ if size < 22:+ raise IpaModeError(f'{path} is too small to be a zip')+ exec_set = {e.strip('/') for e in executables}+ wanted: dict[str, int] = {}+ with open(path, 'r+b') as f:+ _eocd, count, cd_size, cd_off = _find_eocd(f, size)+ if count and cd_off + cd_size > size:+ raise IpaModeError(f'the central directory ends past the file ({cd_off + cd_size} > '+ f'{size}): the archive is truncated')+ f.seek(cd_off)+ cd = f.read(cd_size)+ pos = 0+ seen = 0+ for _ in range(count):+ if pos + 46 > len(cd) or cd[pos:pos + 4] != CDH_SIG:+ raise IpaModeError(f'bad central-directory entry #{seen + 1} at offset {pos}')+ name_len, extra_len, comment_len = struct.unpack_from('<HHH', cd, pos + 28)+ name = cd[pos + 46:pos + 46 + name_len].decode('utf-8', 'surrogateescape')+ (attrs,) = struct.unpack_from('<I', cd, pos + _CD_MODE_OFFSET)+ (created_by,) = struct.unpack_from('<H', cd, pos + 4)+ cur = (attrs >> _CD_MODE_IN_ATTRS) & 0xFFFF+ is_dir = name.endswith('/')+ if is_dir:+ want = MODE_DIR+ elif name in exec_set:+ want = MODE_EXEC+ elif _mode_is_meaningful(cur, created_by):+ # a Mac (or a Unix zip) already wrote a real mode: leave it exactly as it is+ want = cur+ else:+ want = MODE_FILE+ if want != cur:+ wanted[name] = want+ pos += 46 + name_len + extra_len + comment_len+ seen += 1+ if dry_run or not wanted:+ return (f'{len(wanted)} entr{"y" if len(wanted) == 1 else "ies"} would change'+ if dry_run else 'already correct')+ # rewrite just the attribute word of each affected entry+ for name, mode in wanted.items():+ off = _entry_attr_offset(cd, count, name)+ if off is None:+ continue+ f.seek(cd_off + off)+ attrs, = struct.unpack('<I', f.read(4))+ new = (attrs & 0x0000FFFF) | ((mode & 0xFFFF) << _CD_MODE_IN_ATTRS)+ f.seek(cd_off + off)+ f.write(struct.pack('<I', new))+ missing = exec_set - set(_all_names(path))+ note = f'; missing from the archive: {", ".join(sorted(missing))}' if missing else ''+ return (f'{len(wanted)} entr{"y" if len(wanted) == 1 else "ies"} set to their Unix modes '+ f'({", ".join(sorted(wanted))[:200]}){note}')+++def _mode_is_meaningful(mode: int, created_by: int) -> bool:+ """Whether a central-directory mode is a real Unix mode worth keeping.++ Three kinds of value turn up in the wild:++ * a Unix zip (`create_system` 3, a Mac) writes `0o100644` / `0o100755` with the file-type+ bits set — keep it;+ * `pack_ipa.py` on Windows derives the mode from `os.stat()`, which reports `0o666` with no+ type bits — there is nothing to keep, so a data file becomes 0644;+ * Python's `zipfile.writestr` defaults to `0o600` with the type bits set, which would make+ every game file owner-only. That is also not a decision anyone made, so it is repaired.++ A directory entry or an explicitly executable file is handled by the caller before this,+ so this only decides the ordinary-file case.+ """+ if mode == 0 or not mode & 0o777:+ return False+ if created_by >> 8 != 3:+ return False # not created on Unix: no Unix mode to trust+ if not mode & 0o170000:+ return False # 0o666-style, straight from os.stat() on Windows+ if mode & 0o777 == 0o600:+ return False # zipfile's default, not a choice+ return True+++def _entry_attr_offset(cd: bytes, count: int, name: str) -> int | None:+ pos = 0+ for _ in range(count):+ if pos + 46 > len(cd) or cd[pos:pos + 4] != CDH_SIG:+ return None+ name_len, extra_len, comment_len = struct.unpack_from('<HHH', cd, pos + 28)+ this = cd[pos + 46:pos + 46 + name_len].decode('utf-8', 'surrogateescape')+ if this == name:+ return pos + _CD_MODE_OFFSET+ pos += 46 + name_len + extra_len + comment_len+ return None+++def _all_names(path: Path) -> list[str]:+ size = path.stat().st_size+ out: list[str] = []+ with open(path, 'rb') as f:+ _eocd, count, cd_size, cd_off = _find_eocd(f, size)+ f.seek(cd_off)+ cd = f.read(cd_size)+ pos = 0+ for _ in range(count):+ if pos + 46 > len(cd) or cd[pos:pos + 4] != CDH_SIG:+ break+ name_len, extra_len, comment_len = struct.unpack_from('<HHH', cd, pos + 28)+ out.append(cd[pos + 46:pos + 46 + name_len].decode('utf-8', 'surrogateescape'))+ pos += 46 + name_len + extra_len + comment_len+ return out+++def verify(path: os.PathLike | str, executables: list[str]) -> tuple[bool, str]:+ """Check that the named entries carry an execute bit (what the build asserts afterwards)."""+ path = Path(path)+ exec_set = {e.strip('/') for e in executables}+ size = path.stat().st_size+ with open(path, 'rb') as f:+ _eocd, count, cd_size, cd_off = _find_eocd(f, size)+ f.seek(cd_off)+ cd = f.read(cd_size)+ pos = 0+ for _ in range(count):+ if pos + 46 > len(cd) or cd[pos:pos + 4] != CDH_SIG:+ return False, 'central directory is malformed'+ name_len, extra_len, comment_len = struct.unpack_from('<HHH', cd, pos + 28)+ name = cd[pos + 46:pos + 46 + name_len].decode('utf-8', 'surrogateescape')+ if name in exec_set:+ attrs, = struct.unpack_from('<I', cd, pos + _CD_MODE_OFFSET)+ mode = (attrs >> _CD_MODE_IN_ATTRS) & 0xFFFF+ if not mode & 0o111:+ return False, f'{name} has mode {oct(mode)}, no execute bit'+ return True, f'{name} is {oct(mode)}'+ pos += 46 + name_len + extra_len + comment_len+ return False, f'none of {sorted(exec_set)} is in the archive'diff --git a/frontend-qt/nspb_qt/win/ios/Launcher.m b/frontend-qt/nspb_qt/win/ios/Launcher.mnew file mode 100644index 00000000..9a44a594--- /dev/null+++ b/frontend-qt/nspb_qt/win/ios/Launcher.m@@ -0,0 +1,651 @@+// Launcher for the Windows build: a UIKit port of dm/ios/Sources/Launcher.swift (SwiftUI), so+// the app builds with clang alone and needs no Swift toolchain.+//+// The contract is unchanged: dm_show_launcher(view_controller, done) shows the settings screen+// over the root view controller, puts every setting into the environment when Play is pressed,+// then calls done(). It returns false (and does not call done) when there is no launcher: no+// dm/launcher.json, DM_LAUNCHER=0, or a file it cannot read — front_ios.m then starts the game+// at once.+//+// The JSON comes from dm/games/settings.py, which is the same file the Swift launcher reads, so+// every field the Swift model decodes must be honoured here:+//+// env the environment variable the setting sets (required)+// kind "choice" (options [[value, label]]), "range" (min / max / step, shown as a+// percentage) or "toggle" (on / off - the two values the variable takes; "1" / "0"+// when absent)+// label the row's title (required)+// note the section footer explaining the setting (required, may be empty)+// default the shipped value (required)+// section the heading the row sits under; older bundles have none, then it is "Game"+// on/off a toggle's two values+//+// Behaviour that the Swift side has and a naive port would lose:+// * a variable set by an env file (Documents/env.txt, the bundle's dm/env.txt; main.m lists+// them in DM_ENV_FILE_KEYS) is shown but kept - the row is disabled and the note says so;+// * only a value that differs from the game's default is saved, so a setting the player left+// alone follows the defaults of a later build;+// * "Reset to tested defaults" forgets every saved choice;+// * rows are grouped into sections, in the order they first appear.+#import <UIKit/UIKit.h>+#import <os/proc.h>+#include <stdio.h>+#include <stdlib.h>+#include <string.h>++#pragma mark - model++@interface NspbSetting : NSObject+@property (copy) NSString *env, *kind, *label, *note, *def, *section;+@property (copy) NSArray<NSArray<NSString *> *> *options; // choice: [value, label]+@property (copy) NSString *on, *off; // toggle values, resolved+@property double min, max, step;+@property BOOL hasMin, hasMax, hasStep;+@end++@implementation NspbSetting+- (NSString *)sectionTitle { return self.section.length ? self.section : @"Game"; }+- (NSString *)onValue { return self.on.length ? self.on : @"1"; }+- (NSString *)offValue { return self.off.length ? self.off : @"0"; }++// A range compares as numbers (a slider writes "1.00" for 1.0), as Setting.isDefault does.+- (BOOL)isDefault:(NSString *)v {+ if ([self.kind isEqualToString:@"range"]) {+ double a = v.doubleValue, b = self.def.doubleValue;+ return fabs(a - b) < 1e-6;+ }+ return [v isEqualToString:self.def] ? YES : NO;+}++// A saved value is only offered back when the game still lists it.+- (BOOL)accepts:(NSString *)v {+ if ([self.kind isEqualToString:@"choice"]) {+ for (NSArray<NSString *> *o in self.options)+ if ([o[0] isEqualToString:v]) return YES;+ return NO;+ }+ if ([self.kind isEqualToString:@"range"]) {+ if (!self.hasMin || !self.hasMax) return NO;+ double n = v.doubleValue;+ return isfinite(n) && n >= self.min && n <= self.max;+ }+ if ([self.kind isEqualToString:@"toggle"])+ return [v isEqualToString:self.onValue] || [v isEqualToString:self.offValue];+ return YES;+}+@end++static NSString *nspb_str(NSDictionary *d, NSString *k) {+ id v = d[k];+ return [v isKindOfClass:NSString.class] ? v : nil;+}++static NSArray<NspbSetting *> *nspb_load_settings(NSData *data) {+ id root = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];+ if (![root isKindOfClass:NSDictionary.class] || ![root[@"settings"] isKindOfClass:NSArray.class])+ return nil;+ NSMutableArray<NspbSetting *> *out = [NSMutableArray array];+ for (NSDictionary *d in root[@"settings"]) {+ if (![d isKindOfClass:NSDictionary.class]) return nil;+ NspbSetting *s = [NspbSetting new];+ s.env = nspb_str(d, @"env");+ s.kind = nspb_str(d, @"kind");+ s.label = nspb_str(d, @"label");+ s.note = nspb_str(d, @"note");+ s.def = nspb_str(d, @"default");+ s.section = nspb_str(d, @"section");+ s.on = nspb_str(d, @"on");+ s.off = nspb_str(d, @"off");+ // env, kind, label, note and default are all required by the Swift Decodable+ if (!s.env || !s.kind || !s.label || !s.note || !s.def) return nil;+ if ([d[@"options"] isKindOfClass:NSArray.class]) {+ NSMutableArray<NSArray<NSString *> *> *opts = [NSMutableArray array];+ for (id o in d[@"options"]) {+ if (![o isKindOfClass:NSArray.class] || [o count] < 2 ||+ ![o[0] isKindOfClass:NSString.class] || ![o[1] isKindOfClass:NSString.class])+ return nil;+ [opts addObject:@[o[0], o[1]]];+ }+ s.options = opts;+ }+ if ([d[@"min"] isKindOfClass:NSNumber.class]) { s.min = [d[@"min"] doubleValue]; s.hasMin = YES; }+ if ([d[@"max"] isKindOfClass:NSNumber.class]) { s.max = [d[@"max"] doubleValue]; s.hasMax = YES; }+ if ([d[@"step"] isKindOfClass:NSNumber.class]) { s.step = [d[@"step"] doubleValue]; s.hasStep = YES; }+ [out addObject:s];+ }+ return out;+}++@interface NspbModel : NSObject+@property (strong) NSArray<NspbSetting *> *settings;+@property (strong) NSArray<NSString *> *sections;+@property (strong) NSSet<NSString *> *fromFile; // set by an env file: shown, not changed+@property (strong) NSMutableDictionary<NSString *, NSString *> *values;+@property (strong) NSUserDefaults *defaults;+- (instancetype)initWith:(NSArray<NspbSetting *> *)settings;+- (BOOL)changed;+- (void)reset;+- (void)apply;+@end++@implementation NspbModel+- (instancetype)initWith:(NSArray<NspbSetting *> *)settings {+ if (!(self = [super init])) return nil;+ _settings = settings;+ _values = [NSMutableDictionary dictionary];+ _defaults = NSUserDefaults.standardUserDefaults;+ NSString *keys = NSProcessInfo.processInfo.environment[@"DM_ENV_FILE_KEYS"] ?: @"";+ NSMutableSet<NSString *> *ff = [NSMutableSet set];+ for (NSString *k in [keys componentsSeparatedByString:@" "])+ if (k.length) [ff addObject:k];+ _fromFile = ff;+ NSMutableArray<NSString *> *sections = [NSMutableArray array];+ for (NspbSetting *s in settings) {+ NSString *v = nil;+ NSString *envv = NSProcessInfo.processInfo.environment[s.env];+ if ([ff containsObject:s.env] && envv) {+ v = envv;+ } else {+ NSString *saved = [_defaults stringForKey:[@"launcher." stringByAppendingString:s.env]];+ v = (saved && [s accepts:saved]) ? saved : s.def;+ }+ _values[s.env] = v;+ if (![sections containsObject:s.sectionTitle]) [sections addObject:s.sectionTitle];+ }+ _sections = sections;+ return self;+}++- (NSString *)value:(NspbSetting *)s { return self.values[s.env] ?: s.def; }+- (BOOL)locked:(NspbSetting *)s { return [self.fromFile containsObject:s.env]; }++- (NSString *)noteFor:(NspbSetting *)s {+ if (![self locked:s]) return s.note;+ NSString *suffix = @"Set by an env file";+ return s.note.length ? [NSString stringWithFormat:@"%@ · %@", s.note, suffix] : suffix;+}++- (BOOL)changed {+ for (NspbSetting *s in self.settings) {+ if ([self.fromFile containsObject:s.env]) continue;+ if (![s isDefault:[self value:s]]) return YES;+ }+ return NO;+}++- (void)reset {+ for (NspbSetting *s in self.settings) {+ [self.defaults removeObjectForKey:[@"launcher." stringByAppendingString:s.env]];+ if (![self.fromFile containsObject:s.env]) self.values[s.env] = s.def;+ }+ fprintf(stderr, "launcher: settings reset to the game's defaults\n");+}++- (void)apply {+ for (NspbSetting *s in self.settings) {+ NSString *v = [self value:s];+ if ([self.fromFile containsObject:s.env]) {+ fprintf(stderr, "launcher: %s kept at %s (env file)\n", s.env.UTF8String, v.UTF8String);+ continue;+ }+ NSString *key = [@"launcher." stringByAppendingString:s.env];+ if ([s isDefault:v]) [self.defaults removeObjectForKey:key];+ else [self.defaults setObject:v forKey:key];+ setenv(s.env.UTF8String, v.UTF8String, 1);+ fprintf(stderr, "launcher: %s=%s%s\n", s.env.UTF8String, v.UTF8String,+ [s isDefault:v] ? "" : " (changed)");+ }+}+@end++#pragma mark - views++static UILabel *nspb_body(NSString *text) {+ UILabel *l = [UILabel new];+ l.text = text;+ l.font = [UIFont preferredFontForTextStyle:UIFontTextStyleBody];+ l.numberOfLines = 0;+ l.translatesAutoresizingMaskIntoConstraints = NO;+ [l setContentHuggingPriority:UILayoutPriorityRequired forAxis:UILayoutConstraintAxisHorizontal];+ return l;+}++static UILabel *nspb_value(NSString *text) {+ UILabel *l = [UILabel new];+ l.text = text;+ l.textColor = UIColor.secondaryLabelColor;+ l.font = [UIFont monospacedDigitSystemFontOfSize:+ [UIFont preferredFontForTextStyle:UIFontTextStyleBody].pointSize+ weight:UIFontWeightRegular];+ l.translatesAutoresizingMaskIntoConstraints = NO;+ return l;+}++// A settings row: label (+ its note) on the left, the control on the right.+@interface NspbRowCell : UITableViewCell+@end++@implementation NspbRowCell+- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuse {+ return [super initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];+}+@end++@interface NspbSettingsVC : UITableViewController+@property (strong) NspbModel *m;+@property (copy) void (^onReset)(void);+@property (strong) NSTimer *timer;+@property (strong) UILabel *memory;+@end++@implementation NspbSettingsVC++- (NSInteger)numberOfSectionsInTableView:(UITableView *)tv { return (NSInteger)self.m.sections.count + 2; }++- (NSInteger)tableView:(UITableView *)tv numberOfRowsInSection:(NSInteger)sec {+ if (sec < (NSInteger)self.m.sections.count) {+ return (NSInteger)[self rowsInSection:sec].count;+ }+ return 1; // reset row, then the memory row+}++- (NSArray<NspbSetting *> *)rowsInSection:(NSInteger)sec {+ NSString *title = self.m.sections[(NSUInteger)sec];+ NSMutableArray<NspbSetting *> *rows = [NSMutableArray array];+ for (NspbSetting *s in self.m.settings)+ if ([s.sectionTitle isEqualToString:title]) [rows addObject:s];+ return rows;+}++- (NSString *)tableView:(UITableView *)tv titleForHeaderInSection:(NSInteger)sec {+ if (sec < (NSInteger)self.m.sections.count) return self.m.sections[(NSUInteger)sec];+ return nil;+}++- (NSString *)tableView:(UITableView *)tv titleForFooterInSection:(NSInteger)sec {+ if (sec < (NSInteger)self.m.sections.count) {+ NSArray<NspbSetting *> *rows = [self rowsInSection:sec];+ NSMutableArray<NSString *> *notes = [NSMutableArray array];+ for (NspbSetting *s in rows) {+ NSString *n = [self.m noteFor:s];+ if (n.length) [notes addObject:n];+ }+ return notes.count ? [notes componentsJoinedByString:@"\n"] : nil;+ }+ if (sec == (NSInteger)self.m.sections.count)+ return @"Brings back all settings this game was tested with.";+ return nil;+}++- (UITableViewCell *)tableView:(UITableView *)tv cellForRowAtIndexPath:(NSIndexPath *)ip {+ UITableViewCell *c = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault+ reuseIdentifier:nil];+ c.selectionStyle = UITableViewCellSelectionStyleNone;+ c.backgroundColor = UIColor.secondarySystemGroupedBackgroundColor;+ UIView *v = c.contentView;+ UILayoutGuide *g = v.layoutMarginsGuide;++ if (ip.section >= (NSInteger)self.m.sections.count) {+ if (ip.section == (NSInteger)self.m.sections.count) { // Reset to tested defaults+ c.textLabel.text = @"Reset to tested defaults";+ c.textLabel.textColor = UIColor.linkColor;+ c.textLabel.enabled = [self.m changed];+ c.selectionStyle = [self.m changed] ? UITableViewCellSelectionStyleDefault+ : UITableViewCellSelectionStyleNone;+ return c;+ }+ UILabel *l = nspb_body(@"Memory available"); // the same live figure as Launcher.swift+ self.memory = nspb_value([NSByteCountFormatter+ stringFromByteCount:(long long)os_proc_available_memory()+ countStyle:NSByteCountFormatterCountStyleMemory]);+ [v addSubview:l]; [v addSubview:self.memory];+ [NSLayoutConstraint activateConstraints:@[+ [l.leadingAnchor constraintEqualToAnchor:g.leadingAnchor],+ [l.centerYAnchor constraintEqualToAnchor:v.centerYAnchor],+ [self.memory.trailingAnchor constraintEqualToAnchor:g.trailingAnchor],+ [self.memory.centerYAnchor constraintEqualToAnchor:v.centerYAnchor],+ [v.heightAnchor constraintGreaterThanOrEqualToConstant:52]]];+ return c;+ }++ NspbSetting *s = [self rowsInSection:ip.section][(NSUInteger)ip.row];+ BOOL locked = [self.m locked:s];+ UILabel *l = nspb_body(s.label);+ [v addSubview:l];+ NSMutableArray<NSLayoutConstraint *> *cs = [@[+ [l.leadingAnchor constraintEqualToAnchor:g.leadingAnchor],+ [l.centerYAnchor constraintEqualToAnchor:v.centerYAnchor],+ [v.heightAnchor constraintGreaterThanOrEqualToConstant:52]] mutableCopy];++ if ([s.kind isEqualToString:@"choice"]) {+ UIButtonConfiguration *cfg = [UIButtonConfiguration plainButtonConfiguration];+ NSString *cur = [self.m value:s];+ NSString *label = cur;+ for (NSArray<NSString *> *o in s.options)+ if ([o[0] isEqualToString:cur]) { label = o[1]; break; }+ cfg.title = label;+ cfg.baseForegroundColor = UIColor.secondaryLabelColor;+ cfg.image = [UIImage systemImageNamed:@"chevron.up.chevron.down"+ withConfiguration:[UIImageSymbolConfiguration+ configurationWithPointSize:12+ weight:UIImageSymbolWeightSemibold]];+ cfg.imagePlacement = NSDirectionalRectEdgeTrailing;+ cfg.imagePadding = 5;+ cfg.contentInsets = NSDirectionalEdgeInsetsMake(6, 6, 6, 0);+ cfg.titleTextAttributesTransformer = ^NSDictionary *(NSDictionary *a) {+ NSMutableDictionary *m = [a mutableCopy];+ m[NSFontAttributeName] = [UIFont preferredFontForTextStyle:UIFontTextStyleBody];+ return m;+ };+ UIButton *b = [UIButton buttonWithConfiguration:cfg primaryAction:nil];+ b.showsMenuAsPrimaryAction = YES;+ b.changesSelectionAsPrimaryAction = NO;+ b.enabled = !locked;+ if (!locked) b.menu = [self menuFor:s button:b];+ b.translatesAutoresizingMaskIntoConstraints = NO;+ [v addSubview:b];+ [cs addObjectsFromArray:@[+ [b.trailingAnchor constraintEqualToAnchor:g.trailingAnchor],+ [b.centerYAnchor constraintEqualToAnchor:v.centerYAnchor],+ [b.leadingAnchor constraintGreaterThanOrEqualToAnchor:l.trailingAnchor constant:12]]];+ } else if ([s.kind isEqualToString:@"range"]) {+ UISlider *sl = [UISlider new];+ sl.translatesAutoresizingMaskIntoConstraints = NO;+ sl.minimumValue = s.hasMin ? s.min : 0;+ sl.maximumValue = s.hasMax ? s.max : 1;+ sl.value = [self.m value:s].doubleValue;+ sl.enabled = !locked;+ sl.accessibilityLabel = s.label;+ sl.tag = ip.section * 1000 + ip.row;+ [sl addTarget:self action:@selector(slid:) forControlEvents:UIControlEventValueChanged];+ UILabel *pct = nspb_value([self percentage:s]);+ pct.tag = sl.tag;+ [v addSubview:sl]; [v addSubview:pct];+ [cs addObjectsFromArray:@[+ [sl.leadingAnchor constraintEqualToAnchor:l.trailingAnchor constant:12],+ [sl.centerYAnchor constraintEqualToAnchor:v.centerYAnchor],+ [pct.leadingAnchor constraintEqualToAnchor:sl.trailingAnchor constant:12],+ [pct.widthAnchor constraintEqualToConstant:56],+ [pct.trailingAnchor constraintEqualToAnchor:g.trailingAnchor],+ [pct.centerYAnchor constraintEqualToAnchor:v.centerYAnchor],+ [sl.widthAnchor constraintGreaterThanOrEqualToConstant:120]]];+ } else {+ UISwitch *sw = [UISwitch new];+ sw.on = [[self.m value:s] isEqualToString:[s onValue]];+ sw.enabled = !locked;+ sw.tag = ip.section * 1000 + ip.row;+ sw.translatesAutoresizingMaskIntoConstraints = NO;+ [sw addTarget:self action:@selector(toggled:) forControlEvents:UIControlEventValueChanged];+ [v addSubview:sw];+ [cs addObjectsFromArray:@[+ [sw.trailingAnchor constraintEqualToAnchor:g.trailingAnchor],+ [sw.centerYAnchor constraintEqualToAnchor:v.centerYAnchor]]];+ }+ [NSLayoutConstraint activateConstraints:cs];+ if (locked) l.textColor = UIColor.tertiaryLabelColor;+ return c;+}++- (NspbSetting *)settingAt:(NSInteger)tag {+ NSInteger sec = tag / 1000, row = tag % 1000;+ if (sec < 0 || sec >= (NSInteger)self.m.sections.count) return nil;+ NSArray<NspbSetting *> *rows = [self rowsInSection:sec];+ if (row < 0 || row >= (NSInteger)rows.count) return nil;+ return rows[(NSUInteger)row];+}++- (NSString *)percentage:(NspbSetting *)s {+ return [NSString stringWithFormat:@"%ld %%", (long)lround([self.m value:s].doubleValue * 100)];+}++- (UIMenu *)menuFor:(NspbSetting *)s button:(UIButton *)b {+ NSMutableArray<UIAction *> *items = [NSMutableArray array];+ NSString *cur = [self.m value:s];+ __weak NspbSettingsVC *w = self;+ __weak UIButton *wb = b;+ for (NSArray<NSString *> *o in s.options) {+ UIAction *a = [UIAction actionWithTitle:o[1] image:nil identifier:nil+ handler:^(UIAction *__unused act) {+ NspbSettingsVC *me = w;+ if (!me) return;+ me.m.values[s.env] = o[0];+ UIButtonConfiguration *cfg = wb.configuration;+ cfg.title = o[1];+ wb.configuration = cfg;+ wb.menu = [me menuFor:s button:wb];+ // the reset row becomes enabled as soon as something differs from the default+ [me.tableView reloadSections:[NSIndexSet indexSetWithIndex:(NSUInteger)me.m.sections.count]+ withRowAnimation:UITableViewRowAnimationNone];+ }];+ a.state = [o[0] isEqualToString:cur] ? UIMenuElementStateOn : UIMenuElementStateOff;+ [items addObject:a];+ }+ return [UIMenu menuWithTitle:@"" image:nil identifier:nil+ options:UIMenuOptionsSingleSelection+ children:items];+}++- (void)slid:(UISlider *)sl {+ NspbSetting *s = [self settingAt:sl.tag];+ if (!s) return;+ double step = s.hasStep ? s.step : 0.05, lo = s.hasMin ? s.min : 0;+ double v = step > 0 ? lo + round((sl.value - lo) / step) * step : sl.value; // SwiftUI snaps the same way+ self.m.values[s.env] = [NSString stringWithFormat:@"%.2f", v];+ UILabel *pct = [sl.superview viewWithTag:sl.tag];+ pct.text = [self percentage:s];+ sl.accessibilityValue = pct.text;+ sl.value = (float)v;+}++- (void)toggled:(UISwitch *)sw {+ NspbSetting *s = [self settingAt:sw.tag];+ if (!s) return;+ self.m.values[s.env] = sw.on ? [s onValue] : [s offValue];+}++- (void)tableView:(UITableView *)tv didSelectRowAtIndexPath:(NSIndexPath *)ip {+ [tv deselectRowAtIndexPath:ip animated:YES];+ if (ip.section != (NSInteger)self.m.sections.count) return;+ if (![self.m changed]) return;+ [self.m reset];+ [tv reloadData];+ if (self.onReset) self.onReset();+}++- (void)viewDidLoad {+ [super viewDidLoad];+ self.tableView.backgroundColor = UIColor.clearColor;+ self.tableView.rowHeight = UITableViewAutomaticDimension;+ self.tableView.estimatedRowHeight = 52;+ __weak NspbSettingsVC *w = self;+ self.timer = [NSTimer scheduledTimerWithTimeInterval:2 repeats:YES block:^(NSTimer *__unused timer) {+ NspbSettingsVC *me = w;+ if (!me) return;+ me.memory.text = [NSByteCountFormatter+ stringFromByteCount:(long long)os_proc_available_memory()+ countStyle:NSByteCountFormatterCountStyleMemory];+ }];+}++- (void)dealloc { [self.timer invalidate]; }+@end++// The screen: the game card on the left third, the settings list on the right two thirds -+// the geometry of Launcher.swift's HStack.+@interface NspbLauncherVC : UIViewController+@property (strong) NspbModel *m;+@property (copy) void (^play)(void);+@end++@implementation NspbLauncherVC++static id nspb_info(NSString *k) { return [NSBundle.mainBundle objectForInfoDictionaryKey:k]; }++static UIImage *nspb_app_icon(void) {+ UIImage *i = [UIImage imageNamed:@"AppIcon"];+ if (i) return i;+ NSDictionary *icons = nspb_info(@"CFBundleIcons");+ NSArray *files = [icons isKindOfClass:NSDictionary.class]+ ? icons[@"CFBundlePrimaryIcon"][@"CFBundleIconFiles"] : nil;+ for (NSString *f in [files reverseObjectEnumerator]) {+ UIImage *im = [f isKindOfClass:NSString.class] ? [UIImage imageNamed:f] : nil;+ if (im) return im;+ }+ return [UIImage imageNamed:@"AppIcon60x60"];+}++- (void)viewDidLoad {+ [super viewDidLoad];+ self.overrideUserInterfaceStyle = UIUserInterfaceStyleDark;+ self.view.backgroundColor = UIColor.blackColor;++ // ---- left: icon, name, version, Play+ UIStackView *card = [UIStackView new];+ card.axis = UILayoutConstraintAxisVertical;+ card.alignment = UIStackViewAlignmentCenter;+ card.spacing = 16;+ UIImage *icon = nspb_app_icon();+ if (icon) {+ UIImageView *iv = [[UIImageView alloc] initWithImage:icon];+ iv.layer.cornerRadius = 22;+ iv.layer.cornerCurve = kCACornerCurveContinuous;+ iv.clipsToBounds = YES;+ iv.isAccessibilityElement = NO;+ [iv.widthAnchor constraintEqualToConstant:96].active = YES;+ [iv.heightAnchor constraintEqualToConstant:96].active = YES;+ [card addArrangedSubview:iv];+ }+ UILabel *name = [UILabel new];+ id disp = nspb_info(@"CFBundleDisplayName");+ name.text = [disp isKindOfClass:NSString.class] ? disp : @"Game";+ name.numberOfLines = 0;+ name.textAlignment = NSTextAlignmentCenter;+ UIFontDescriptor *fd = [[UIFont preferredFontForTextStyle:UIFontTextStyleTitle1].fontDescriptor+ fontDescriptorWithSymbolicTraits:UIFontDescriptorTraitBold];+ name.font = [UIFont fontWithDescriptor:fd size:0];+ [card addArrangedSubview:name];+ UILabel *ver = [UILabel new];+ id verstr = nspb_info(@"CFBundleShortVersionString");+ ver.text = [NSString stringWithFormat:@"Version %@",+ [verstr isKindOfClass:NSString.class] ? verstr : @""];+ ver.font = [UIFont preferredFontForTextStyle:UIFontTextStyleCallout];+ ver.textColor = UIColor.secondaryLabelColor;+ [card addArrangedSubview:ver];++ // iOS 26's .glassProminent, selected the way Launcher.swift does it (the API is newer than+ // the deployment target some builds use), else the filled style.+ UIButtonConfiguration *cfg = nil;+ SEL glass = NSSelectorFromString(@"prominentGlassButtonConfiguration");+ if ([UIButtonConfiguration respondsToSelector:glass]) {+ cfg = ((UIButtonConfiguration *(*)(id, SEL))+ [UIButtonConfiguration methodForSelector:glass])(UIButtonConfiguration.class, glass);+ }+ if (!cfg) cfg = [UIButtonConfiguration filledButtonConfiguration];+ cfg.buttonSize = UIButtonConfigurationSizeLarge;+ cfg.cornerStyle = UIButtonConfigurationCornerStyleCapsule;+ UIFontDescriptor *pd = [[UIFont preferredFontForTextStyle:UIFontTextStyleTitle3].fontDescriptor+ fontDescriptorWithSymbolicTraits:UIFontDescriptorTraitBold];+ cfg.attributedTitle = [[NSAttributedString alloc]+ initWithString:@"Play"+ attributes:@{NSFontAttributeName:+ [UIFont fontWithDescriptor:pd size:0]}];+ __weak NspbLauncherVC *w = self;+ UIButton *play = [UIButton buttonWithConfiguration:cfg+ primaryAction:[UIAction actionWithHandler:^(UIAction *__unused a) {+ NspbLauncherVC *me = w;+ if (me.play) me.play();+ }]];+ [play.widthAnchor constraintEqualToConstant:220].active = YES;+ [card addArrangedSubview:play];+ [card setCustomSpacing:20 afterView:ver];+ card.translatesAutoresizingMaskIntoConstraints = NO;+ [self.view addSubview:card];++ // ---- right: the settings+ NspbSettingsVC *list = [[NspbSettingsVC alloc] initWithStyle:UITableViewStyleInsetGrouped];+ list.m = self.m;+ list.onReset = ^{+ fprintf(stderr, "launcher: reset tapped\n");+ };+ [self addChildViewController:list];+ list.view.translatesAutoresizingMaskIntoConstraints = NO;+ [self.view addSubview:list.view];+ [list didMoveToParentViewController:self];++ UIView *v = self.view;+ // two side-by-side halves, as Launcher.swift's HStack: the list takes the right two thirds+ // and the card centres inside the left third+ UILayoutGuide *left = [UILayoutGuide new];+ [v addLayoutGuide:left];+ [NSLayoutConstraint activateConstraints:@[+ [list.view.topAnchor constraintEqualToAnchor:v.topAnchor],+ [list.view.bottomAnchor constraintEqualToAnchor:v.bottomAnchor],+ [list.view.trailingAnchor constraintEqualToAnchor:v.safeAreaLayoutGuide.trailingAnchor],+ [list.view.widthAnchor constraintEqualToAnchor:v.safeAreaLayoutGuide.widthAnchor+ multiplier:2.0 / 3.0],+ [left.leadingAnchor constraintEqualToAnchor:v.safeAreaLayoutGuide.leadingAnchor],+ [left.trailingAnchor constraintEqualToAnchor:list.view.leadingAnchor],+ [card.centerXAnchor constraintEqualToAnchor:left.centerXAnchor],+ [card.centerYAnchor constraintEqualToAnchor:v.centerYAnchor],+ [card.widthAnchor constraintLessThanOrEqualToAnchor:left.widthAnchor constant:-32]]];+}++- (UIInterfaceOrientationMask)supportedInterfaceOrientations { return UIInterfaceOrientationMaskLandscape; }+- (BOOL)prefersStatusBarHidden { return YES; }+- (BOOL)prefersHomeIndicatorAutoHidden { return YES; }+@end++#pragma mark - entry point++// A capture IPA (the run-time shader capture done on the device instead of a Mac) sets+// DM_GLSLC_CAPTURE / DM_VK_CAPTURE / DM_GL_CAPTURE in its dm/env.txt to a folder relative to+// Documents, which is the working directory at that point. The Vulkan and GL captures write+// into the folder without creating it, so it is made here, before the game starts.+static void nspb_make_capture_folders(void) {+ static const char *const keys[] = {"DM_GLSLC_CAPTURE", "DM_VK_CAPTURE", "DM_GL_CAPTURE"};+ for (int i = 0; i < 3; i++) {+ const char *k = keys[i], *d = getenv(k);+ if (d && *d) {+ [NSFileManager.defaultManager createDirectoryAtPath:@(d)+ withIntermediateDirectories:YES+ attributes:nil+ error:nil];+ fprintf(stderr, "capture: %s → Documents/%s\n", k, d);+ }+ }+}++bool dm_show_launcher(void *view_controller, void (*done)(void)) {+ nspb_make_capture_folders();+ const char *off = getenv("DM_LAUNCHER");+ if (off && !strcmp(off, "0")) {+ fprintf(stderr, "launcher: off (DM_LAUNCHER=0)\n");+ return false;+ }+ NSString *path = [[NSBundle.mainBundle.resourcePath stringByAppendingPathComponent:@"dm"]+ stringByAppendingPathComponent:@"launcher.json"];+ NSData *data = [NSData dataWithContentsOfFile:path];+ if (!data) return false;+ NSArray<NspbSetting *> *settings = nspb_load_settings(data);+ if (!settings.count) {+ fprintf(stderr, "[RED] launcher: dm/launcher.json cannot be read; starting the game\n");+ return false;+ }+ UIViewController *parent = (__bridge UIViewController *)view_controller;+ NspbModel *model = [[NspbModel alloc] initWith:settings];+ NspbLauncherVC *vc = [NspbLauncherVC new];+ vc.m = model;+ vc.modalPresentationStyle = UIModalPresentationFullScreen;+ __weak NspbLauncherVC *wvc = vc;+ __block BOOL started = NO;+ vc.play = ^{+ NspbLauncherVC *me = wvc;+ if (started || !me) return;+ started = YES;+ [model apply];+ [me dismissViewControllerAnimated:NO completion:^{ done(); }];+ };+ [parent presentViewController:vc animated:NO completion:nil];+ fprintf(stderr, "launcher: %lu settings shown\n", (unsigned long)settings.count);+ return true;+}diff --git a/frontend-qt/nspb_qt/win/ios/compat_rt.c b/frontend-qt/nspb_qt/win/ios/compat_rt.cnew file mode 100644index 00000000..3356a309--- /dev/null+++ b/frontend-qt/nspb_qt/win/ios/compat_rt.c@@ -0,0 +1,37 @@+// Stand-in for the part of Darwin's compiler-rt (libclang_rt.ios.a) that C / Objective-C code+// reaches through @available / __builtin_available.+//+// LLVM's Windows release ships no Darwin runtime libraries, so a target of the form+// arm64-apple-ios* has no libclang_rt.ios.a. When the source uses `@available(iOS 26, *)` the+// compiler emits a call to __isPlatformVersionAtLeast, and without the runtime library the link+// fails with an undefined symbol that says nothing about the real cause.+//+// This repository's own code does not use @available today, so this file is usually not linked.+// build_app.py checks the clang resource directory and only compiles it in when the Darwin+// runtime is genuinely absent — that way a future `@available` in the host does not turn into an+// unexplained link error, and nothing changes on a toolchain that does ship the runtime.+//+// Semantics follow compiler-rt's os_version_check.c on current systems: ask dyld through+// _availability_version_check (libSystem, iOS 15 and later), which every iOS this app can run on+// provides.+#include <stdint.h>++typedef uint32_t dyld_platform_t;+typedef struct { dyld_platform_t platform; uint32_t version; } dyld_build_version_t;++extern _Bool _availability_version_check(uint32_t count, dyld_build_version_t versions[]);++static uint32_t pack(uint32_t major, uint32_t minor, uint32_t sub) {+ return (major << 16) | ((minor & 0xff) << 8) | (sub & 0xff);+}++int32_t __isPlatformVersionAtLeast(uint32_t platform, uint32_t major, uint32_t minor,+ uint32_t sub) {+ dyld_build_version_t v = {platform, pack(major, minor, sub)};+ return _availability_version_check(1, &v);+}++// The older entry point, for the platform the binary was built for (2 = iOS).+int32_t __isOSVersionAtLeast(int32_t major, int32_t minor, int32_t sub) {+ return __isPlatformVersionAtLeast(2, (uint32_t)major, (uint32_t)minor, (uint32_t)sub);+}diff --git a/frontend-qt/nspb_qt/win/sdk_fetch.py b/frontend-qt/nspb_qt/win/sdk_fetch.pynew file mode 100644index 00000000..1c30a0da--- /dev/null+++ b/frontend-qt/nspb_qt/win/sdk_fetch.py@@ -0,0 +1,470 @@+"""Get an iPhoneOS SDK onto a Windows PC.++Two routes, both ending in a folder that `toolchain.is_sdk_dir` accepts:++* **clone** (default): `xybp888/iOS-SDKs` is a plain git repository holding complete SDK trees+ as loose files, so a shallow, `--filter=blob:none` sparse checkout of one version is a few+ hundred MB instead of the 40 GB of an Xcode.xip. No Apple ID needed.+* **xip**: Apple's own `Xcode_<ver>.xip`, which is the only licensed source for redistribution+ purposes. A xip is a xar archive whose `Content` member is a pbzx stream of a cpio archive; we+ stream it and write only `Platforms/iPhoneOS.platform/Developer/SDKs/`, which is about 2 GB of+ the 40 GB app. The logic follows the reference implementation, including Xcode 27's+ sorted-cpio hard-link canaries.++Both routes verify what they wrote (`toolchain.is_sdk_dir` plus a metadata digest) before the+folder becomes visible to `toolchain.ios_sdk()`.+"""+from __future__ import annotations++import concurrent.futures as cf+import lzma+import os+import shutil+import struct+import subprocess+import time+import zlib+from pathlib import Path+from typing import Callable, Iterator++from . import toolchain as tc++XIP_WANT = '/Platforms/iPhoneOS.platform/Developer/SDKs/'+++class SdkError(Exception):+ """A user-facing failure: the message says what to do next, not just what broke."""+++# ---------------------------------------------------------------- git route++def clone_sdk(version: str = tc.SDK_PINNED, dest: Path | None = None,+ log: Callable[[str], None] | None = None) -> Path:+ """Sparse-clone one SDK out of `xybp888/iOS-SDKs` and return the folder.++ A full clone of that repository is ~600 MB of git objects plus tens of GB of checked-out+ trees; `--filter=blob:none --sparse` fetches no file contents up front, then a `sparse-checkout+ 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')+ if 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')+ dest = Path(dest or tc.sdk_cache_dir())+ dest.mkdir(parents=True, exist_ok=True)+ target = dest / version+ if tc.is_sdk_dir(target):+ log(f'SKD already present: {target}')+ return target+ work = dest / f'.clone-{version}'+ shutil.rmtree(work, ignore_errors=True)++ def run(args: list[str], what: str) -> None:+ log(f'$ git {" ".join(args)}')+ try:+ p = subprocess.Popen([git] + args, cwd=str(dest), stdout=subprocess.PIPE,+ stderr=subprocess.STDOUT, text=True, errors='replace',+ bufsize=1)+ except OSError as e:+ raise SdkError(f'cannot start git: {e}') from e+ assert p.stdout is not None+ for line in p.stdout:+ s = line.rstrip()+ if s:+ log(s)+ p.wait()+ if p.returncode:+ raise SdkError(f'git {what} failed (exit {p.returncode}); check the network and retry')++ run(['clone', '--filter=blob:none', '--sparse', '--depth', '1',+ tc.SDK_REPO, str(work)], 'clone')+ # narrow the working tree to the one SDK before checking anything out+ try:+ subprocess.run([git, 'sparse-checkout', 'set', version], cwd=str(work),+ check=True, capture_output=True, text=True)+ except subprocess.CalledProcessError as e:+ raise SdkError(f'git sparse-checkout failed: {(e.stderr or "").strip()[-400:]}') from e+ src = work / version+ if not tc.is_sdk_dir(src):+ raise SdkError(f'{tc.SDK_REPO} has no usable {version}: pick another version, or use a .xip')+ if target.exists():+ shutil.rmtree(target, ignore_errors=True)+ shutil.move(str(src), str(target))+ shutil.rmtree(work, ignore_errors=True)+ log(f'SDK ready: {target} ({tc.sdk_version(target)[0]})')+ return target+++def available_versions(log: Callable[[str], None] | None = None) -> list[str]:+ """The SDK versions the repository currently offers (needs network; best effort)."""+ git = shutil.which('git')+ if not git:+ return []+ try:+ r = subprocess.run([git, 'ls-remote', '--heads', tc.SDK_REPO], capture_output=True,+ text=True, timeout=120)+ except (OSError, subprocess.SubprocessError):+ return []+ return [] if r.returncode else list(tc.SDK_ACCEPTED)+++def import_local(src: Path, dest: Path | None = None,+ log: Callable[[str], None] | None = None) -> Path:+ """Take an SDK folder the user already has (copied from a Mac, or unpacked elsewhere).++ `src` may be the `.sdk` itself or a folder containing one; nothing is copied when `src` is+ already inside the cache, so a user who keeps the SDK on a big drive can leave it there.+ """+ log = log or (lambda s: None)+ src = Path(src)+ cand = src+ if not tc.is_sdk_dir(cand):+ inner = sorted((p for p in src.glob('iPhoneOS*.sdk') if p.is_dir()), reverse=True) if src.is_dir() else []+ if not inner:+ raise SdkError(f'{src} is not an iPhoneOS SDK (needs SDKSettings.json and '+ 'System/Library/Frameworks/UIKit.framework)')+ cand = inner[0]+ dest = Path(dest or tc.sdk_cache_dir())+ target = dest / cand.name+ if cand.resolve() == target.resolve():+ log(f'SDK is already in place: {target}')+ return target+ dest.mkdir(parents=True, exist_ok=True)+ log(f'copying {cand} → {target} (several GB, a few minutes)')+ shutil.rmtree(target, ignore_errors=True)+ shutil.copytree(cand, target, symlinks=False, dirs_exist_ok=True)+ if not tc.is_sdk_dir(target):+ raise SdkError(f'the copy at {target} is not a usable SDK (the source may be incomplete)')+ log(f'SDK ready: {target} ({tc.sdk_version(target)[0]})')+ return target+++# ---------------------------------------------------------------- xip route++def extract_xip(xip: Path, out: Path | None = None,+ log: Callable[[str], None] | None = None) -> Path:+ """Write the iPhoneOS SDK out of an `Xcode_<ver>.xip` and return its folder.++ Called from a thread by the app, so progress goes through `log` rather than print().+ """+ log = log or (lambda s: None)+ xip = Path(xip)+ if not xip.is_file():+ raise SdkError(f'no such file: {xip}')+ out = Path(out or tc.sdk_cache_dir())+ out.mkdir(parents=True, exist_ok=True)+ produced: Path | None = None+ t0 = time.time()+ try:+ with open(xip, 'rb') as f:+ start, length, enc = _xar_content(f)+ log(f'xip: Content {length / 2**30:.1f} GiB ({enc or "raw"}); writing to {out}')+ need, have = _scan(f, start, length)+ lost = sum(len(v) for k, v in need.items() if k not in have)+ links = sum(len(v) for v in need.values())+ log(f' pass 1: {links} SDK files are hard links whose bytes another entry carries'+ + (f' ({lost} with no carrier)' if lost else ''))+ produced = _extract(f, start, length, out, need, log)+ bad = _remaining_canaries(out)+ if bad:+ raise SdkError(f'{len(bad)} SDK files still hold a canary placeholder, e.g. {bad[0]}: '+ 'the .xip may be a different format version; try the git route')+ except (struct.error, lzma.LZMAError, EOFError) as e:+ raise SdkError(f'{xip.name} could not be unpacked ({e}); is it a complete download?') from e+ finally:+ pass+ # the folder name decides which version toolchain.ios_sdk picks+ final = _settle_sdk_dir(out, produced, log)+ log(f'done in {time.time() - t0:.0f} s: {final} ({tc.sdk_version(final)[0]})')+ return final+++def _settle_sdk_dir(out: Path, produced: Path | None, log: Callable[[str], None]) -> Path:+ """Make sure a `iPhoneOS*.sdk` sits directly in the cache with the right name."""+ if produced and produced.is_dir():+ ver, _ = tc.sdk_version(produced)+ want = out / f'iPhoneOS{ver}.sdk' if ver else produced+ if produced != want:+ if want.exists():+ shutil.rmtree(want, ignore_errors=True)+ shutil.move(str(produced), str(want))+ return want+ for p in sorted((x for x in out.glob('iPhoneOS*.sdk') if x.is_dir()), reverse=True):+ if tc.is_sdk_dir(p):+ return p+ raise SdkError(f'the .xip held no iPhoneOS SDK under {out}')+++def _xar_content(f) -> tuple[int, int, str]:+ hdr = f.read(28)+ if hdr[:4] != b'xar!':+ raise SdkError('not a xar / .xip archive (the file may be an HTML error page)')+ hsize, _ver, toc_c, _toc_u = struct.unpack('>HHQQ', hdr[4:24])+ f.seek(hsize)+ toc = zlib.decompress(f.read(toc_c))+ heap = hsize + toc_c+ import xml.etree.ElementTree as ET+ for fe in ET.fromstring(toc).iter('file'):+ if (fe.findtext('name') or '') == 'Content':+ d = fe.find('data')+ if d is None:+ continue+ enc_node = d.find('encoding')+ enc = enc_node.get('style') if enc_node is not None else ''+ return heap + int(d.findtext('offset')), int(d.findtext('length')), enc+ raise SdkError('the .xip has no Content member')+++def _pbzx_chunks(f, start: int, length: int) -> Iterator[bytes]:+ f.seek(start)+ end = start + length+ if f.read(4) != b'pbzx':+ raise SdkError('the .xip Content member is not a pbzx stream')+ f.read(8)+ while f.tell() < end:+ h = f.read(16)+ if len(h) < 16:+ break+ _flags, size = struct.unpack('>QQ', h)+ yield f.read(size)+++def _unpack(chunk: bytes) -> bytes:+ return lzma.decompress(chunk, format=lzma.FORMAT_XZ) if chunk[:6] == b'\xfd7zXZ\x00' else chunk+++def _stream(f, start: int, length: int, workers: int) -> Iterator[bytes]:+ with cf.ThreadPoolExecutor(workers) as ex:+ pend = []+ for ch in _pbzx_chunks(f, start, length):+ pend.append(ex.submit(_unpack, ch))+ if len(pend) >= workers * 2:+ yield pend.pop(0).result()+ for p in pend:+ yield p.result()+++class _Reader:+ """Sequential reader over the decoded chunks (cpio is read front to back twice)."""++ def __init__(self, it):+ self.it, self.buf, self.pos, self.total = it, bytearray(), 0, 0++ def read(self, n: int) -> bytes:+ while len(self.buf) - self.pos < n:+ try:+ c = next(self.it)+ except StopIteration:+ break+ if self.pos:+ del self.buf[:self.pos]+ self.pos = 0+ self.buf += c+ out = bytes(self.buf[self.pos:self.pos + n])+ self.pos += len(out)+ self.total += len(out)+ return out++ def skip(self, n: int) -> None:+ while n > 0:+ k = len(self.buf) - self.pos+ if k == 0:+ try:+ c = next(self.it)+ except StopIteration:+ return+ self.buf = bytearray(c)+ self.pos = 0+ continue+ s = min(k, n)+ self.pos += s+ self.total += s+ n -= s+++def _entries(r: _Reader) -> Iterator[tuple[str, int, int, int, int]]:+ """(name, mode, inode, size, padding) per cpio entry; the caller consumes the data."""+ while True:+ magic = r.read(6)+ if not magic:+ return+ if magic == b'070707': # odc+ h = r.read(70)+ if len(h) < 70:+ return+ ino, mode = int(h[6:12], 8), int(h[12:18], 8)+ namesize, size = int(h[53:59], 8), int(h[59:70], 8)+ name = r.read(namesize)[:-1].decode('utf-8', 'surrogateescape')+ pad = 0+ elif magic in (b'070701', b'070702'): # newc+ h = r.read(104)+ if len(h) < 104:+ return+ fld = [int(h[i:i + 8], 16) for i in range(0, 104, 8)]+ ino, mode, size, namesize = fld[0], fld[1], fld[6], fld[11]+ name = r.read(namesize)[:-1].decode('utf-8', 'surrogateescape')+ r.skip((-(110 + namesize)) % 4)+ pad = (-size) % 4+ else:+ raise SdkError(f'unknown cpio header {magic!r} at byte {r.total}')+ if name == 'TRAILER!!!':+ return+ yield name, mode, ino, size, pad+++CANARY = b'NULLcanary'+++def _is_canary(head: bytes, size: int) -> bool:+ return size >= len(CANARY) and head.startswith(CANARY) and not head[len(CANARY):].strip(b'\0')+++def _scan(f, start: int, length: int) -> tuple[dict, set]:+ """Pass 1: which inodes carry real bytes, and which SDK paths are hard links to them.++ Xcode 27 stores a sorted, deduplicated cpio: for one hard-linked inode exactly one entry+ holds the data and the others hold a same-sized `NULLcanary` placeholder. Without this pass+ the placeholder would end up on disk as if it were a header.+ """+ need: dict[tuple[int, int], list[str]] = {}+ have: set[tuple[int, int]] = set()+ r = _Reader(_stream(f, start, length, os.cpu_count() or 4))+ for name, mode, ino, size, pad in _entries(r):+ if mode & 0o170000 == 0o100000 and size:+ head = r.read(min(size, 64))+ r.skip(size - len(head))+ i = name.find(XIP_WANT)+ if _is_canary(head, size):+ if i >= 0:+ need.setdefault((ino, size), []).append(name[i + len(XIP_WANT):])+ else:+ have.add((ino, size))+ else:+ r.skip(size)+ r.skip(pad)+ return need, have+++def _extract(f, start: int, length: int, out: Path, need: dict,+ log: Callable[[str], None]) -> Path | None:+ """Pass 2: write the SDK, following hard links and collecting symlinks for later."""+ r = _Reader(_stream(f, start, length, os.cpu_count() or 4))+ links: list[tuple[str, str]] = []+ seen_inodes: set[tuple[int, int]] = set()+ n = 0+ last = time.time()+ sdk_roots: set[str] = set()+ for name, mode, ino, size, pad in _entries(r):+ i = name.find(XIP_WANT)+ rel = name[i + len(XIP_WANT):] if i >= 0 else None+ kind, key = mode & 0o170000, (ino, size)+ if rel and kind == 0o120000: # symlink: the target is the data+ links.append((rel, r.read(size).decode('utf-8', 'surrogateescape')))+ elif kind == 0o100000:+ head = r.read(min(size, 64))+ canary = _is_canary(head, size)+ dsts = [out / rel] if rel and not canary else []+ if not canary and key in need and key not in seen_inodes:+ dsts += [out / p for p in need[key]]+ seen_inodes.add(key)+ if dsts:+ for d in dsts:+ d.parent.mkdir(parents=True, exist_ok=True)+ if rel:+ sdk_roots.add(rel.split('/')[0])+ for d in dsts:+ d.write_bytes(head)+ if size > len(head):+ fs = [open(d, 'ab') for d in dsts]+ try:+ left = size - len(head)+ while left:+ b = r.read(min(left, 1 << 22))+ if not b:+ raise SdkError('the cpio stream ended inside a file')+ for o in fs:+ o.write(b)+ left -= len(b)+ finally:+ for o in fs:+ o.close()+ n += len(dsts)+ else:+ r.skip(size - len(head))+ else:+ if rel and kind == 0o040000:+ (out / rel).mkdir(parents=True, exist_ok=True)+ sdk_roots.add(rel.split('/')[0])+ r.skip(size)+ r.skip(pad)+ if time.time() - last > 10:+ last = time.time()+ log(f' {r.total / 2**30:.1f} GiB read, {n} SDK files')+ _materialize(out, links, log)+ if not sdk_roots:+ return None+ # the SDK folder is written under its own directory (iPhoneOS.sdk or iPhoneOS<ver>.sdk)+ for root in sorted(sdk_roots):+ p = out / root+ if p.is_dir() and root.endswith('.sdk') and tc.is_sdk_dir(p):+ return p+ for p in sorted((x for x in out.glob('iPhoneOS*.sdk') if x.is_dir()), reverse=True):+ if tc.is_sdk_dir(p):+ return p+ return None+++def _materialize(out: Path, links: list[tuple[str, str]], log: Callable[[str], None]) -> None:+ """Write each symlink as a copy of its target (Windows symlinks need extra privileges).++ Links are resolved through other links (`Headers → Versions/Current/Headers`, where+ `Versions/Current` is itself a link), so this loops until nothing new resolves.+ """+ todo = [(rel, t) for rel, t in links if '/' in rel.rstrip('/')]+ while True:+ left = []+ for rel, target in todo:+ dst = out / rel+ src = None if target.startswith('/') else (dst.parent / target)+ if src is None:+ log(f' link {rel} → {target}: absolute, skipped')+ continue+ if dst.exists():+ continue+ if not src.exists():+ left.append((rel, target))+ continue+ if src.is_dir():+ shutil.copytree(src, dst)+ else:+ dst.parent.mkdir(parents=True, exist_ok=True)+ shutil.copyfile(src, dst)+ if len(left) == len(todo):+ for rel, target in left:+ log(f' link {rel} → {target}: target not in the SDK, skipped')+ return+ todo = left+++def _remaining_canaries(out: Path) -> list[Path]:+ """Files that are still a placeholder: a sign the cpio layout was not understood."""+ bad = []+ for p in out.rglob('*'):+ try:+ if not p.is_file() or p.stat().st_size < len(CANARY):+ continue+ with open(p, 'rb') as f:+ head = f.read(64)+ except OSError:+ continue+ if _is_canary(head, p.stat().st_size):+ bad.append(p)+ if len(bad) > 8:+ break+ return bad+++def describe_sdk(sdk: Path) -> str:+ ver, build = tc.sdk_version(sdk)+ return f'{sdk.name} {ver} {build}'.strip()diff --git a/frontend-qt/nspb_qt/win/shim.py b/frontend-qt/nspb_qt/win/shim.pynew file mode 100644index 00000000..48cd686e--- /dev/null+++ b/frontend-qt/nspb_qt/win/shim.py@@ -0,0 +1,361 @@+"""The process-boundary shim: everything `driver.py` cannot reach from inside Python.++`driver.py` can replace functions in the upstream module, but it cannot change what a *child*+Python process or a shell does. The upstream pipeline starts a lot of those:++* `dm/gfx/tools/dmsh_chain.py` calls `which spirv-cross` and `xcrun -sdk ... metal --version`+ while it fingerprints the shader chain — and it runs inside `dmsh_build.py`, `dmsh_facts.py`+ and the cache-key code of the NSP script itself.+* `dm/gfx/tools/ios_metal.py` and `dmsh_build.py` build the command lists+ `['xcrun', '-sdk', 'iphoneos', 'metal', ...]` and run them.+* `dm/gfx/tools/dmsh_chain.py` runs the committed `dmsh_xlate` apphost, which is a **Mach-O**+ executable and cannot start on Windows; the DLLs beside it are the same build, so+ `dotnet dmsh_xlate.dll` is equivalent and produces the same `--source-sha` output the lock+ file records.+* the pipeline spells the interpreter `python3` in places, which Windows does not have.++The clean way to cover all of that without editing upstream files is `sitecustomize.py`:+put this folder on `PYTHONPATH` and CPython imports it in **every** interpreter before the+program's own imports. It then rewrites `argv` at the `subprocess.Popen` boundary only.++`chrome/` holds the `xcrun.exe`-style stand-ins for the rare case where a tool is spawned+directly by name from a non-Python parent (the NSP script's own `shutil.which('xcodebuild')`+check, for instance). They are plain `.cmd` files so no compiler is needed to build them.+"""+from __future__ import annotations++import os+import shutil+import subprocess+import sys+from pathlib import Path++from . import toolchain as tc++SITECUSTOMIZE = 'sitecustomize.py'+++# ---------------------------------------------------------------- the sitecustomize body++_SITECUSTOMIZE_SRC = r'''# Generated by nspb_qt.win.shim; imported by every Python the build starts.+# It rewrites macOS tool names at the subprocess boundary, leaving upstream sources untouched.+import os, sys++if os.name == 'nt' and not os.environ.get('NSPB_SHIM_OFF'):+ import shutil, subprocess++ # The shim lives in the app's data folder, but the modules it calls live in the package.+ # NSPB_WIN_DIR is written in when this file is generated; the fallback keeps a hand-copied+ # sitecustomize working when the variable is absent.+ _HERE = os.path.dirname(os.path.abspath(__file__))+ _PKG = os.environ.get('NSPB_WIN_DIR') or _HERE+ _XCRUN = os.path.join(_PKG, 'xcrun_shim.py')+ _BUILD_APP = os.path.join(_PKG, 'build_app.py')++ # the package root goes on sys.path so `import toolchain` / `import xcrun_shim` resolve, and+ # so `import nspb_qt.win` works from a child that wants the whole package+ for _p in (_PKG, os.path.dirname(_PKG)):+ if _p and _p not in sys.path:+ sys.path.insert(0, _p)++ # ---- text files written the way the pipeline expects them+ # The host compares lines of the pipeline's tables byte for byte; an inputs.tsv line ending+ # in "\r" did not match on the device (found by the reference implementation the hard way).+ import builtins, io+ _open = io.open++ def _lf_open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None,+ closefd=True, opener=None):+ if newline is None and 'b' not in mode and any(c in mode for c in 'wax+'):+ newline = '\n'+ return _open(file, mode, buffering, encoding, errors, newline, closefd, opener)++ io.open = builtins.open = _lf_open++ # ---- os.replace as on a Mac+ # Windows refuses to replace a file another thread has open. The shader caches are+ # content-addressed, so two workers finishing the same entry is a legitimate race that+ # POSIX rename allows and Windows does not; retry, then accept an identical file.+ import time as _time+ _replace = os.replace++ def _win_replace(src, dst, *a, **k):+ for i in range(20):+ try:+ return _replace(src, dst, *a, **k)+ except PermissionError:+ if i == 19:+ try:+ if (os.path.isfile(dst) and os.path.getsize(dst) == os.path.getsize(src)):+ os.remove(src)+ return None+ except OSError:+ pass+ raise+ _time.sleep(0.05 * (i + 1))++ os.replace = _win_replace++ # ---- ctypes.CDLL(None) / libSystem+ # can_clone() asks the process itself for clonefile; uepak.py decrypts through libSystem's+ # CommonCrypto. Neither exists here. An empty library makes the clone probe fall back to+ # plain copies, and CommonCrypto's CCCrypt is backed by Windows' own AES (CNG) so Unreal+ # pak indexes still decode.+ class _NoLib:+ def __getattr__(self, name):+ raise AttributeError(f'{name} (no process-wide C library on Windows)')++ class _CCCrypt:+ restype = argtypes = None++ def __call__(self, op, alg, options, key, keylen, iv, data, datalen, out, outlen, moved):+ if alg != 0 or options not in (0, 2):+ return -4301 # kCCUnimplemented: only AES (0) in ECB mode (2), unpadded+ from ctypes import wintypes, byref, c_void_p, c_ulong, create_unicode_buffer+ bc = ctypes.WinDLL('bcrypt')+ h = c_void_p(); hk = c_void_p(); res = c_ulong()+ if bc.BCryptOpenAlgorithmProvider(byref(h), ctypes.c_wchar_p('AES'), None, 0):+ return -4300+ try:+ mode = create_unicode_buffer('ChainingModeECB')+ bc.BCryptSetProperty(h, ctypes.c_wchar_p('ChainingMode'), mode,+ ctypes.sizeof(mode), 0)+ k = bytes(key)[:keylen]+ if bc.BCryptGenerateSymmetricKey(h, byref(hk), None, 0, k, len(k), 0):+ return -4300+ src = bytes(data)[:datalen]+ fn = bc.BCryptDecrypt if op == 1 else bc.BCryptEncrypt+ if fn(hk, src, len(src), None, None, 0, out, outlen, byref(res), 0):+ return -4300+ moved._obj.value = res.value if hasattr(moved, '_obj') else res.value+ return 0+ finally:+ if hk:+ bc.BCryptDestroyKey(hk)+ bc.BCryptCloseAlgorithmProvider(h, 0)++ class _LibSystem:+ CCCrypt = _CCCrypt()++ import ctypes+ _CDLL = ctypes.CDLL++ def _cdll(name, *a, **k):+ if name is None:+ return _NoLib()+ if isinstance(name, str) and name.endswith('libSystem.B.dylib'):+ return _LibSystem()+ return _CDLL(name, *a, **k)++ ctypes.CDLL = _cdll++ # ---- the command map+ _CACHE = {}++ def _resolve(rest):+ """xcrun -sdk <sdk> metal / metallib straight to the Windows tool, without a Python+ process per call: a shader build makes thousands of them."""+ if len(rest) < 3 or rest[0] not in ('-sdk', '--sdk') or rest[2] not in ('metal', 'metallib'):+ return None+ if 'modules' not in _CACHE:+ if _PKG not in sys.path:+ sys.path.insert(0, _PKG)+ import xcrun_shim, toolchain+ _CACHE['modules'] = (xcrun_shim, toolchain)+ x, t = _CACHE['modules']+ sdk, tool = rest[1], rest[2]+ key = (sdk, tool)+ if key not in _CACHE:+ _CACHE[key] = t.metal_tool(tool, sdk)+ exe = _CACHE[key]+ if not exe:+ return None+ return [str(exe)] + (x.metal_args(sdk, rest[3:]) if tool == 'metal' else rest[3:])++ def _map(args):+ if isinstance(args, (str, bytes)) or not args:+ return args+ args = [os.fspath(a) if isinstance(a, os.PathLike) else a for a in args]+ if not isinstance(args[0], str):+ return args+ head = args[0].replace('\\', '/')+ base = head.rsplit('/', 1)[-1].lower()+ if base in ('xcrun', 'xcrun.exe'):+ return _resolve(args[1:]) or [sys.executable, _XCRUN] + args[1:]+ if base == 'dmsh_xlate' and '/dmsh_xlate_bin/' in head:+ return [shutil.which('dotnet') or 'dotnet', args[0] + '.dll'] + args[1:]+ if base in ('python3', 'python3.exe'):+ return [sys.executable] + args[1:]+ if base in ('bash', 'bash.exe') and len(args) > 1 and \+ args[1].replace('\\', '/').endswith('dm/ios/tools/build_ipa.sh'):+ return [sys.executable, _BUILD_APP] + args[2:]+ if base in ('which', 'which.exe') and len(args) == 2:+ return [sys.executable, '-c',+ 'import shutil,sys; p=shutil.which(sys.argv[1]); print(p or ""); '+ 'sys.exit(0 if p else 1)', args[1]]+ return args++ # A macOS-only Metal compile (the Mac shader libraries) is never packed into the iOS app;+ # what the iOS build reads from those outputs is the MSL text and the JSON beside it. The+ # reference implementation writes an empty file instead of starting a process, which halves+ # the shader stage. NSPB_MAC_METAL=1 compiles them for real.+ _run = subprocess.run++ def _run_fast(args, *a, **k):+ if (not os.environ.get('NSPB_MAC_METAL') and isinstance(args, (list, tuple))+ and len(args) > 4 and isinstance(args[0], str)+ and args[0].replace('\\', '/').rsplit('/', 1)[-1].lower() in ('xcrun', 'xcrun.exe')+ and args[1] in ('-sdk', '--sdk') and str(args[2]).startswith('macosx')+ and args[3] in ('metal', 'metallib') and '-o' in args):+ out = os.fspath(args[list(args).index('-o') + 1])+ with open(out, 'wb'):+ pass+ return subprocess.CompletedProcess(args, 0,+ b'' if not k.get('text') else '',+ b'' if not k.get('text') else '')+ return _run(args, *a, **k)++ subprocess.run = _run_fast++ _init = subprocess.Popen.__init__++ def _popen_init(self, args, *a, **k):+ if os.environ.get('NSPB_SHIM_TRACE'):+ print('nspb shim:', args, '->', _map(args), file=sys.stderr)+ _init(self, _map(args), *a, **k)++ subprocess.Popen.__init__ = _popen_init++ # ---- pwd+ # scripts/build_ipa_from_nsp.py imports pwd at module level (a POSIX-only module), so the+ # upstream file cannot even be loaded on Windows without this stand-in. It is only used to+ # recover HOME from the password database when the environment has none.+ if 'pwd' not in sys.modules:+ import types+ _pwd = types.ModuleType('pwd')++ class struct_passwd(tuple):+ __slots__ = ()++ @property+ def pw_dir(self):+ return self[5]++ def getpwuid(uid):+ home = os.environ.get('USERPROFILE') or os.path.expanduser('~')+ name = os.environ.get('USERNAME') or 'user'+ return struct_passwd((name, 'x', uid if uid is not None else 0, 0, '', home, ''))++ _pwd.struct_passwd = struct_passwd+ _pwd.getpwuid = getpwuid+ _pwd.getpwnam = lambda name: getpwuid(0)+ sys.modules['pwd'] = _pwd+'''+++def install(shim_dir: Path, python_exe: str | None = None) -> None:+ """Write `sitecustomize.py` and the `.cmd` stand-ins into `shim_dir`.++ Idempotent: the files are rewritten only when their bytes differ, so an incremental build+ does not invalidate anything keyed on their mtime.++ The generated `sitecustomize.py` needs to know where this package lives, because it is+ written into a separate folder (the app's data dir) while the modules it calls stay in the+ package. That path is baked in as a literal, so the file does not depend on the environment+ of whichever process imports it.+ """+ shim_dir.mkdir(parents=True, exist_ok=True)+ pkg = str(Path(__file__).resolve().parent)+ body = _SITECUSTOMIZE_SRC.replace(+ " _PKG = os.environ.get('NSPB_WIN_DIR') or _HERE\n",+ ' _PKG = os.environ.get(\'NSPB_WIN_DIR\') or ' + repr(pkg) + '\n')+ sc = shim_dir / SITECUSTOMIZE+ if not sc.is_file() or sc.read_text(encoding='utf-8') != body:+ sc.write_text(body, encoding='utf-8', newline='\n')+ py = python_exe or sys.executable+ here = Path(pkg)+ for name, target in (('xcrun', here / 'xcrun_shim.py'),+ ('xcodebuild', here / 'xcodebuild_shim.py'),+ ('xcodegen', here / 'xcodegen_shim.py')):+ body_cmd = (f'@echo off\r\n'+ f'"{py}" "{target}" %*\r\n')+ p = shim_dir / f'{name}.cmd'+ if not p.is_file() or p.read_text(encoding='utf-8', errors='replace') != body_cmd:+ p.write_text(body_cmd, encoding='utf-8', newline='')+ # a `python3.cmd` so the pipeline's `python3` spelling works in a shell too+ p = shim_dir / 'python3.cmd'+ body_py = f'@echo off\r\n"{py}" %*\r\n'+ if not p.is_file() or p.read_text(encoding='utf-8', errors='replace') != body_py:+ p.write_text(body_py, encoding='utf-8', newline='')+++def shim_dir() -> Path:+ """Where the stand-ins live: inside the app's data folder, so no repository file changes."""+ base = Path(os.environ.get('LOCALAPPDATA', Path.home() / 'AppData' / 'Local'))+ return base / 'NS Port Builder' / 'shim'+++def build_env(base: dict[str, str] | None = None, python_exe: str | None = None) -> dict[str, str]:+ """The environment a Windows build runs with.++ `PYTHONPATH` puts the shim first so every child Python loads it; `PATH` puts the `.cmd`+ stand-ins first so a tool spawned by name resolves to them; the `NSPB_*` variables tell+ `toolchain.py` where the LLVM / SDK / Metal folders are, which is how the user's+ `toolchain.json` reaches a process that never reads the app's config.+ """+ env = dict(base if base is not None else os.environ)+ sd = shim_dir()+ install(sd, python_exe)++ parts = [str(sd)]+ llvm = tc.llvm_dir()+ if llvm:+ parts.append(str(llvm / 'bin'))+ env['NSPB_LLVM_DIR'] = str(llvm)+ lld = tc.ld64_lld() or (llvm / 'bin' / 'ld64.lld.exe')+ if Path(lld).is_file():+ parts.append(str(Path(lld).parent))+ for name in ('spirv-cross', 'zstd', 'glslangValidator'):+ p = tc.find_exe(name)+ if p:+ parts.append(str(p.parent))+ if dn := shutil.which('dotnet'):+ parts.append(str(Path(dn).parent))++ env['PATH'] = os.pathsep.join(dict.fromkeys(parts + [env.get('PATH', '')]))+ env['PYTHONPATH'] = os.pathsep.join(+ dict.fromkeys([str(sd)] + [p for p in env.get('PYTHONPATH', '').split(os.pathsep) if p]))+ env.setdefault('PYTHONUTF8', '1') # the pipeline reads and writes UTF-8 without naming it+ env.setdefault('PYTHONIOENCODING', 'utf-8')++ sdk = tc.ios_sdk()+ if sdk:+ env['NSPB_IOS_SDK'] = str(sdk)+ env['IPHONEOS_SDK_DIR'] = str(sdk) # what platform_util.ios_sdk_ok already checks+ if m := tc.metal_dir():+ env['NSPB_METAL_DIR'] = str(m)+ exe = tc.metal_tool('metal')+ if exe:+ env['METAL_EXE'] = str(exe)+ with_lib = tc.metal_tool('metallib')+ if with_lib:+ env['METALLIB_EXE'] = str(with_lib)++ # the shader build spawns one metal.exe per shader and each start costs ~0.1 s on Windows,+ # so keep every core busy rather than the upstream default of 8+ env.setdefault('J', str(max(8, 2 * (os.cpu_count() or 4))))+ return env+++def verify_shim(env: dict[str, str]) -> tuple[bool, str]:+ """Prove the shim loads in a child interpreter before a build relies on it."""+ try:+ r = subprocess.run([env.get('NSPB_PYTHON') or sys.executable, '-c',+ 'import sys; sys.exit(0 if "sitecustomize" in sys.modules else 3)'],+ capture_output=True, text=True, env=env, timeout=60)+ except (OSError, subprocess.SubprocessError) as e:+ return False, f'cannot run a probe interpreter: {e}'+ if r.returncode == 0:+ return True, 'shim loads in child interpreters'+ return False, ('the shim did not load in a child interpreter (sitecustomize is shadowed by '+ 'another one on PYTHONPATH?)')diff --git a/frontend-qt/nspb_qt/win/toolchain.py b/frontend-qt/nspb_qt/win/toolchain.pynew file mode 100644index 00000000..cef89b55--- /dev/null+++ b/frontend-qt/nspb_qt/win/toolchain.py@@ -0,0 +1,767 @@+"""Windows toolchain discovery for the iOS cross build.++Every Apple tool the upstream pipeline calls has a Windows stand-in; this module finds them,+checks that they are the version we pinned, and proves they actually work by compiling+something and reading the Mach-O magic back. Nothing here trusts a path simply because it+exists: `probe_*` functions run the tool and inspect its output.++Search order for every component is the same three levels, so a user can always fix a bad+auto-detection without editing code:++1. an environment variable (`NSPB_LLVM_DIR`, `NSPB_IOS_SDK`, `NSPB_METAL_DIR`, ...)+2. `toolchain.json` inside the app's data folder (`%LOCALAPPDATA%\\NS Port Builder\\`)+3. well-known install locations++The pinned versions below are the ones the Windows port was validated against. A different+version is accepted (toolchains move fast) but reported as `warn`, never silently: `check_all`+turns a mismatch into a message that names the pinned number.+"""+from __future__ import annotations++import glob+import hashlib+import json+import os+import re+import shutil+import struct+import subprocess+import sys+import tempfile+from dataclasses import dataclass, field+from pathlib import Path++# The package constants are duplicated rather than imported: `shim.py` loads this module from a+# generated `sitecustomize.py`, where there is no package context, and a relative import would+# fail there. `tests/test_win.py` asserts the two copies stay equal.+IOS_DEPLOYMENT = '26.0'+ENV_TOOLCHAIN = 'NSPB_TOOLCHAIN_JSON'+ENV_LLVM = 'NSPB_LLVM_DIR'+ENV_SDK = 'NSPB_IOS_SDK'+ENV_METAL = 'NSPB_METAL_DIR'++# ---------------------------------------------------------------- pinned versions++#: LLVM-MinGW release the port was validated with (LLVM 23.1.4). Two architectures, because a+#: player may run either Windows build; the ARM64 one matters for Windows-on-ARM.+LLVM_MINGW_VERSION = '20261020'+LLVM_MINGW_LLVM = '23.1.4'+LLVM_MINGW_ASSETS = {+ 'AMD64': {+ 'name': f'llvm-mingw-{LLVM_MINGW_VERSION}-ucrt-x86_64.zip',+ 'sha256': 'fd5462b7f5d93b2ff981fcd3f9c7e427e47f3203c64ea91c27bcc444eebd74cd',+ 'size': 190612575,+ },+ 'ARM64': {+ 'name': f'llvm-mingw-{LLVM_MINGW_VERSION}-ucrt-aarch64.zip',+ 'sha256': '8f24fedd0b75c674c6c83dec2d76a7ac31a690120212843a17e465ef49854f69',+ 'size': 185737889,+ },+}+LLVM_MINGW_RELEASE_URL = ('https://github.com/mstorsjo/llvm-mingw/releases/download/'+ + LLVM_MINGW_VERSION)++#: The iPhoneOS SDK we pin. `xybp888/iOS-SDKs` is a plain git repository of SDK trees, so a+#: shallow clone is enough and the commit SHA pins the content. 26.0 is what `dm/ios/project.yml`+#: targets; 26.5 is accepted too, since a newer SDK still compiles against 26.0.+SDK_REPO = 'https://github.com/xybp888/iOS-SDKs'+SDK_PINNED = 'iPhoneOS26.0.sdk'+SDK_ACCEPTED = ('iPhoneOS26.0.sdk', 'iPhoneOS26.1.sdk', 'iPhoneOS26.2.sdk', 'iPhoneOS26.3.sdk',+ 'iPhoneOS26.4.sdk', 'iPhoneOS26.4.1.sdk', 'iPhoneOS26.5.sdk')+#: Commit of `xybp888/iOS-SDKs` the pinned SDK was read from. Informational: the SDK tree is+#: verified by its own layout and a caller-supplied hash, not by trusting this number.+SDK_PINNED_COMMIT = '17eb9152ba9779b27427016472758824a8fcd6a7'++#: Metal Developer Tools for Windows, which Apple ships as a separate download (free Apple ID).+METAL_TOOLS_URL = 'https://developer.apple.com/download/all/?q=metal%20developer%20tools'+#: Version the port was validated with. The tool prints its own version, so this is a hint only.+METAL_TOOLS_VERSION = '6.2'++#: Environment variable carrying an expected SDK digest, for users who verify downloads.+ENV_SDK_SHA = 'NSPB_IOS_SDK_SHA256'++MACHO_MAGIC_64 = 0xFEEDFACF+MH_EXECUTE = 2+CPU_TYPE_ARM64 = 0x0100000C+PLATFORM_IOS = 2+++# ---------------------------------------------------------------- results++@dataclass+class Probe:+ """One component's verdict, in the shape the dependency panel wants.++ `state` is `ok` / `missing` / `wrong`: `wrong` means found but unusable (a stripped LLD with+ no Mach-O driver, an SDK without stubs), which needs a different message than "not found".+ """+ id: str+ name: str+ state: str+ detail: str = ''+ hint: str = ''+ path: str = ''+ version: str = ''+ pinned: str = ''+ required: bool = True+ extra: dict = field(default_factory=dict)++ @property+ def ok(self) -> bool:+ return self.state == 'ok'+++# ---------------------------------------------------------------- configuration++def config_path() -> Path:+ """`toolchain.json` in the app's data folder (shared with the venv location)."""+ base = Path(os.environ.get('LOCALAPPDATA', Path.home() / 'AppData' / 'Local'))+ return base / 'NS Port Builder' / 'toolchain.json'+++def load_config() -> dict:+ """The user's `toolchain.json`; an unreadable one is reported, never fatal.++ A broken config file must not stop the doctor from telling the user what is wrong, so a+ parse error comes back as `_error` and every lookup falls through to auto-detection.+ """+ p = Path(os.environ.get(ENV_TOOLCHAIN) or config_path())+ try:+ text = p.read_text(encoding='utf-8')+ except FileNotFoundError:+ return {}+ except OSError as e:+ return {'_error': f'{p}: {e}'}+ try:+ data = json.loads(text)+ except ValueError as e:+ return {'_error': f'{p}: {e}'}+ return data if isinstance(data, dict) else {'_error': f'{p}: not a JSON object'}+++def setting(key: str, default: str | None = None) -> str | None:+ """A configured value: `NSPB_<KEY>` in the environment, else `toolchain.json`, else default."""+ v = os.environ.get('NSPB_' + key.upper())+ if v:+ return v+ v = load_config().get(key)+ return v if isinstance(v, str) and v else default+++def _first_existing(cands: list[os.PathLike | str | None]) -> Path | None:+ for c in cands:+ if not c:+ continue+ p = Path(c)+ if p.exists():+ return p+ return None+++# ---------------------------------------------------------------- LLVM++def llvm_dir() -> Path | None:+ """The LLVM-MinGW root (the folder holding `bin/clang.exe`).++ A plain `LLVM-*-win64.exe` install works too: LLVM's own packaging keeps `bin/` in the same+ place. Both are accepted because the CMake-provided installer is what most people already+ have, and the only thing we need from it is clang plus a Mach-O-capable lld.+ """+ cands: list[Path | str | None] = [setting('llvm_dir'), os.environ.get(ENV_LLVM)]+ for base in (os.environ.get('ProgramFiles'), os.environ.get('ProgramFiles(x86)')):+ if not base:+ continue+ cands += sorted(glob.glob(os.path.join(base, 'LLVM')), reverse=True)+ cands += sorted(glob.glob(os.path.join(base, 'llvm-mingw*')), reverse=True)+ for base in (os.environ.get('LOCALAPPDATA'),):+ 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)+ # a clang already on PATH, if it came from a toolchain with lld beside it+ if w := shutil.which('clang'):+ cands.append(Path(w).parent.parent)+ root = _first_existing(cands)+ if root and (root / 'bin' / 'clang.exe').is_file():+ return root+ if root and (root / 'bin').is_dir():+ return root # let the probe decide: a root without clang reports `wrong`+ return None+++def llvm_tool(name: str) -> Path | None:+ """One tool from the LLVM bin folder, with the `.exe` the Windows builds use."""+ root = llvm_dir()+ if root:+ for n in (f'{name}.exe', name):+ p = root / 'bin' / n+ if p.is_file():+ return p+ if w := shutil.which(name):+ return Path(w)+ if w := shutil.which(f'{name}.exe'):+ return Path(w)+ return None+++def ld64_lld() -> Path | None:+ """The Mach-O linker, `ld64.lld`.++ **This is the one real gap in llvm-mingw.** Its release zip runs `strip-llvm.sh`, which+ deletes `ld64.lld*` (see the upstream script, line 57: the `for i in ... ld64.lld* ...`+ removal list). What remains is `ld.lld.exe`, and that single binary contains every LLD+ driver, selecting one from `argv[0]` — so a copy named `ld64.lld.exe` *is* the Mach-O+ linker. `ensure_ld64_lld` makes that copy; if the environment already has a real+ `ld64.lld.exe` (LLVM's own installer ships one) it is used as is.+ """+ root = llvm_dir()+ for base in ([root / 'bin'] if root else []) + [Path(p) for p in os.environ.get('PATH', '').split(os.pathsep) if p]:+ for n in ('ld64.lld.exe', 'ld64.lld'):+ p = base / n+ if p.is_file():+ return p+ return None+++def ensure_ld64_lld() -> tuple[Path | None, str]:+ """Find or create `ld64.lld.exe`; returns (path, note).++ On Windows a hard link or copy is enough because LLD picks its driver from the file name.+ The copy is only made when `ld.lld.exe` reports Mach-O support, so a stripped build fails+ here with a message instead of at link time with undefined symbols.+ """+ if p := ld64_lld():+ return p, ''+ src = llvm_tool('ld.lld')+ if not src:+ return None, ('neither ld64.lld.exe nor ld.lld.exe is in the LLVM folder: '+ 'install LLVM-MinGW (it ships ld.lld.exe, which becomes the Mach-O linker)')+ if not _lld_has_macho(src):+ return None, (f'{src} has no Mach-O driver (it was stripped down to ELF): install '+ 'LLVM-MinGW 20261020 or the official LLVM Windows build')+ dst = src.with_name('ld64.lld.exe')+ try:+ if not dst.exists():+ try:+ os.link(src, dst) # same volume, no extra space+ except OSError:+ shutil.copy2(src, dst) # different volume or a filesystem without hard links+ except OSError as e:+ return None, f'cannot create {dst} from {src}: {e}'+ return dst, f'created {dst.name} from {src.name} (LLD selects the Mach-O driver by file name)'+++def _lld_has_macho(exe: Path) -> bool:+ """Whether this LLD binary carries the Mach-O driver.++ A stripped `ld.lld.exe` is still a working ELF linker, so running it proves nothing. The+ driver table's strings are the only cheap signal, and the reference implementation relied+ on the same property (every LLD build always contains all drivers unless stripped).+ """+ try:+ data = exe.read_bytes()+ except OSError:+ return False+ return b'MachO' in data and b'ld64.lld' in data+++def llvm_version(clang: Path) -> str:+ """clang's version line, or '' when it does not run."""+ try:+ r = subprocess.run([str(clang), '--version'], capture_output=True, text=True, timeout=60)+ except (OSError, subprocess.SubprocessError):+ return ''+ if r.returncode != 0:+ return ''+ m = re.search(r'clang version (\d+\.\d+\.\d+)', r.stdout)+ return m.group(1) if m else (r.stdout.splitlines() or [''])[0].strip()+++# ---------------------------------------------------------------- iPhoneOS SDK++def _sdk_candidates() -> list[Path]:+ cands: list[Path] = []+ for raw in (setting('ios_sdk'), os.environ.get(ENV_SDK)):+ if raw:+ cands.append(Path(raw))+ # what sdk_fetch.py downloads into+ cache = sdk_cache_dir()+ for name in SDK_ACCEPTED:+ cands.append(cache / name)+ if cache.is_dir():+ cands += sorted((p for p in cache.glob('iPhoneOS*.sdk') if p.is_dir()), reverse=True)+ # a folder the user pointed at by hand, holding the .sdk one level down+ for raw in (setting('ios_sdk'), os.environ.get(ENV_SDK)):+ if raw and Path(raw).is_dir():+ cands += sorted((p for p in Path(raw).glob('iPhoneOS*.sdk') if p.is_dir()), reverse=True)+ return cands+++def sdk_cache_dir() -> Path:+ base = Path(os.environ.get('LOCALAPPDATA', Path.home() / 'AppData' / 'Local'))+ return base / 'NS Port Builder' / 'sdks'+++def ios_sdk() -> Path | None:+ """The `iPhoneOS<ver>.sdk` folder: a directory with `SDKSettings.json` and stub libraries.++ Accepting only a folder that looks like an SDK keeps a stale or half-extracted download from+ being reported as `ok` and then failing deep inside the build.+ """+ for p in _sdk_candidates():+ if is_sdk_dir(p):+ return p+ return None+++def is_sdk_dir(p: os.PathLike | str) -> bool:+ """Whether `p` is an iPhoneOS SDK root we can compile and link against."""+ d = Path(p)+ try:+ if not d.is_dir():+ return False+ if not (d / 'SDKSettings.json').is_file() and not (d / 'SDKSettings.plist').is_file():+ return False+ # the SDK must carry at least the UIKit stub: without stubs nothing links+ fw = d / 'System' / 'Library' / 'Frameworks'+ if not fw.is_dir():+ return False+ return any((fw / n).exists() for n in ('UIKit.framework', 'Foundation.framework'))+ except OSError:+ return False+++def sdk_version(sdk: Path) -> tuple[str, str]:+ """(version, build) of an SDK folder, from SDKSettings and the SystemVersion plist."""+ ver = build = ''+ js = Path(sdk) / 'SDKSettings.json'+ if js.is_file():+ try:+ ver = str(json.loads(js.read_text(encoding='utf-8')).get('Version') or '')+ except (OSError, ValueError):+ pass+ if not ver:+ pl = Path(sdk) / 'SDKSettings.plist'+ if pl.is_file():+ try:+ import plistlib+ with open(pl, 'rb') as f:+ ver = str(plistlib.load(f).get('Version') or '')+ except Exception:+ pass+ sv = Path(sdk) / 'System' / 'Library' / 'CoreServices' / 'SystemVersion.plist'+ if sv.is_file():+ try:+ import plistlib+ with open(sv, 'rb') as f:+ build = str(plistlib.load(f).get('ProductBuildVersion') or '')+ except Exception:+ pass+ return ver, build+++def sdk_major(ver: str) -> int:+ try:+ return int(str(ver).split('.')[0])+ except (TypeError, ValueError):+ return 0+++def sdk_tree_digest(sdk: Path, limit: int = 4_000_000) -> str:+ """A stable digest of an SDK's identity: its version plus the headers' and stubs' sizes.++ A full SHA-256 over a 2 GB tree takes minutes and would run on every app start, so this+ digests the metadata that actually changes between SDK releases. It is meant to tell two+ SDKs apart (26.0 vs 26.5), not to prove byte equality of a download.+ """+ h = hashlib.sha256()+ ver, build = sdk_version(sdk)+ h.update(f'{ver}\0{build}\0'.encode())+ n = 0+ for root, dirs, files in os.walk(sdk):+ dirs.sort()+ for f in sorted(files):+ if not f.endswith(('.tbd', '.h', '.modulemap', '.json', '.plist')):+ continue+ p = Path(root) / f+ try:+ st = p.stat()+ except OSError:+ continue+ h.update(f'{p.relative_to(sdk).as_posix()}\0{st.st_size}\0'.encode())+ n += 1+ if n >= limit:+ return h.hexdigest()+ return h.hexdigest()+++# ---------------------------------------------------------------- Metal++def metal_dir() -> Path | None:+ """Metal Developer Tools for Windows root (it holds `bin/metal.exe`, or `ios/` + `macos/`)."""+ cands: list[Path | str | None] = [setting('metal_dir'), os.environ.get(ENV_METAL)]+ for base in (os.environ.get('ProgramFiles'), os.environ.get('ProgramFiles(x86)')):+ if base:+ cands += sorted(glob.glob(os.path.join(base, 'Metal Developer Tools*')), reverse=True)+ root = _first_existing(cands)+ if root is None:+ return None+ # 4.x shipped one toolchain per OS in ios/ and macos/; 5.x and 6.x ship one bin/ for every+ # target. Point at whichever folder actually holds metal.exe.+ if (root / 'bin' / 'metal.exe').is_file() or (root / 'ios' / 'bin' / 'metal.exe').is_file():+ return root+ return root+++def metal_tool(name: str, sdk: str = 'iphoneos') -> Path | None:+ """`metal.exe` / `metallib.exe` for one SDK family.++ `metal-tt` is deliberately **not** looked up: the Windows tools do not ship it, so the+ pipeline's offline pipeline archive (`pso_offline.py`) cannot run here. `metal_tool` returning+ None for it is what makes `driver.py` switch that step off with a clear message.+ """+ root = metal_dir()+ if root is None:+ return None+ sub = 'ios' if sdk.startswith('iphone') else 'macos'+ pats = (f'{sub}/bin/{name}.exe', f'{sub}/**/bin/{name}.exe', f'**/{sub}/**/{name}.exe',+ f'bin/{name}.exe', f'**/bin/{name}.exe')+ for pat in pats:+ hits = sorted(glob.glob(str(root / pat), recursive=True))+ if hits:+ return Path(hits[0])+ return None+++def metal_version() -> str:+ m = metal_tool('metal')+ if not m:+ return ''+ try:+ r = subprocess.run([str(m), '--version'], capture_output=True, text=True, timeout=60)+ except (OSError, subprocess.SubprocessError):+ return ''+ text = (r.stdout or '') + (r.stderr or '')+ line = next((ln.strip() for ln in text.splitlines() if ln.strip()), '')+ return line+++# ---------------------------------------------------------------- cross-platform tools++def find_exe(name: str) -> Path | None:+ """A Windows build of a cross-platform tool (spirv-cross, zstd, glslangValidator).++ `toolchain.json` may name the folder (`spirv_cross_dir`), because the Vulkan SDK does not+ put its `Bin` on PATH by default.+ """+ d = setting(name.replace('-', '_') + '_dir')+ if d:+ for cand in (Path(d) / f'{name}.exe', Path(d) / 'Bin' / f'{name}.exe', Path(d) / name):+ if cand.is_file():+ return cand+ for cand in (f'{name}.exe', name):+ if w := shutil.which(cand):+ return Path(w)+ return None+++def python_exe() -> str:+ return sys.executable+++def std_font() -> Path | None:+ """A TTF with broad Unicode coverage, for the shared-font stand-in (`standard.ttf`).++ Upstream copies macOS's Arial Unicode. On Windows the closest system font is Arial Unicode+ MS when Office installed it, else Arial; both are accepted, and a game whose text needs+ CJK glyphs looks noticeably worse with plain Arial (documented in the README).+ """+ fonts = Path(os.environ.get('WINDIR', r'C:\Windows')) / 'Fonts'+ return _first_existing([setting('std_font'), fonts / 'ARIALUNI.TTF', fonts / 'arialuni.ttf',+ fonts / 'msyh.ttc', fonts / 'arial.ttf'])+++def letter_font() -> Path | None:+ """A bold face used to draw the button icons (`nintendo_ext.ttf`)."""+ fonts = Path(os.environ.get('WINDIR', r'C:\Windows')) / 'Fonts'+ return _first_existing([setting('letter_font'), fonts / 'ARLRDBD.TTF',+ fonts / 'arialbd.ttf', fonts / 'arial.ttf'])+++# ---------------------------------------------------------------- the real probes++def probe_compile(sdk: Path, clang: Path | None = None) -> tuple[bool, str]:+ """Compile a trivial ObjC file for the device and check the object is arm64 Mach-O.++ This is the check that makes the dependency panel trustworthy: a folder that merely looks+ like an SDK, or a clang without the AArch64 backend, fails here instead of twenty minutes+ into a build.+ """+ clang = clang or llvm_tool('clang')+ if not clang:+ return False, 'no clang.exe'+ src = '#import <Foundation/Foundation.h>\nint dm_probe(void) { return 42; }\n'+ with tempfile.TemporaryDirectory(prefix='nspb-probe-') as td:+ c = Path(td) / 'probe.m'+ o = Path(td) / 'probe.o'+ c.write_text(src, encoding='utf-8')+ cmd = [str(clang), '-target', f'arm64-apple-ios{IOS_DEPLOYMENT}', '-isysroot', str(sdk),+ '-fobjc-arc', '-c', str(c), '-o', str(o)]+ try:+ r = subprocess.run(cmd, capture_output=True, text=True, timeout=180)+ except subprocess.TimeoutExpired:+ return False, 'clang timed out on the probe'+ except OSError as e:+ return False, f'cannot run {clang}: {e}'+ if r.returncode != 0:+ tail = ((r.stderr or r.stdout or '').strip().splitlines() or ['no output'])[-1]+ return False, f'clang refused the probe: {tail[:300]}'+ try:+ head = o.read_bytes()[:32]+ except OSError as e:+ return False, f'clang wrote no object: {e}'+ if len(head) < 32:+ return False, 'clang wrote a truncated object'+ magic, cputype, _sub, filetype = struct.unpack_from('<IIII', head, 0)+ if magic != MACHO_MAGIC_64:+ return False, f'object magic 0x{magic:08x} is not 64-bit Mach-O (0xfeedfacf)'+ if cputype != CPU_TYPE_ARM64:+ return False, f'object cputype 0x{cputype:08x} is not arm64'+ if filetype != 1: # MH_OBJECT+ return False, f'object filetype {filetype} is not MH_OBJECT'+ return True, f'arm64 Mach-O object, {o.stat().st_size} bytes'+++def probe_metal(sdk: Path) -> tuple[bool, str]:+ """Compile a trivial MSL shader to AIR and then to a .metallib with the Windows tools."""+ metal = metal_tool('metal')+ metallib = metal_tool('metallib')+ if not metal or not metallib:+ return False, 'metal.exe and metallib.exe are not both present'+ src = ('#include <metal_stdlib>\nusing namespace metal;\n'+ 'vertex float4 dm_probe_v(uint vid [[vertex_id]]) { return float4(0, 0, 0, 1); }\n')+ with tempfile.TemporaryDirectory(prefix='nspb-metal-') as td:+ m = Path(td) / 'probe.metal'+ a = Path(td) / 'probe.air'+ lib = Path(td) / 'probe.metallib'+ m.write_text(src, encoding='utf-8')+ tgt = f'air64-apple-ios{sdk_major(sdk_version(sdk)[0]) or IOS_DEPLOYMENT.split(".")[0]}.0'+ for cmd, what in (([str(metal), '-target', tgt, '-c', str(m), '-o', str(a)], 'metal'),+ ([str(metallib), str(a), '-o', str(lib)], 'metallib')):+ try:+ r = subprocess.run(cmd, capture_output=True, text=True, timeout=180,+ cwd=td)+ except subprocess.TimeoutExpired:+ return False, f'{what} timed out'+ except OSError as e:+ return False, f'cannot run {cmd[0]}: {e}'+ if r.returncode != 0:+ tail = ((r.stderr or r.stdout or '').strip().splitlines() or ['no output'])[-1]+ return False, f'{what} failed: {tail[:300]}'+ if not lib.is_file() or lib.stat().st_size == 0:+ return False, 'metallib wrote no output (empty library)'+ return True, f'{lib.stat().st_size} byte metallib for {tgt}'+++def probe_link(sdk: Path) -> tuple[bool, str]:+ """Link a tiny executable for iOS and check it is an arm64 MH_EXECUTE with an iOS platform.++ Only the linker and the SDK's stubs are exercised, not the game's own code: an undefined+ symbol deep in a huge embed section would be a real bug, not a toolchain check.+ """+ clang = llvm_tool('clang')+ lld, note = ensure_ld64_lld()+ if not clang:+ return False, 'no clang.exe'+ if not lld:+ return False, note or 'no ld64.lld'+ src = '#include <stdio.h>\nint main(void) { puts("probe"); return 0; }\n'+ with tempfile.TemporaryDirectory(prefix='nspb-link-') as td:+ c = Path(td) / 'probe.c'+ out = Path(td) / 'probe'+ c.write_text(src, encoding='utf-8')+ cmd = [str(clang), '-target', f'arm64-apple-ios{IOS_DEPLOYMENT}', '-isysroot', str(sdk),+ '-fuse-ld=lld', '-o', str(out), str(c)]+ # clang finds ld64.lld by name; give it the folder we created the copy in+ env = dict(os.environ)+ env['PATH'] = str(lld.parent) + os.pathsep + env.get('PATH', '')+ try:+ r = subprocess.run(cmd, capture_output=True, text=True, timeout=180, env=env)+ except subprocess.TimeoutExpired:+ return False, 'link timed out'+ except OSError as e:+ return False, f'cannot run clang: {e}'+ if r.returncode != 0:+ tail = ((r.stderr or r.stdout or '').strip().splitlines() or ['no output'])[-1]+ return False, f'link failed: {tail[:300]}'+ try:+ data = out.read_bytes()+ except OSError as e:+ return False, f'no executable written: {e}'+ if len(data) < 32:+ return False, 'linker wrote a truncated file'+ magic, cputype, _sub, filetype = struct.unpack_from('<IIII', data, 0)+ if magic != MACHO_MAGIC_64 or cputype != CPU_TYPE_ARM64:+ return False, f'not an arm64 Mach-O executable (magic 0x{magic:08x})'+ if filetype != MH_EXECUTE:+ return False, f'filetype {filetype} is not MH_EXECUTE'+ plat = macho_platform(data)+ if plat is not None and plat != PLATFORM_IOS:+ return False, f'platform {plat} is not iOS ({PLATFORM_IOS})'+ return True, f'arm64 MH_EXECUTE{"" if plat is None else f", platform {plat}"}, {len(data)} bytes'+++def macho_platform(data: bytes) -> int | None:+ """`LC_BUILD_VERSION`'s platform, or None when the binary has no such load command."""+ try:+ ncmds, _sizeofcmds = struct.unpack_from('<II', data, 16)+ except struct.error:+ return None+ off = 32+ for _ in range(ncmds):+ try:+ cmd, size = struct.unpack_from('<II', data, off)+ except struct.error:+ return None+ if cmd == 0x32: # LC_BUILD_VERSION+ try:+ return struct.unpack_from('<I', data, off + 8)[0]+ except struct.error:+ return None+ if size < 8:+ return None+ off += size+ return None+++# ---------------------------------------------------------------- the whole picture++def check_all(deep: bool = False) -> list[Probe]:+ """Every component, in the order the dependency panel shows them.++ `deep` adds the compile / link / Metal probes. They take a few seconds, so the panel runs+ them on a background thread; a shallow check is enough to say "not found" fast.+ """+ out: list[Probe] = []+ cfg = load_config()+ if '_error' in cfg:+ out.append(Probe('toolchain_json', 'toolchain.json', 'wrong', cfg['_error'],+ 'fix the JSON, or delete the file to fall back to auto-detection',+ pinned='', required=False))++ # ---- LLVM+ root = llvm_dir()+ clang = llvm_tool('clang')+ if not root or not clang:+ out.append(Probe(+ 'llvm', f'LLVM (clang {LLVM_MINGW_LLVM})', 'missing',+ 'clang.exe not found', pinned=LLVM_MINGW_ASSETS['AMD64']['name'],+ extra={'download': LLVM_MINGW_ASSETS.get(_arch(), LLVM_MINGW_ASSETS['AMD64'])}))+ else:+ ver = llvm_version(clang)+ if ver:+ out.append(Probe('llvm', 'LLVM (clang)', 'ok', str(clang), path=str(root), version=ver,+ pinned=LLVM_MINGW_LLVM))+ else:+ out.append(Probe('llvm', 'LLVM (clang)', 'wrong',+ f'{clang} does not run (a partial or 32-bit install?)',+ pinned=LLVM_MINGW_LLVM, path=str(root)))++ # ---- the Mach-O linker, which llvm-mingw does not ship under its own name+ lld, lld_note = ensure_ld64_lld()+ if lld:+ out.append(Probe('lld', 'ld64.lld (Mach-O linker)', 'ok', str(lld), hint=lld_note))+ else:+ out.append(Probe('lld', 'ld64.lld (Mach-O linker)', 'missing', lld_note or 'not found',+ pinned='ships with LLVM as ld.lld.exe; renamed automatically'))++ # ---- the SDK+ sdk = ios_sdk()+ if not sdk:+ out.append(Probe('ios_sdk', f'iPhoneOS SDK {SDK_PINNED[:-4]}', 'missing',+ 'no iPhoneOS*.sdk folder',+ hint='Download it in the app, or point toolchain.json "ios_sdk" at one',+ pinned=SDK_PINNED))+ else:+ ver, build = sdk_version(sdk)+ maj = sdk_major(ver)+ if maj >= 26:+ out.append(Probe('ios_sdk', 'iPhoneOS SDK', 'ok', str(sdk), path=str(sdk),+ version=f'{ver} {build}'.strip(), pinned=SDK_PINNED))+ else:+ out.append(Probe('ios_sdk', 'iPhoneOS SDK', 'wrong',+ f'{sdk} is iOS {ver or "?"}; the app needs 26.0 or later (Metal 4)',+ pinned=SDK_PINNED, path=str(sdk), version=ver))+ want = os.environ.get(ENV_SDK_SHA)+ if want:+ got = sdk_tree_digest(sdk)+ out.append(Probe('ios_sdk_sha', 'iPhoneOS SDK digest', 'ok' if got == want.lower() else 'wrong',+ got if got == want.lower() else f'{got} (expected {want.lower()})',+ required=False))++ # ---- Metal+ mroot = metal_dir()+ mv = metal_version() if mroot else ''+ metal_ok = bool(metal_tool('metal') and metal_tool('metallib'))+ if metal_ok:+ out.append(Probe('metal', 'Metal Developer Tools', 'ok', str(mroot), path=str(mroot),+ version=mv, pinned=METAL_TOOLS_VERSION))+ else:+ out.append(Probe('metal', 'Metal Developer Tools', 'missing',+ f'not found under {mroot}' if mroot else 'metal.exe / metallib.exe not found',+ hint=METAL_TOOLS_URL, pinned=METAL_TOOLS_VERSION))+ # metal-tt is Apple-internal-only: report it so nobody expects the pipeline archive here+ out.append(Probe('metal_tt', 'metal-tt (pipeline archive)', 'ok' if metal_tool('metal-tt') else 'missing',+ 'available' if metal_tool('metal-tt') else+ 'not in the Windows Metal tools: the offline pipeline archive is disabled here',+ required=False))++ # ---- the rest of the toolchain+ for name, label, hint, req in (+ ('spirv-cross', 'spirv-cross', 'Vulkan SDK for Windows (vulkan.lunarg.com), or a GitHub release', True),+ ('zstd', 'zstd', 'github.com/facebook/zstd/releases (zstd-*-win64.zip)', True),+ ('glslangValidator', 'glslangValidator', 'only OpenGL games need it (Vulkan SDK ships it)', False)):+ p = find_exe(name)+ out.append(Probe(name, label, 'ok' if p else 'missing', str(p or 'not found'),+ hint=hint, required=req, path=str(p or '')))++ # ---- fonts+ f = std_font()+ out.append(Probe('std_font', 'standard font (STD_FONT)', 'ok' if f else 'missing', str(f or ''),+ hint='any TTF with wide Unicode coverage', required=False, path=str(f or '')))++ if deep:+ if sdk and clang:+ ok, detail = probe_compile(sdk, clang)+ out.append(Probe('probe_compile', 'cross-compile probe', 'ok' if ok else 'wrong', detail))+ ok2, detail2 = probe_link(sdk)+ out.append(Probe('probe_link', 'cross-link probe', 'ok' if ok2 else 'wrong', detail2))+ if sdk and metal_ok:+ ok3, detail3 = probe_metal(sdk)+ out.append(Probe('probe_metal', 'Metal compile probe', 'ok' if ok3 else 'wrong', detail3))+ return out+++def missing_required(probes: list[Probe]) -> list[Probe]:+ return [p for p in probes if p.required and not p.ok]+++def _arch() -> str:+ """Which llvm-mingw archive this machine needs."""+ return 'ARM64' if os.environ.get('PROCESSOR_ARCHITECTURE', '').upper() in ('ARM64', 'AARCH64') else 'AMD64'+++def download_asset(arch: str | None = None) -> dict:+ a = LLVM_MINGW_ASSETS.get(arch or _arch(), LLVM_MINGW_ASSETS['AMD64'])+ return dict(a, url=f'https://github.com/mstorsjo/llvm-mingw/releases/download/'+ f'{LLVM_MINGW_VERSION}/{a["name"]}')+++def summary() -> str:+ """One line for the log: what was found, in the order it matters."""+ parts = []+ for p in check_all():+ if not p.required:+ continue+ mark = 'ok' if p.ok else p.state+ parts.append(f'{p.name}: {mark}{"" if not p.version else f" {p.version}"}')+ return '; '.join(parts)diff --git a/frontend-qt/nspb_qt/win/xcodebuild_shim.py b/frontend-qt/nspb_qt/win/xcodebuild_shim.pynew file mode 100644index 00000000..e1813201--- /dev/null+++ b/frontend-qt/nspb_qt/win/xcodebuild_shim.py@@ -0,0 +1,50 @@+"""`xcodebuild` for Windows: answers the questions the pipeline asks, refuses the rest.++The pipeline uses xcodebuild for exactly two things on the IPA path:++* `check_prereqs` wants `shutil.which('xcodebuild')` to succeed — but `driver.py` replaces that+ check entirely, so this is only for a user who runs the upstream script by hand.+* `toolchain()` records `xcodebuild -version` in the shader cache keys, so the same inputs are+ reused across runs. A stable, honest string keeps the key stable.++Anything that would actually *build* (a bare `xcodebuild`, `-project`, `-scheme`) exits non-zero+with a message pointing at the real path, because there is no Xcode here and pretending+otherwise would produce a confusing failure much later.+"""+from __future__ import annotations++import sys+++#: The value recorded in the shader cache keys. It names this shim rather than a fake Xcode+#: version, so a cache built on Windows is never mistaken for one built on a Mac.+VERSION_BANNER = 'xcodebuild (nspb Windows shim; LLVM clang + ld64.lld, no Xcode)'+++def main(argv: list[str] | None = None) -> int:+ a = list(sys.argv[1:] if argv is None else argv)+ if not a:+ print(VERSION_BANNER, file=sys.stderr)+ print('there is no Xcode on Windows: the iOS app is compiled with LLVM clang and linked '+ 'with ld64.lld (see frontend-qt/README.md, "Windows build")', file=sys.stderr)+ return 69 # EX_UNAVAILABLE+ if a[0] in ('-version', '--version'):+ print(VERSION_BANNER)+ return 0+ if a[0] in ('-showBuildSettings', '-showsdks', '-list'):+ return 0 # nothing to list: an empty answer is correct+ if a[0] == '-downloadPlatform':+ print('the iOS SDK is not downloaded through Xcode on Windows: get an iPhoneOS SDK with '+ 'the app, or point toolchain.json "ios_sdk" at one', file=sys.stderr)+ return 69+ if a[0] == '-downloadComponent':+ print('the Metal toolchain is not an Xcode component on Windows: install Apple\'s '+ '"Metal Developer Tools for Windows" instead', file=sys.stderr)+ return 69+ print(f'xcodebuild (Windows): cannot build here ({a[0]}); the Windows path packs the IPA '+ 'directly with LLVM clang + ld64.lld', file=sys.stderr)+ return 69+++if __name__ == '__main__':+ raise SystemExit(main())diff --git a/frontend-qt/nspb_qt/win/xcodegen_shim.py b/frontend-qt/nspb_qt/win/xcodegen_shim.pynew file mode 100644index 00000000..28132931--- /dev/null+++ b/frontend-qt/nspb_qt/win/xcodegen_shim.py@@ -0,0 +1,32 @@+"""`xcodegen` for Windows: there is none, and this says so clearly.++xcodegen is a Swift program that generates `.xcodeproj` bundles. Nothing equivalent exists on+Windows, and none is needed: an Xcode project only makes sense as input to Xcode, which is+macOS-only. On Windows the app is assembled straight into `DmIOS.app` by `build_app.py`, so the+project-file step is not replaced — it is skipped, and `driver.py` marks the `--prepare-xcode`+option as Mac-only.++This stand-in exists for one reason: `check_prereqs` in the upstream script looks for+`xcodegen` on PATH and refuses to start when it is absent. `driver.py` replaces that check, but+a user who runs the upstream script directly should get an actionable message rather than+"xcodegen not found (brew install xcodegen)" — a Homebrew instruction on Windows.+"""+from __future__ import annotations++import sys+++def main(argv: list[str] | None = None) -> int:+ a = list(sys.argv[1:] if argv is not None else (sys.argv[1:] if argv is None else argv))+ if a and a[0] in ('-version', '--version', 'version'):+ print('xcodegen (nspb Windows shim): not used on Windows')+ return 0+ print('xcodegen is not available on Windows and is not needed: the Windows build packs '+ 'DmIOS.app directly (no .xcodeproj is generated). If you are running '+ 'scripts/build_ipa_from_nsp.py by hand, use the app instead, or pass --platform ios '+ 'through the Windows driver (nspb_qt/win/driver.py).', file=sys.stderr)+ return 69+++if __name__ == '__main__':+ raise SystemExit(main())diff --git a/frontend-qt/nspb_qt/win/xcrun_shim.py b/frontend-qt/nspb_qt/win/xcrun_shim.pynew file mode 100644index 00000000..e71eb679--- /dev/null+++ b/frontend-qt/nspb_qt/win/xcrun_shim.py@@ -0,0 +1,183 @@+"""`xcrun` for Windows: the subset of the interface the pipeline actually uses.++Mapped calls, and why each needs translating rather than just forwarding:++``xcrun -sdk iphoneos metal ...``+ Metal Developer Tools for Windows' `metal.exe`. Xcode's `-mios-version-min=X` is not+ understood there; the Windows compiler wants an explicit `-target air64-apple-iosX`, so the+ flag is rewritten. A macOS compile with no target gets `air64-apple-macos<version>`.+``xcrun -sdk ... metallib ...``+ `metallib.exe` of the matching toolchain.+``xcrun -sdk iphoneos clang ...``+ LLVM clang with `-target arm64-apple-ios<deployment> -isysroot <SDK>`. `/dev/null` becomes+ `NUL`, because `compile_check.py` uses `-o /dev/null`.+``xcrun [-sdk ...] --show-sdk-version | --show-sdk-build-version | --show-sdk-path``+ Read from the SDK's `SDKSettings.json` / `SystemVersion.plist`.+``xcrun -f <tool>``+ The path of the mapped tool, or exit 1.++Anything else exits 127 with a message naming the call, so an unmapped step shows up in the+build log as a missing tool instead of silently producing a wrong result.++`metal-tt` is deliberately absent: the Windows Metal tools do not ship it, and pretending it+works would produce a half-written pipeline archive.+"""+from __future__ import annotations++import subprocess+import sys+from pathlib import Path++# Importable both as `nspb_qt.win.xcrun_shim` and as a plain script (the `.cmd` stand-in runs it+# by path, where there is no package context).+if __package__:+ from . import toolchain as tc+ from . import IOS_DEPLOYMENT as _IOS_DEPLOYMENT+else: # pragma: no cover - script mode+ sys.path.insert(0, str(Path(__file__).resolve().parents[2]))+ from nspb_qt.win import toolchain as tc+ from nspb_qt.win import IOS_DEPLOYMENT as _IOS_DEPLOYMENT++#: Metal targets used when the caller gave none. The iOS one matches what upstream passes as+#: `-mios-version-min=18.0` (a Metal language version, not the app's deployment target).+METAL_IOS_TARGET = '18.0'+METAL_MACOS_TARGET = '15.0'+++def metal_args(sdk: str, args: list[str]) -> list[str]:+ """Translate Xcode's Metal flags into what the Windows Metal compiler accepts.++ The important one is the target: the Windows `metal.exe` has no implicit OS, so a compile+ without `-target` produces AIR for the host and `metallib` then refuses to link it.+ """+ out: list[str] = []+ has_target = False+ for a in args:+ if a.startswith('-mios-version-min='):+ out += ['-target', f'air64-apple-ios{a.split("=", 1)[1]}']+ has_target = True+ continue+ if a.startswith(('-mmacosx-version-min=', '-mmacos-version-min=')):+ out += ['-target', f'air64-apple-macos{a.split("=", 1)[1]}']+ has_target = True+ continue+ if a in ('-target', '--target') or a.startswith(('-target=', '--target=')):+ has_target = True+ out.append(a)+ if not has_target and not any(a in ('--version', '-v', '--help', '-version') for a in args):+ tgt = (f'air64-apple-ios{tc.setting("metal_ios_target", METAL_IOS_TARGET)}'+ if sdk.startswith('iphone')+ else f'air64-apple-macos{tc.setting("metal_macos_target", METAL_MACOS_TARGET)}')+ out = ['-target', tgt] + out+ return out+++def clang_args(args: list[str]) -> list[str]:+ sdk = tc.ios_sdk()+ if not sdk:+ _die('no iPhoneOS SDK (download one in the app, or set "ios_sdk" in toolchain.json)')+ fixed = ['NUL' if a == '/dev/null' else a for a in args]+ dep = tc.setting('ios_deployment', _IOS_DEPLOYMENT)+ return ['-target', f'arm64-apple-ios{dep}', '-isysroot', str(sdk)] + fixed+++def _sdk_info(sdk: str, what: str) -> str:+ if sdk.startswith('iphone'):+ p = tc.ios_sdk()+ if not p:+ _die(f'no iPhoneOS SDK for {what}')+ ver, build = tc.sdk_version(p)+ table = {'--show-sdk-path': str(p), '--show-sdk-version': ver,+ '--show-sdk-build-version': build}+ if what in table:+ return table[what]+ _die(f'unsupported query {what}')+ # macOS: there is no macOS SDK here. The Metal tools' own folder name identifies the+ # toolchain for the caches that key on it.+ root = tc.metal_dir()+ if what == '--show-sdk-path':+ return str(root or '')+ if what == '--show-sdk-version':+ return 'windows-metal-tools'+ if what == '--show-sdk-build-version':+ return root.name if root else 'missing'+ _die(f'unsupported query {what}')+++TOOL_MAP = {+ 'strip': 'llvm-strip', 'nm': 'llvm-nm', 'otool': 'llvm-otool', 'lipo': 'llvm-lipo',+ 'objdump': 'llvm-objdump', 'ar': 'llvm-ar', 'libtool': 'llvm-ar', 'ranlib': 'llvm-ranlib',+ 'dsymutil': 'llvm-dsymutil',+}+++def find(sdk: str, tool: str) -> Path | None:+ """The Windows executable standing in for one xcrun tool."""+ if tool in ('metal', 'metallib', 'metal-objdump', 'metal-ar'):+ return tc.metal_tool(tool, sdk)+ if tool in ('clang', 'clang++'):+ return tc.llvm_tool('clang')+ if tool in ('ld', 'ld64', 'ld64.lld'):+ lld, _note = tc.ensure_ld64_lld()+ return lld+ if tool == 'swiftc':+ return None # no Swift toolchain: win/ios/Launcher.m replaces Launcher.swift+ if tool == 'actool':+ return None # the asset catalog is replaced by loose PNGs+ if tool == 'metal-tt':+ return None # not shipped by Apple's Windows Metal tools+ if tool in TOOL_MAP:+ return tc.llvm_tool(TOOL_MAP[tool])+ return tc.llvm_tool(tool)+++def _die(msg: str, code: int = 127) -> None:+ print(f'xcrun (Windows): {msg}', file=sys.stderr)+ raise SystemExit(code)+++def main(argv: list[str] | None = None) -> int:+ sdk = 'macosx'+ a = list(sys.argv[1:] if argv is None else argv)+ while a and a[0].startswith('-'):+ if a[0] in ('-sdk', '--sdk') and len(a) > 1:+ sdk = a[1]+ a = a[2:]+ elif a[0] in ('--show-sdk-version', '--show-sdk-build-version', '--show-sdk-path'):+ print(_sdk_info(sdk, a[0]))+ return 0+ elif a[0] in ('-r', '--run'):+ a = a[1:]+ elif a[0] in ('-f', '--find'):+ if len(a) < 2:+ _die('-f needs a tool name')+ t = find(sdk, a[1])+ print(t or '')+ return 0 if t else 1+ elif a[0] == '--version':+ print('xcrun (nspb Windows shim)')+ return 0+ else:+ _die('unsupported option ' + a[0])+ if not a:+ _die('no tool named')+ tool, rest = a[0], a[1:]+ exe = find(sdk, tool)+ if not exe:+ _die(f'no Windows tool for `xcrun -sdk {sdk} {tool}`'+ + (' (the Windows Metal tools do not ship metal-tt)' if tool == 'metal-tt' else+ ' (the app is built with clang + ld64.lld, not Swift or actool)'+ if tool in ('swiftc', 'actool') else+ ' (see the Windows build section of frontend-qt/README.md)'))+ if tool == 'metal':+ rest = metal_args(sdk, rest)+ elif tool == 'clang':+ rest = clang_args(rest)+ try:+ return subprocess.run([str(exe)] + rest).returncode+ except OSError as e:+ _die(f'cannot start {exe}: {e}')+++if __name__ == '__main__':+ raise SystemExit(main())diff --git a/frontend-qt/tests/test_win.py b/frontend-qt/tests/test_win.pynew file mode 100644index 00000000..d2d96a32--- /dev/null+++ b/frontend-qt/tests/test_win.py@@ -0,0 +1,842 @@+"""Tests for the Windows build path that can run on macOS.++The Windows modules are written so that everything except the actual toolchain invocations is+testable without Windows: the discovery logic takes its paths from environment variables and+`toolchain.json`, the Makefile source-list check reads text, the IPA mode fixer works on any zip,+and the driver's patches can be inspected without loading the upstream script.++What is **not** covered here, and must be checked on a real Windows machine:++* `probe_compile` / `probe_link` / `probe_metal` against a genuine LLVM-MinGW, iPhoneOS SDK and+ Metal Developer Tools install;+* the compile and link of the real host sources, and `ios/Launcher.m` against UIKit;+* a full `python -m nspb_qt.win.driver` run on a game folder.++Those need the toolchain; the helpers below assert the parts that decide *whether* they would be+attempted with the right arguments.++ python3 -m unittest discover -s frontend-qt/tests -v+"""+from __future__ import annotations++import json+import os+import subprocess+import sys+import tempfile+import unittest+import zipfile+from pathlib import Path+from unittest import mock++HERE = Path(__file__).resolve().parent+QT = HERE.parent+sys.path.insert(0, str(QT))++from nspb_qt.win import build_app, fix_ipa_modes, shim # noqa: E402+from nspb_qt.win import toolchain as tc # noqa: E402+++# ---------------------------------------------------------------- helpers++def make_fake_sdk(root: Path, version: str = '26.0') -> Path:+ """A directory that looks like an iPhoneOS SDK to `toolchain.is_sdk_dir`."""+ sdk = root / f'iPhoneOS{version}.sdk'+ (sdk / 'System/Library/Frameworks/UIKit.framework/Headers').mkdir(parents=True)+ (sdk / 'System/Library/Frameworks/Foundation.framework').mkdir(parents=True)+ (sdk / 'usr/lib').mkdir(parents=True)+ (sdk / 'SDKSettings.json').write_text(json.dumps({'Version': version}), encoding='utf-8')+ (sdk / 'System/Library/Frameworks/UIKit.framework/UIKit.tbd').write_text('---', encoding='utf-8')+ (sdk / 'System/Library/Frameworks/UIKit.framework/Headers/UIKit.h').write_text(+ '// fake', encoding='utf-8')+ (sdk / 'usr/lib/libSystem.tbd').write_text('---', encoding='utf-8')+ return sdk+++def make_fake_llvm(root: Path, with_lld64: bool = True, with_macho: bool = True) -> Path:+ """An LLVM folder with executable stubs named like the real tools."""+ llvm = root / 'LLVM'+ (llvm / 'bin').mkdir(parents=True)+ (llvm / 'bin/clang.exe').write_bytes(b'stub')+ (llvm / 'bin/ld.lld.exe').write_bytes(b'MachO ld64.lld darwin' if with_macho else b'ELF only')+ if with_lld64:+ (llvm / 'bin/ld64.lld.exe').write_bytes(b'MachO ld64.lld darwin')+ return llvm+++class ToolchainDiscoveryTest(unittest.TestCase):+ """The three-level search: environment, then toolchain.json, then known locations."""++ def setUp(self) -> None:+ self.tmp = tempfile.TemporaryDirectory()+ self.root = Path(self.tmp.name)+ self.env = mock.patch.dict(os.environ, {}, clear=False)+ self.env.start()+ for k in ('NSPB_LLVM_DIR', 'NSPB_IOS_SDK', 'NSPB_METAL_DIR', 'NSPB_TOOLCHAIN_JSON',+ 'NSPB_IOS_SDK_SHA256', 'ProgramFiles', 'ProgramFiles(x86)', 'LOCALAPPDATA'):+ os.environ.pop(k, None)+ os.environ['LOCALAPPDATA'] = str(self.root / 'LocalAppData')++ def tearDown(self) -> None:+ self.env.stop()+ self.tmp.cleanup()++ def test_llvm_found_from_env(self) -> None:+ llvm = make_fake_llvm(self.root)+ os.environ['NSPB_LLVM_DIR'] = str(llvm)+ self.assertEqual(tc.llvm_dir(), llvm)+ self.assertEqual(tc.llvm_tool('clang'), llvm / 'bin/clang.exe')++ def test_llvm_found_from_toolchain_json(self) -> None:+ llvm = make_fake_llvm(self.root)+ cfg = self.root / 'toolchain.json'+ cfg.write_text(json.dumps({'llvm_dir': str(llvm)}), encoding='utf-8')+ os.environ['NSPB_TOOLCHAIN_JSON'] = str(cfg)+ self.assertEqual(tc.llvm_dir(), llvm)++ def test_env_beats_toolchain_json(self) -> None:+ env_llvm = make_fake_llvm(self.root / 'a')+ cfg_llvm = make_fake_llvm(self.root / 'b')+ cfg = self.root / 'toolchain.json'+ cfg.write_text(json.dumps({'llvm_dir': str(cfg_llvm)}), encoding='utf-8')+ os.environ['NSPB_TOOLCHAIN_JSON'] = str(cfg)+ os.environ['NSPB_LLVM_DIR'] = str(env_llvm)+ self.assertEqual(tc.llvm_dir(), env_llvm)++ def test_broken_toolchain_json_does_not_raise(self) -> None:+ cfg = self.root / 'toolchain.json'+ cfg.write_text('{not json', encoding='utf-8')+ os.environ['NSPB_TOOLCHAIN_JSON'] = str(cfg)+ self.assertIn('_error', tc.load_config())+ # discovery still works: it falls through to the other levels+ llvm = make_fake_llvm(self.root)+ os.environ['NSPB_LLVM_DIR'] = str(llvm)+ self.assertEqual(tc.llvm_dir(), llvm)++ def test_no_llvm_returns_none(self) -> None:+ with mock.patch.object(tc.shutil, 'which', return_value=None):+ self.assertIsNone(tc.llvm_dir())+++class Ld64Test(unittest.TestCase):+ """`ld64.lld.exe` does not ship with llvm-mingw; the copy from `ld.lld.exe` replaces it."""++ def setUp(self) -> None:+ self.tmp = tempfile.TemporaryDirectory()+ self.root = Path(self.tmp.name)+ self.env = mock.patch.dict(os.environ, {}, clear=False)+ self.env.start()+ for k in ('ProgramFiles', 'ProgramFiles(x86)', 'LOCALAPPDATA'):+ os.environ.pop(k, None)+ os.environ['LOCALAPPDATA'] = str(self.root / 'local')++ def tearDown(self) -> None:+ self.env.stop()+ self.tmp.cleanup()++ def test_lld_has_macho_reads_driver_strings(self) -> None:+ llvm = make_fake_llvm(self.root, with_lld64=False, with_macho=True)+ self.assertTrue(tc._lld_has_macho(llvm / 'bin/ld.lld.exe'))++ def test_stripped_lld_is_reported(self) -> None:+ llvm = make_fake_llvm(self.root, with_lld64=False, with_macho=False)+ os.environ['NSPB_LLVM_DIR'] = str(llvm)+ got, note = tc.ensure_ld64_lld()+ self.assertIsNone(got)+ self.assertIn('no Mach-O driver', note)++ def test_copy_created_when_absent(self) -> None:+ llvm = make_fake_llvm(self.root, with_lld64=False, with_macho=True)+ os.environ['NSPB_LLVM_DIR'] = str(llvm)+ got, note = tc.ensure_ld64_lld()+ self.assertIsNotNone(got)+ self.assertEqual(got.name, 'ld64.lld.exe')+ self.assertTrue(got.is_file())+ # idempotent: the second call finds it instead of making another+ again, note2 = tc.ensure_ld64_lld()+ self.assertEqual(again, got)+ self.assertEqual(note2, '')++ def test_existing_ld64_lld_wins(self) -> None:+ llvm = make_fake_llvm(self.root, with_lld64=True)+ os.environ['NSPB_LLVM_DIR'] = str(llvm)+ got, note = tc.ensure_ld64_lld()+ self.assertEqual(got, llvm / 'bin/ld64.lld.exe')+ self.assertEqual(note, '')+++class SdkTest(unittest.TestCase):+ def setUp(self) -> None:+ self.tmp = tempfile.TemporaryDirectory()+ self.root = Path(self.tmp.name)+ self.env = mock.patch.dict(os.environ, {}, clear=False)+ self.env.start()+ for k in ('NSPB_IOS_SDK', 'LOCALAPPDATA'):+ os.environ.pop(k, None)+ os.environ['LOCALAPPDATA'] = str(self.root / 'local')++ def tearDown(self) -> None:+ self.env.stop()+ self.tmp.cleanup()++ def test_is_sdk_dir_accepts_a_real_layout(self) -> None:+ sdk = make_fake_sdk(self.root)+ self.assertTrue(tc.is_sdk_dir(sdk))++ def test_is_sdk_dir_rejects_a_plain_folder(self) -> None:+ plain = self.root / 'iPhoneOS26.0.sdk'+ plain.mkdir()+ self.assertFalse(tc.is_sdk_dir(plain))++ def test_is_sdk_dir_rejects_missing_stubs(self) -> None:+ sdk = make_fake_sdk(self.root)+ import shutil as sh+ sh.rmtree(sdk / 'System/Library/Frameworks/UIKit.framework')+ sh.rmtree(sdk / 'System/Library/Frameworks/Foundation.framework')+ self.assertFalse(tc.is_sdk_dir(sdk))++ def test_sdk_found_from_env(self) -> None:+ sdk = make_fake_sdk(self.root)+ os.environ['NSPB_IOS_SDK'] = str(sdk)+ self.assertEqual(tc.ios_sdk(), sdk)++ def test_sdk_version_parsed(self) -> None:+ sdk = make_fake_sdk(self.root, '26.5')+ self.assertEqual(tc.sdk_version(sdk)[0], '26.5')+ self.assertEqual(tc.sdk_major('26.5'), 26)+ self.assertEqual(tc.sdk_major(''), 0)++ def test_sdk_tree_digest_is_stable_and_discriminating(self) -> None:+ a = make_fake_sdk(self.root / 'a', '26.0')+ b = make_fake_sdk(self.root / 'b', '26.5')+ self.assertEqual(tc.sdk_tree_digest(a), tc.sdk_tree_digest(a))+ self.assertNotEqual(tc.sdk_tree_digest(a), tc.sdk_tree_digest(b))+++class CheckAllTest(unittest.TestCase):+ """The panel's rows, on a machine with nothing installed and with a fake toolchain."""++ def setUp(self) -> None:+ self.tmp = tempfile.TemporaryDirectory()+ self.root = Path(self.tmp.name)+ self.env = mock.patch.dict(os.environ, {}, clear=False)+ self.env.start()+ for k in ('NSPB_LLVM_DIR', 'NSPB_IOS_SDK', 'NSPB_METAL_DIR', 'NSPB_TOOLCHAIN_JSON',+ 'ProgramFiles', 'ProgramFiles(x86)', 'LOCALAPPDATA'):+ os.environ.pop(k, None)+ os.environ['LOCALAPPDATA'] = str(self.root / 'local')+ os.environ['ProgramFiles'] = str(self.root / 'PF')+ self.which = mock.patch.object(tc.shutil, 'which', return_value=None)+ self.which.start()++ def tearDown(self) -> None:+ self.which.stop()+ self.env.stop()+ self.tmp.cleanup()++ def test_nothing_installed_reports_missing(self) -> None:+ probes = tc.check_all(deep=False)+ ids = {p.id: p for p in probes}+ self.assertEqual(ids['llvm'].state, 'missing')+ self.assertEqual(ids['ios_sdk'].state, 'missing')+ self.assertEqual(ids['metal'].state, 'missing')+ self.assertFalse(ids['lld'].ok)+ # metal-tt is optional and must never be required+ self.assertFalse(ids['metal_tt'].required)++ def test_a_fake_toolchain_turns_rows_ok(self) -> None:+ llvm = make_fake_llvm(self.root, with_lld64=False, with_macho=True)+ sdk = make_fake_sdk(self.root)+ metal = self.root / 'Metal Developer Tools'+ (metal / 'bin').mkdir(parents=True)+ (metal / 'bin/metal.exe').write_bytes(b'stub')+ (metal / 'bin/metallib.exe').write_bytes(b'stub')+ os.environ['NSPB_LLVM_DIR'] = str(llvm)+ os.environ['NSPB_IOS_SDK'] = str(sdk)+ os.environ['NSPB_METAL_DIR'] = str(metal)+ ids = {p.id: p for p in tc.check_all(deep=False)}+ self.assertTrue(ids['lld'].ok, ids['lld'])+ self.assertTrue(ids['ios_sdk'].ok, ids['ios_sdk'])+ self.assertTrue(ids['metal'].ok, ids['metal'])+ self.assertEqual(ids['ios_sdk'].version.split()[0], '26.0')++ def test_old_sdk_is_wrong_not_ok(self) -> None:+ sdk = make_fake_sdk(self.root, '17.0')+ os.environ['NSPB_IOS_SDK'] = str(sdk)+ ids = {p.id: p for p in tc.check_all(deep=False)}+ self.assertEqual(ids['ios_sdk'].state, 'wrong')+ self.assertIn('26.0', ids['ios_sdk'].detail)++ def test_deep_probes_run_only_with_tools(self) -> None:+ # nothing installed: no probe rows at all, rather than three failures+ ids = {p.id for p in tc.check_all(deep=True)}+ self.assertNotIn('probe_compile', ids)+ self.assertNotIn('probe_link', ids)+++class MetalArgsTest(unittest.TestCase):+ """Xcode's Metal flags become the Windows compiler's `-target` triple."""++ def test_ios_version_min_becomes_target(self) -> None:+ from nspb_qt.win import xcrun_shim+ got = xcrun_shim.metal_args('iphoneos', ['-c', '-mios-version-min=18.0', 'a.metal'])+ self.assertIn('-target', got)+ self.assertIn('air64-apple-ios18.0', got)+ self.assertNotIn('-mios-version-min=18.0', got)++ def test_macos_version_min_becomes_target(self) -> None:+ from nspb_qt.win import xcrun_shim+ got = xcrun_shim.metal_args('macosx', ['-c', '-mmacosx-version-min=14.0', 'a.metal'])+ self.assertIn('air64-apple-macos14.0', got)++ def test_missing_target_gets_the_default(self) -> None:+ from nspb_qt.win import xcrun_shim+ got = xcrun_shim.metal_args('iphoneos', ['-c', 'a.metal'])+ self.assertEqual(got[:2], ['-target', 'air64-apple-ios18.0'])++ def test_version_query_is_left_alone(self) -> None:+ from nspb_qt.win import xcrun_shim+ self.assertEqual(xcrun_shim.metal_args('iphoneos', ['--version']), ['--version'])++ def test_explicit_target_is_not_duplicated(self) -> None:+ from nspb_qt.win import xcrun_shim+ got = xcrun_shim.metal_args('iphoneos', ['-target', 'air64-apple-ios26.0', '-c'])+ self.assertEqual(got.count('-target'), 1)++ def test_metal_tt_has_no_windows_tool(self) -> None:+ # the pipeline archive is disabled here, and the caller relies on this being None+ self.assertIsNone(tc.metal_tool('metal-tt'))++ def test_metal_tool_takes_name_then_sdk(self) -> None:+ """The signature is (name, sdk). Both call sites once had it backwards, which made+ every `xcrun -sdk iphoneos metal` fall back to a slow Python wrapper instead of+ starting metal.exe directly -- a cost paid once per shader."""+ with tempfile.TemporaryDirectory() as td:+ root = Path(td)+ (root / 'bin').mkdir()+ (root / 'bin/metal.exe').write_bytes(b'x')+ (root / 'ios/bin').mkdir(parents=True)+ (root / 'ios/bin/metal.exe').write_bytes(b'ios')+ old = os.environ.get('NSPB_METAL_DIR')+ os.environ['NSPB_METAL_DIR'] = str(root)+ try:+ self.assertIsNotNone(tc.metal_tool('metal', 'iphoneos'))+ self.assertIsNotNone(tc.metal_tool('metal', 'macosx'))+ # the reversed call is what the bug looked like: it silently returns None+ self.assertIsNone(tc.metal_tool('iphoneos', 'metal'))+ finally:+ if old is None:+ os.environ.pop('NSPB_METAL_DIR', None)+ else:+ os.environ['NSPB_METAL_DIR'] = old+++class HostSourcesTest(unittest.TestCase):+ """The Makefile rules are reproduced, and a change upstream stops the build."""++ def setUp(self) -> None:+ self.repo = QT.parent+ self.gen = Path(tempfile.mkdtemp())+ (self.gen / 'game_profile.h').write_text('// x', encoding='utf-8')++ def tearDown(self) -> None:+ import shutil+ shutil.rmtree(self.gen, ignore_errors=True)++ def test_source_list_matches_the_makefile(self) -> None:+ files, incs = build_app.host_sources(self.repo, self.gen)+ names = {p.name for p in files}+ # from SRC=+ for must in ('loader.c', 'hle.c', 'romfs_arc.c', 'crash.c', 'probe.c', 'thread.c',+ 'memstat.m', 'haptics_apple.m', 'entry.S', 'main.c'):+ self.assertIn(must, names, f'{must} missing from the host source list')+ # Mac-only sources are dropped+ self.assertNotIn('front_mac.m', names)+ # the iOS front end is compiled by the iOS project, not the host walk+ self.assertNotIn('front_ios.m', names)+ self.assertNotIn('main.m', names)+ # and main.c is in+ self.assertIn('main.c', names)+ # include dirs include the ones the Makefile's compile line names+ inc_str = ' '.join(str(i) for i in incs)+ self.assertIn('gfx/nvn/include', inc_str.replace('\\', '/'))+ self.assertIn('stb_vorbis', inc_str.replace('\\', '/'))+ self.assertIn('libvpx', inc_str.replace('\\', '/'))++ def test_libvpx_sources_are_included(self) -> None:+ files, _ = build_app.host_sources(self.repo, self.gen)+ vpx = [p for p in files if 'third_party/libvpx' in p.as_posix()]+ self.assertTrue(vpx, 'no libvpx sources: the host would fail to link its movie decoder')++ def test_a_changed_makefile_stops_the_build(self) -> None:+ # simulate an upstream edit by pointing at a repository copy with a modified Makefile+ with tempfile.TemporaryDirectory() as td:+ fake = Path(td) / 'repo'+ (fake / 'dm/host').mkdir(parents=True)+ makefile = (self.repo / 'dm/host/Makefile').read_text(encoding='utf-8')+ (fake / 'dm/host/Makefile').write_text(+ makefile.replace('romfs_arc.c ', 'romfs_arc.c newfile.c '), encoding='utf-8')+ with self.assertRaises(SystemExit) as ctx:+ build_app.host_sources(fake, self.gen)+ # host_sources() reports through build_app.die(), which raises SystemExit(1); the+ # message itself goes to stdout, so capture it instead of reading the exception+ self.assertEqual(ctx.exception.code, 1)++ def test_missing_source_stops_the_build(self) -> None:+ with tempfile.TemporaryDirectory() as td:+ fake = Path(td) / 'repo'+ (fake / 'dm/host').mkdir(parents=True)+ makefile = (self.repo / 'dm/host/Makefile').read_text(encoding='utf-8')+ (fake / 'dm/host/Makefile').write_text(makefile, encoding='utf-8')+ # the Makefile is intact but the sources are not there+ with self.assertRaises(SystemExit) as ctx:+ build_app.host_sources(fake, self.gen)+ self.assertEqual(ctx.exception.code, 1)++ def test_frameworks_drop_cocoa_and_keep_what_exists(self) -> None:+ sdk = make_fake_sdk(Path(tempfile.mkdtemp()))+ try:+ (sdk / 'System/Library/Frameworks/Metal.framework').mkdir(parents=True)+ fws = build_app.framework_list(sdk, [])+ self.assertNotIn('Cocoa', fws)+ self.assertIn('Metal', fws)+ self.assertIn('UIKit', fws)+ self.assertNotIn('AVFAudio', fws) # not in this fake SDK+ finally:+ import shutil+ shutil.rmtree(sdk.parent, ignore_errors=True)+++class InfoPlistTest(unittest.TestCase):+ def test_keys_the_app_reads_are_present(self) -> None:+ p = build_app.info_plist(bundle_id='org.example.1', name='Game', version='1.2.3',+ category='public.app-category.games', show_fps='YES',+ lang='ja', sdk_ver='26.0', sdk_build='23A1', icons=True,+ executable='DmIOS', deployment='26.0')+ self.assertEqual(p['CFBundleIdentifier'], 'org.example.1')+ self.assertEqual(p['CFBundleExecutable'], 'DmIOS')+ self.assertEqual(p['MinimumOSVersion'], '26.0')+ self.assertEqual(p['DTSDKName'], 'iphoneos26.0')+ # read by main.m / the launcher+ self.assertEqual(p['DMShowFPS'], 'YES')+ self.assertEqual(p['DMLanguage'], 'ja')+ self.assertIn('CFBundleIcons', p)+ self.assertIn('UIApplicationSceneManifest', p)+ self.assertEqual(p['UIRequiredDeviceCapabilities'], ['arm64'])++ def test_without_icons_no_icon_keys(self) -> None:+ p = build_app.info_plist(bundle_id='b', name='n', version='1', category='c',+ show_fps='NO', lang='en-US', sdk_ver='26.0', sdk_build='',+ icons=False, executable='DmIOS', deployment='26.0')+ self.assertNotIn('CFBundleIcons', p)+++class IpaModesTest(unittest.TestCase):+ """The zip mode fixer, which stands in for `pack_ipa.py --exec` (an upstream file we+ must not edit)."""++ def _make_ipa(self, path: Path, exec_mode: int = 0o666) -> None:+ with zipfile.ZipFile(path, 'w') as z:+ z.writestr('Payload/DmIOS.app/DmIOS', b'\xcf\xfa\xed\xfe' + b'\0' * 28)+ z.writestr('Payload/DmIOS.app/Info.plist', b'plist')+ z.writestr('Payload/DmIOS.app/dm/shader_map.tsv', b'x')+ z.writestr('Payload/', b'')++ def test_executable_gets_the_execute_bit(self) -> None:+ with tempfile.TemporaryDirectory() as td:+ ipa = Path(td) / 'a.ipa'+ self._make_ipa(ipa)+ fixed = fix_ipa_modes.fix(ipa, ['Payload/DmIOS.app/DmIOS'])+ self.assertIn('Payload/DmIOS.app/DmIOS', fixed)+ ok, detail = fix_ipa_modes.verify(ipa, ['Payload/DmIOS.app/DmIOS'])+ self.assertTrue(ok, detail)+ self.assertIn('0o100755', detail)++ def test_data_files_get_0644(self) -> None:+ with tempfile.TemporaryDirectory() as td:+ ipa = Path(td) / 'a.ipa'+ self._make_ipa(ipa)+ fix_ipa_modes.fix(ipa, ['Payload/DmIOS.app/DmIOS'])+ modes = _zip_modes(ipa)+ self.assertEqual(modes['Payload/DmIOS.app/Info.plist'], 0o100644)+ self.assertEqual(modes['Payload/DmIOS.app/dm/shader_map.tsv'], 0o100644)+ self.assertEqual(modes['Payload/DmIOS.app/DmIOS'], 0o100755)++ def test_a_mac_built_ipa_is_left_alone(self) -> None:+ with tempfile.TemporaryDirectory() as td:+ ipa = Path(td) / 'a.ipa'+ with zipfile.ZipFile(ipa, 'w') as z:+ # what Info-ZIP / pack_ipa writes on a Mac+ for name, mode in (('Payload/DmIOS.app/DmIOS', 0o100755),+ ('Payload/DmIOS.app/Info.plist', 0o100644)):+ info = zipfile.ZipInfo(name)+ info.external_attr = mode << 16+ z.writestr(info, b'data')+ before = ipa.read_bytes()+ note = fix_ipa_modes.fix(ipa, ['Payload/DmIOS.app/DmIOS'])+ self.assertEqual(note, 'already correct')+ self.assertEqual(before, ipa.read_bytes(), 'a correct archive must not be rewritten')++ def test_idempotent(self) -> None:+ with tempfile.TemporaryDirectory() as td:+ ipa = Path(td) / 'a.ipa'+ self._make_ipa(ipa)+ fix_ipa_modes.fix(ipa, ['Payload/DmIOS.app/DmIOS'])+ once = ipa.read_bytes()+ self.assertEqual(fix_ipa_modes.fix(ipa, ['Payload/DmIOS.app/DmIOS']), 'already correct')+ self.assertEqual(once, ipa.read_bytes())++ def test_missing_executable_is_reported(self) -> None:+ with tempfile.TemporaryDirectory() as td:+ ipa = Path(td) / 'a.ipa'+ self._make_ipa(ipa)+ note = fix_ipa_modes.fix(ipa, ['Payload/DmIOS.app/NotThere'])+ self.assertIn('missing from the archive', note)++ def test_not_a_zip_raises(self) -> None:+ with tempfile.TemporaryDirectory() as td:+ bad = Path(td) / 'x.ipa'+ bad.write_bytes(b'not a zip at all')+ with self.assertRaises(fix_ipa_modes.IpaModeError):+ fix_ipa_modes.fix(bad, ['Payload/DmIOS.app/DmIOS'])+++def _zip_modes(path: Path) -> dict[str, int]:+ out = {}+ with zipfile.ZipFile(path) as z:+ for info in z.infolist():+ out[info.filename] = (info.external_attr >> 16) & 0xFFFF+ return out+++class ShimTest(unittest.TestCase):+ def test_install_is_idempotent(self) -> None:+ with tempfile.TemporaryDirectory() as td:+ d = Path(td)+ shim.install(d, python_exe=sys.executable)+ first = {p.name: p.read_bytes() for p in d.iterdir()}+ shim.install(d, python_exe=sys.executable)+ second = {p.name: p.read_bytes() for p in d.iterdir()}+ self.assertEqual(first, second)+ self.assertIn('sitecustomize.py', first)+ for name in ('xcrun.cmd', 'xcodebuild.cmd', 'xcodegen.cmd', 'python3.cmd'):+ self.assertIn(name, first, f'{name} stand-in not written')++ def test_sitecustomize_is_valid_python(self) -> None:+ import ast+ ast.parse(shim._SITECUSTOMIZE_SRC)++ def test_sitecustomize_maps_the_commands_we_depend_on(self) -> None:+ src = shim._SITECUSTOMIZE_SRC+ # every rewrite the pipeline needs, asserted against the generated text so a future+ # edit cannot silently drop one+ for needle in ("base in ('xcrun', 'xcrun.exe')",+ "base == 'dmsh_xlate'",+ "base in ('python3', 'python3.exe')",+ "dm/ios/tools/build_ipa.sh",+ "base in ('which', 'which.exe')",+ "sys.modules['pwd'] = _pwd",+ 'BCryptDecrypt'):+ self.assertIn(needle, src, f'{needle} missing from the shim')++ def test_build_env_prepends_the_shim(self) -> None:+ with tempfile.TemporaryDirectory() as td:+ with mock.patch.object(shim, 'shim_dir', return_value=Path(td)):+ env = shim.build_env({'PATH': 'C:\\Windows', 'PYTHONPATH': ''},+ python_exe=sys.executable)+ self.assertTrue(env['PATH'].startswith(td))+ self.assertTrue(env['PYTHONPATH'].startswith(td))+ self.assertEqual(env['PYTHONUTF8'], '1')+++class DriverCliTest(unittest.TestCase):+ """Mac-only options are refused before any work starts."""++ def test_prepare_xcode_refused(self) -> None:+ from nspb_qt.win import driver+ with self.assertRaises(SystemExit) as ctx:+ driver.check_cli(['D:\\games\\x', '--prepare-xcode'])+ self.assertIn('needs Xcode', str(ctx.exception))++ def test_platform_ios_allowed(self) -> None:+ from nspb_qt.win import driver+ driver.check_cli(['D:\\games\\x', '--platform', 'ios'])++ def test_platform_mac_refused(self) -> None:+ from nspb_qt.win import driver+ with self.assertRaises(SystemExit) as ctx:+ driver.check_cli(['D:\\games\\x', '--platform', 'mac'])+ self.assertIn('macOS', str(ctx.exception))++ def test_platform_mac_app_refused(self) -> None:+ from nspb_qt.win import driver+ with self.assertRaises(SystemExit):+ driver.check_cli(['--platform=mac-app'])++ def test_newer_upstream_works_are_still_refused(self) -> None:+ from nspb_qt.win import driver+ self.assertIn('--prepare-xcode', driver.REFUSED_OPTIONS)+ self.assertIn('--platform', driver.REFUSED_OPTIONS)+++class DriverPatchTest(unittest.TestCase):+ """The upstream module loads and its Mac-only functions get replaced."""++ @classmethod+ def setUpClass(cls) -> None:+ from nspb_qt.win import driver+ cls.driver = driver+ cls.repo = QT.parent+ if not (cls.repo / 'scripts/build_ipa_from_nsp.py').is_file():+ raise unittest.SkipTest('not a repository checkout')+ # `pwd` is installed by the stub inside load_upstream, so this works on any OS+ cls.saved = {k: os.environ.get(k) for k in+ ('NSPB_ALLOW_NON_WINDOWS', 'GAME', 'W')}+ cls.mod = driver.load_upstream(cls.repo)+ driver.patch(cls.mod, cls.repo)++ @classmethod+ def tearDownClass(cls) -> None:+ for k, v in cls.saved.items():+ if v is None:+ os.environ.pop(k, None)+ else:+ os.environ[k] = v++ def test_upstream_loaded(self) -> None:+ self.assertTrue(hasattr(self.mod, 'cli'))+ self.assertTrue(hasattr(self.mod, 'BuildError'))++ def test_mac_only_functions_refuse(self) -> None:+ with self.assertRaises(self.mod.BuildError) as ctx:+ self.mod.build_mac_host(self.repo, Path('out'), {}, Path('logs'), None)+ self.assertIn('arm64', str(ctx.exception))+ with self.assertRaises(self.mod.BuildError):+ self.mod.capture_shaders(None, None, None, None, {}, None, None, 'gl')+ with self.assertRaises(self.mod.BuildError):+ self.mod.mac_app()+ with self.assertRaises(self.mod.BuildError):+ self.mod.mac_run()++ def test_can_clone_is_false_and_apple_silicon_true(self) -> None:+ self.assertFalse(self.mod.can_clone(Path('.')))+ self.assertTrue(self.mod.apple_silicon())++ def test_check_prereqs_raises_with_a_report(self) -> None:+ with self.assertRaises(self.mod.BuildError) as ctx:+ self.mod.check_prereqs({}, Path('missing/dmsh_xlate'), mac=False)+ msg = str(ctx.exception)+ self.assertIn('missing on this PC', msg)+ # the message must name what to do, not just what is wrong+ self.assertTrue('LLVM' in msg or 'clang' in msg.lower())++ def test_check_prereqs_refuses_mac(self) -> None:+ with self.assertRaises(self.mod.BuildError) as ctx:+ self.mod.check_prereqs({}, Path('x'), mac=True)+ self.assertIn('need a Mac', str(ctx.exception))++ def test_toolchain_probe_uses_the_windows_metal(self) -> None:+ probes = self.mod.toolchain()+ self.assertTrue(probes)+ joined = ' '.join(' '.join(p[1]) for p in probes if p[0] == 'cmd')+ self.assertIn('xcrun_shim.py', joined)+ self.assertIn('metal', joined)+ self.assertNotIn('xcodebuild', joined)++ def test_tool_paths_are_replaced_not_extended(self) -> None:+ """On Windows the upstream macOS list must be gone.++ The replacement is derived from `toolchain` discovery, which on a macOS test host+ legitimately finds `/usr` and Homebrew — that is `which clang` answering. What matters+ is that the *upstream default* list was replaced rather than appended to, so assert on+ the object identity of the assignment: patch() assigns a fresh list.+ """+ upstream_default = ['/opt/homebrew/bin', '/usr/local/bin', '/usr/local/share/dotnet',+ os.path.expanduser('~/.dotnet')]+ self.assertNotEqual(self.mod.TOOL_PATHS, upstream_default,+ 'patch() left the upstream macOS TOOL_PATHS in place')+ # and the GUI-launch reason the list exists still holds: it is a plain list of str+ self.assertTrue(all(isinstance(p, str) for p in self.mod.TOOL_PATHS))++ def test_bash_build_ipa_is_redirected(self) -> None:+ calls = []++ def fake_run(cmd, log, env=None, cwd=None, on_line=None):+ calls.append(list(cmd))+ return 0+ # `run_ipa` calls the module-level original; swap that for the test and re-patch so+ # the closure is rebuilt against it (patch() only captures when nothing is captured yet)+ orig = self.driver._UPSTREAM_RUN+ try:+ self.driver._UPSTREAM_RUN = fake_run+ self.driver.patch(self.mod, self.repo)+ self.mod.run(['bash', str(self.repo / 'dm/ios/tools/build_ipa.sh'), 'out.ipa'],+ Path('log'))+ finally:+ self.driver._UPSTREAM_RUN = orig+ self.driver.patch(self.mod, self.repo)+ self.assertEqual(len(calls), 1)+ self.assertEqual(Path(calls[0][0]).name, Path(sys.executable).name)+ self.assertTrue(calls[0][1].endswith('build_app.py'))+ self.assertEqual(calls[0][-1], 'out.ipa')++ def test_prepare_xcode_through_run_is_still_refused(self) -> None:+ with self.assertRaises(self.mod.BuildError):+ self.mod.run(['bash', str(self.repo / 'dm/ios/tools/build_ipa.sh'), '--prepare-xcode'],+ Path('log'))+++class SdkFetchTest(unittest.TestCase):+ def test_extract_rejects_a_non_xip(self) -> None:+ from nspb_qt.win import sdk_fetch+ with tempfile.TemporaryDirectory() as td:+ bad = Path(td) / 'x.xip'+ bad.write_bytes(b'<html>404</html>')+ with self.assertRaises(sdk_fetch.SdkError) as ctx:+ sdk_fetch.extract_xip(bad, Path(td) / 'out')+ self.assertIn('xar', str(ctx.exception))++ def test_extract_rejects_a_missing_file(self) -> None:+ from nspb_qt.win import sdk_fetch+ with self.assertRaises(sdk_fetch.SdkError):+ sdk_fetch.extract_xip(Path('/nonexistent/Xcode.xip'))++ def test_import_local_rejects_a_plain_folder(self) -> None:+ from nspb_qt.win import sdk_fetch+ with tempfile.TemporaryDirectory() as td:+ plain = Path(td) / 'notasdk'+ plain.mkdir()+ with self.assertRaises(sdk_fetch.SdkError):+ sdk_fetch.import_local(plain, Path(td) / 'cache')++ def test_import_local_accepts_a_nested_sdk(self) -> None:+ from nspb_qt.win import sdk_fetch+ with tempfile.TemporaryDirectory() as td:+ sdk = make_fake_sdk(Path(td) / 'download')+ got = sdk_fetch.import_local(sdk.parent, Path(td) / 'cache', log=lambda s: None)+ self.assertTrue(tc.is_sdk_dir(got))+ self.assertEqual(got.name, 'iPhoneOS26.0.sdk')++ def test_available_versions_is_a_best_effort_list(self) -> None:+ from nspb_qt.win import sdk_fetch+ # no network in CI: must not raise+ got = sdk_fetch.available_versions()+ self.assertIsInstance(got, list)+++class FetchTest(unittest.TestCase):+ def test_sha256_of_a_file(self) -> None:+ from nspb_qt.win import fetch+ with tempfile.TemporaryDirectory() as td:+ p = Path(td) / 'x'+ p.write_bytes(b'abc')+ self.assertEqual(fetch.sha256_of(p),+ 'ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad')++ def test_pinned_hashes_are_well_formed(self) -> None:+ for arch, asset in tc.LLVM_MINGW_ASSETS.items():+ self.assertEqual(len(asset['sha256']), 64, arch)+ self.assertTrue(all(c in '0123456789abcdef' for c in asset['sha256']), arch)+ self.assertIn(arch, ('AMD64', 'ARM64'))+ self.assertGreater(asset['size'], 100_000_000)++ def test_download_asset_url(self) -> None:+ a = tc.download_asset('AMD64')+ self.assertIn(tc.LLVM_MINGW_VERSION, a['url'])+ self.assertTrue(a['url'].endswith(a['name']))+++class ConstantParityTest(unittest.TestCase):+ """`toolchain.py` duplicates the package constants so it can be loaded standalone from the+ generated sitecustomize.py. The copies must not drift."""++ def test_duplicated_constants_match_the_package(self) -> None:+ import nspb_qt.win as pkg+ pairs = {+ 'IOS_DEPLOYMENT': (pkg.IOS_DEPLOYMENT, tc.IOS_DEPLOYMENT),+ 'ENV_TOOLCHAIN': (pkg.ENV_TOOLCHAIN, tc.ENV_TOOLCHAIN),+ 'ENV_LLVM': (pkg.ENV_LLVM, tc.ENV_LLVM),+ 'ENV_SDK': (pkg.ENV_SDK, tc.ENV_SDK),+ 'ENV_METAL': (pkg.ENV_METAL, tc.ENV_METAL),+ }+ for name, (a, b) in pairs.items():+ self.assertEqual(a, b, f'{name} differs between nspb_qt.win and nspb_qt.win.toolchain')++ def test_toolchain_imports_standalone(self) -> None:+ """shim.py loads it from a generated sitecustomize with no package context."""+ import subprocess+ code = ('import sys; sys.path.insert(0, %r); import toolchain; '+ 'print(toolchain.IOS_DEPLOYMENT)') % str(QT / 'nspb_qt' / 'win')+ r = subprocess.run([sys.executable, '-c', code], capture_output=True, text=True)+ self.assertEqual(r.returncode, 0, r.stderr[-600:])+ self.assertEqual(r.stdout.strip(), '26.0')+++class PlatformIsolationTest(unittest.TestCase):+ """Nothing Windows-specific may load on macOS through the normal import path."""++ def test_model_does_not_import_win_at_module_level(self) -> None:+ src = (QT / 'nspb_qt/model.py').read_text(encoding='utf-8')+ head = src.split('def _windows_deps')[0]+ self.assertNotIn('from .win import', head)+ self.assertNotIn('import nspb_qt.win', head)++ def test_platform_util_has_no_win_import(self) -> None:+ src = (QT / 'nspb_qt/platform_util.py').read_text(encoding='utf-8')+ self.assertNotIn('nspb_qt.win', src)+ self.assertNotIn('from .win', src)++ def test_importing_the_package_does_not_touch_win(self) -> None:+ import subprocess+ code = (+ 'import sys; sys.path.insert(0, %r)\n'+ 'import nspb_qt.model\n'+ 'bad = [m for m in sys.modules if m.startswith("nspb_qt.win")]\n'+ 'print("|".join(bad))\n'+ ) % str(QT)+ r = subprocess.run([sys.executable, '-c', code], capture_output=True, text=True,+ env={**os.environ, 'NSPB_REPO': ''})+ # PySide6 may be missing in a bare interpreter; that is not this test's subject+ if r.returncode != 0 and 'PySide6' in (r.stderr or ''):+ self.skipTest('PySide6 is not installed')+ self.assertEqual(r.returncode, 0, r.stderr[-800:])+ self.assertEqual(r.stdout.strip(), '', 'importing the model loaded nspb_qt.win')++ def test_win_modules_import_without_a_toolchain(self) -> None:+ with tempfile.TemporaryDirectory() as td:+ env = {**os.environ, 'LOCALAPPDATA': td, 'ProgramFiles': td,+ 'NSPB_TOOLCHAIN_JSON': str(Path(td) / 'nope.json')}+ for k in ('NSPB_LLVM_DIR', 'NSPB_IOS_SDK', 'NSPB_METAL_DIR'):+ env.pop(k, None)+ code = (+ 'import sys; sys.path.insert(0, %r)\n'+ 'from nspb_qt.win import toolchain, sdk_fetch, shim, fix_ipa_modes, fetch, '+ 'doctor, build_app, driver, xcrun_shim\n'+ 'print("ok")\n'+ ) % str(QT)+ r = subprocess.run([sys.executable, '-c', code], capture_output=True, text=True,+ env=env)+ self.assertEqual(r.returncode, 0, r.stderr[-1200:])+ self.assertEqual(r.stdout.strip(), 'ok')+++class LocalizationTest(unittest.TestCase):+ def test_every_windows_dep_key_exists_in_both_languages(self) -> None:+ from nspb_qt.i18n import Lang+ from nspb_qt.localization import TABLE, t+ keys = ['dep.llvm', 'dep.llvm.hint', 'dep.lld', 'dep.lld.hint',+ 'dep.probe.compile', 'dep.probe.compile.hint',+ 'dep.probe.link', 'dep.probe.link.hint',+ 'dep.probe.metal', 'dep.probe.metal.hint',+ 'dep.glslang', 'dep.glslang.hint', 'dep.optionalMissing',+ 'dep.iossdk', 'dep.iossdk.hint', 'dep.metal', 'dep.metal.hint']+ for k in keys:+ self.assertIn(k, TABLE, f'{k} missing from the table')+ zh = t(k, Lang.ZH)+ en = t(k, Lang.EN)+ self.assertTrue(zh and zh != k, f'{k} has no Chinese text')+ self.assertTrue(en and en != k, f'{k} has no English text')+++if __name__ == '__main__':+ unittest.main(verbosity=2)