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 app: the five things the handheld report found
LNPANDY18380a64f781
diff --git a/README.md b/README.mdindex 4f880592..a315d049 100644--- a/README.md+++ b/README.md@@ -204,6 +204,7 @@ Newest first. The fork follows upstream daily, so its game list and host fixes a| Date | Version | What changed ||---|---|---|+| 2026-10-26 | v0.4.6 | **Windows app fixed against real hardware reports**: the missing .NET SDK row (it never appeared, so nothing could install it), no more black console windows stealing the foreground, download mirrors chosen by a speed probe (a 974 s LLVM download on a mainland connection), tools installed outside the app folder so updates stop deleting them, and repository checks that say what git is doing || 2026-10-26 | v0.4.5 | **Mac app output** (a double-clickable .app from the same build); **A15/A16 and earlier devices** via CPU BC decode, as an app switch; per-game data folders (`Documents/games/<id>/`) so an external drive works; NRO header no longer scanned as code; the nightly sync can no longer fail silently || 2026-10-26 | v0.4.4 | **Fixes a build failure that hit every app build in v0.4.3** (`work` read before it was assigned); 72 games (+3) || 2026-10-26 | v0.4.3 | NSZ/XCZ dumps work out of the box; a fresh Xcode now reports its missing iOS SDK; three environment traps closed |diff --git a/README.zh-CN.md b/README.zh-CN.mdindex d74b1159..acc6e63b 100644--- a/README.zh-CN.md+++ b/README.zh-CN.md@@ -206,6 +206,7 @@ cd frontend && swift run # 或直接双击 frontend/NS Port Builder.app| 日期 | 版本 | 变更 ||---|---|---|+| 2026-10-26 | v0.4.6 | **Windows 版按真机反馈修好**:.NET SDK 那一行以前根本不存在(所以永远装不上)、不再弹出黑色命令行窗口抢走焦点、下载走镜像并用测速挑最快的一个(真机上 LLVM 曾下 974 秒)、工具装到 App 目录外所以更新不再把它删掉、检查更新会说明 git 在做什么 || 2026-10-26 | v0.4.5 | **可输出 Mac App**(同一次构建产出可双击运行的 .app);**支持 A15 / A16 及更早设备**(CPU 解压 BC 纹理,App 内开关);每游戏独立数据目录(`Documents/games/<id>/`),外置硬盘可用;NRO 头不再被当作代码扫描;每日同步不会再静默失败 || 2026-10-26 | v0.4.4 | **修复了 v0.4.3 里每个 App 构建都会失败的问题**(`work` 在赋值前被读取);72 款游戏(+3) || 2026-10-26 | v0.4.3 | NSZ/XCZ 压缩格式开箱可用;全新 Xcode 会明说缺 iOS SDK;三个环境陷阱关掉 |diff --git a/frontend-qt/README.md b/frontend-qt/README.mdindex abc6b658..fb07cd57 100644--- a/frontend-qt/README.md+++ b/frontend-qt/README.md@@ -45,11 +45,13 @@ wherever `NSPB_REPO` points, and the repository group lets you pick it by hand.## What is not there 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).+- **The Windows build path has run on a real Windows machine** — a handheld PC, which is where the+ bug reports came from — through repository download, git auto-install and the LLVM / SDK / .NET+ downloads. The compile, link, `Metal` compile and the final IPA on Windows have still not been+ exercised end to end against a genuine LLVM-MinGW + iPhoneOS SDK + Metal Developer Tools+ install. See [Windows build → Open risks](#open-risks).+- No self-update. Repository download and update buttons do exist (`Download repository`,+ `Check for updates`, `Pull updates`), and they log what git is doing.- No per-stage progress bar, no cancel-with-cleanup (cancel terminates the child).## Layout@@ -98,7 +100,15 @@ The upstream file is never edited, so the daily sync cannot conflict with this w## What you need to install-Run this first; it lists what is missing and where to get it:+The app installs everything it can itself: the Dependencies panel has an **Install** button per+row and **Install all missing**, and the rows it can fetch are .NET SDK, LLVM-MinGW and the+iPhoneOS SDK. What it cannot fetch is Apple's Metal Developer Tools (an Apple ID login) and the+optional Vulkan/GL tools.++Everything it downloads goes to `%LOCALAPPDATA%\NS Port Builder\tools`, outside the app folder, so+updating the app (re-extracting its zip) does not throw the 182 MB LLVM archive away.++Run this first if you prefer the command line; it lists what is missing and where to get it:```batpython -m nspb_qt.win.doctor@@ -106,7 +116,10 @@ python -m nspb_qt.win.doctor1. **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).+2. **.NET SDK 10** — the app downloads it (the zip, not the installer: no administrator rights,+ about 287 MB), or get it from <https://dotnet.microsoft.com/download/dotnet/10.0> (SDK, x64).+ `nx_extract` targets `net10.0`, so SDK 8 or 9 alone is not enough; the dependency row says so+ rather than failing halfway through a build.3. **LLVM-MinGW 20261020** — the app's Dependencies panel downloads and verifies it, or:```bat@@ -118,7 +131,9 @@ python -m nspb_qt.win.doctor| archive | SHA-256 ||---|---|| `llvm-mingw-20261020-ucrt-x86_64.zip` | `fd5462b7f5d93b2ff981fcd3f9c7e427e47f3203c64ea91c27bcc444eebd74cd` |- | `llvm-mingw-20261020-ucrt-aarch64.zip` | `8f24fedd0b75c674c6c83dec2d76a7ac31a690120212843a17e465ef49854f69` |++ Only the x86-64 archive is published by this app; a Windows-on-ARM machine runs it under+ emulation (the dependency panel says so in a `host architecture` row).The official `LLVM-*-win64.msi` from llvm.org works too (same clang, same LLD).@@ -147,12 +162,39 @@ If auto-detection picks the wrong folder, set it in{"llvm_dir": "D:\\tools\\llvm-mingw-20261020-ucrt-x86_64","ios_sdk": "D:\\SDKs\\iPhoneOS26.0.sdk",+ "dotnet_dir": "C:\\Program Files\\dotnet","metal_dir": "C:\\Program Files\\Metal Developer Tools","spirv_cross_dir": "C:\\VulkanSDK\\1.4.321.0\\Bin","zstd_dir": "C:\\tools\\zstd"}```+Each key also has an environment variable (`NSPB_LLVM_DIR`, `NSPB_IOS_SDK`, `NSPB_DOTNET_DIR`,+`NSPB_METAL_DIR`, …), which wins over the file.++## Downloads, mirrors, and no console windows++Three things about how the app fetches its tools are worth knowing, because each of them was a+bug report from a handheld PC on a mainland connection:++**Mirrors.** GitHub release assets are the slow ones. Every download tries the direct URL plus+two mirrors (`ghfast.top`, `gh-proxy.com`), and picks between them by timing a 256 KB ranged+request — the report that prompted this was a 974-second download that *succeeded*, so failing+over on errors alone would never have helped. The pinned SHA-256 is the only thing that decides+what gets unpacked: a mirror serving different bytes is rejected exactly like a corrupted+download. Microsoft's CDN (the .NET SDK) is not mirrored; it is fast enough on its own.++**Where tools land.** `%LOCALAPPDATA%\NS Port Builder\tools`. Not inside the app folder: the app+ships as a zip that gets re-extracted for every update, which would take 182 MB of LLVM with it.+Older builds used `<app>\_internal\.tools` and that path is still read, so an existing install+keeps working.++**No console windows.** The app is a windowed process, so every child it started — git, clang,+lld, the PortableGit self-extractor, and the repository's own Python scripts — used to get its+own black console window. On a handheld that read as "a command line appears, shows nothing, and+the install stops". `platform_util.hide_console_for_children()` patches `subprocess.Popen` once at+start-up, so children of children inherit an invisible console too.+## Verify each step`nspb_qt.win.toolchain` does not trust that a path exists — it runs the tool:diff --git a/frontend-qt/nspb_qt/__main__.py b/frontend-qt/nspb_qt/__main__.pyindex 8cecf008..d58bc669 100644--- a/frontend-qt/nspb_qt/__main__.py+++ b/frontend-qt/nspb_qt/__main__.py@@ -8,11 +8,15 @@ from PySide6.QtGui import QGuiApplicationfrom PySide6.QtWidgets import QApplicationfrom .model import Model+from .platform_util import hide_console_for_childrenfrom .style import STYLEfrom .ui import MainWindowdef main() -> int:+ # Before anything can spawn a child: on Windows every subprocess would otherwise open its own+ # console window (see the docstring — this is the "black window, nothing happens" report).+ hide_console_for_children()# High-DPI: let Qt scale with the screen. On a handheld (a small 720p/800p panel at# 125-150%) the default policy rounds the scale factor up and the window no longer fits;# PassThrough honours the system factor as-is and the font sizes below stay in points.diff --git a/frontend-qt/nspb_qt/localization.py b/frontend-qt/nspb_qt/localization.pyindex 707975af..7d49640b 100644--- a/frontend-qt/nspb_qt/localization.py+++ b/frontend-qt/nspb_qt/localization.py@@ -67,6 +67,15 @@ TABLE: dict[str, tuple[str, str]] = {'data.noNsp': ('这个文件夹里没有 NSP/XCI', 'No NSP/XCI in this folder'),'build.start': ('开始构建', 'Start build'),'build.cancel': ('取消构建', 'Cancel build'),+ 'msg.macAppDone': ('Mac App 已生成,可在访达里双击运行', 'Mac app ready — double-click it in the Finder'),+ 'msg.macAppMissing': ('构建结束但没有找到 .app(仓库里缺 dm/mac/pack_app.py?)', 'Build finished but no .app was produced (is dm/mac/pack_app.py in the checkout?)'),+ 'opt.title': ('构建选项', 'Build options'),+ 'opt.note': ('按输出类型', 'per output'),+ 'opt.bc': ('兼容老设备(A15 / A16 及更早)', 'Older devices (A15 / A16 and earlier)'),+ 'opt.bc.note': ('在不支持 BC 纹理压缩的 GPU 上于 CPU 解压:iPhone 13 及更早、A16 的 iPad。新设备请保持关闭——GPU 路径更快', 'Decode BC textures on the CPU for GPUs without BC support: iPhone 13 and earlier, A16 iPads. Leave off on newer devices — the GPU path is faster'),+ 'opt.macNoBc': ('Mac App 用这台 Mac 的 GPU,不需要兼容选项', "A Mac app uses this Mac's GPU; no compatibility option needed"),+ 'msg.bcOn': ('兼容老设备:BC 纹理将在 CPU 上解压', 'Older-device mode: BC textures will be decoded on the CPU'),+ 'msg.bcEnvFailed': ('无法写入环境文件:%@——继续构建,但兼容模式未启用', 'Could not write the environment file: %@ — building without the compatibility mode'),'target.ios': ('输出:iPhone IPA', 'Output: iPhone IPA'),'target.mac': ('输出:Mac App', 'Output: Mac app'),'target.tip': ('点一下切换(Mac App 可直接双击运行,不需要 iPhone)', 'Click to switch (a Mac app runs on this Mac, no iPhone needed)'),@@ -126,6 +135,8 @@ TABLE: dict[str, tuple[str, str]] = {'dep.dotnet': ('.NET SDK 10', '.NET SDK 10'),'dep.dotnet.hint': ('dotnet-install.sh 装到 ~/.dotnet', 'dotnet-install.sh into ~/.dotnet'),'dep.dotnet.missing': ('没找到带 SDK 10 的 dotnet', 'no dotnet with SDK 10 found'),+ 'dep.dotnet.downloading': ('正在下载 .NET SDK 10…(约 287 MB,解压后约 900 MB)', 'Downloading .NET SDK 10… (about 287 MB, about 900 MB unpacked)'),+ 'dep.dotnet.done': ('.NET SDK 已安装:%@', '.NET SDK installed: %@'),'dep.python': ('Python + 包', 'Python + packages'),'dep.python.hint': ('lz4 capstone fonttools backports.zstd', 'lz4 capstone fonttools backports.zstd'),'dep.python.missing': ('%@ 缺包', '%@ is missing packages'),diff --git a/frontend-qt/nspb_qt/model.py b/frontend-qt/nspb_qt/model.pyindex 0300422f..decb47e7 100644--- a/frontend-qt/nspb_qt/model.py+++ b/frontend-qt/nspb_qt/model.py@@ -172,6 +172,23 @@ class Model(QObject):threading.Thread(target=self._check_deps_worker, daemon=True).start()def _check_deps_worker(self) -> None:+ """Build the dependency rows off the UI thread.++ Any exception has to leave the panel in a finished state: an unhandled one killed this+ thread while `deps_checked` stayed False, so the panel sat on "Checking…" forever and the+ handheld report read "Check again does nothing". A failed check now says so.+ """+ try:+ self._check_deps()+ except Exception as e: # noqa: BLE001 - a check must never be fatal+ import traceback+ self.log(f'dependency check failed: {type(e).__name__}: {e}\n')+ self.log(traceback.format_exc() + '\n')+ self.deps = []+ self.deps_checked = True+ self.depsChanged.emit()++ def _check_deps(self) -> None:deps: list[Dep] = []# Python + packages@@ -187,11 +204,17 @@ class Model(QObject):deps.append(Dep('python', 'dep.python', 'dep.python.hint', DepState.OLD,f'dep.python.old:{py_ver or "?"}:3.9'))- # .NET- dn, dn_ok = pu.find_dotnet()- deps.append(Dep('dotnet', 'dep.dotnet', 'dep.dotnet.hint',- DepState.OK if dn_ok else DepState.MISSING,- dn if dn_ok else 'dep.dotnet.missing'))+ # .NET. On Windows the row comes from `_windows_deps()` instead: there the check has to be+ # "SDK 10 or newer is installed" (nx_extract targets net10.0) and the fix is an in-app+ # download, neither of which `find_dotnet` knows about. This generic row is what the+ # Windows panel used to be missing entirely — the handheld report's first line,+ # ".NET SDK 10 never appears in the log", came from exactly that gap.+ dn = dn_ok = None+ if not pu.IS_WIN:+ dn, dn_ok = pu.find_dotnet()+ deps.append(Dep('dotnet', 'dep.dotnet', 'dep.dotnet.hint',+ DepState.OK if dn_ok else DepState.MISSING,+ dn if dn_ok else 'dep.dotnet.missing'))# Xcode (macOS) or the cross toolchain (Windows)if pu.IS_WIN:@@ -219,7 +242,10 @@ class Model(QObject):self.deps = depsself.python_path, self.python_ok, self.python_ver = py, py_ok, py_ver- self.dotnet_path, self.dotnet_ok = dn, dn_ok+ if not pu.IS_WIN:+ # On Windows `_windows_deps` already set these from the toolchain probe, which is+ # where the app-installed SDK is visible; this branch is the macOS one.+ self.dotnet_path, self.dotnet_ok = dn, dn_okself.deps_checked = Trueself.depsChanged.emit()@@ -249,6 +275,20 @@ class Model(QObject):def state(p) -> DepState:return DepState.OK if p.ok else (DepState.OLD if p.state == 'wrong' else DepState.MISSING)+ # .NET first: it is what the extractor and the shader translator run on, and it is the+ # row the Windows panel did not have at all before (a macOS-only branch produced it).+ p = by_id.get('dotnet')+ if p:+ detail = p.detail if not p.ok else (p.version or p.path or 'ok')+ out.append(Dep('dotnet', 'dep.dotnet', 'dep.dotnet.hint', state(p), detail,+ install=[] if p.ok else ['__win__:dotnet']))+ # the build passes DOTNET_ROOT to its children; this is the only place that knows+ # about the copy the app installed for itself+ if p.path:+ self.dotnet_path, self.dotnet_ok = str(Path(p.path) / 'dotnet.exe'), p.ok+ else:+ self.dotnet_path, self.dotnet_ok = 'dotnet', False+# LLVM (+ the Mach-O linker, which comes from the same folder)p = by_id.get('llvm')if p:@@ -405,7 +445,9 @@ class Model(QObject):if not git or not self.repo_ok or not self.repo_is_git:returnself.repo_busy = True+ self.repo_status = self.t('repo.pulling')self.repoChanged.emit()+ self.log(self.t('repo.pulling') + '\n')def work() -> None:out = ''@@ -425,18 +467,46 @@ class Model(QObject):threading.Thread(target=work, daemon=True).start()def check_repo_updates(self) -> None:- """How far behind origin/main the checkout is (0 = current)."""+ """How far behind origin/main the checkout is (0 = current).++ `git fetch` over a slow link takes tens of seconds, and the button used to go grey with+ nothing in the log until it finished — reported as "I click Check for updates, it greys+ out, and nothing happens". So: say what is starting, stream git's own progress lines, and+ end with a line either way. git writes progress to stderr with `--progress`, which is why+ the fetch below asks for it explicitly (it is off by default when stderr is a pipe).+ """git = self.git_binary()if not git or not self.repo_ok or not self.repo_is_git:returnself.repo_busy = True+ self.repo_status = self.t('repo.checking')self.repoChanged.emit()+ self.log(self.t('repo.checking') + '\n')+ self.log(f'$ git -C {self.repo_path} fetch --progress origin main\n')def work() -> None:+ ok = False+ try:+ p = subprocess.Popen([git, '-C', self.repo_path, 'fetch', '--progress',+ 'origin', 'main'],+ stdout=subprocess.PIPE, stderr=subprocess.STDOUT,+ text=True, errors='replace', env=pu.child_env(),+ **pu.no_window_kwargs())+ assert p.stdout is not None+ for line in p.stdout:+ # git rewrites a progress line with \r; the log is line-based+ if s := line.replace('\r', '\n').strip():+ self.log(s + '\n')+ p.wait()+ ok = p.returncode == 0+ except OSError as e:+ self.log(f'{e}\n')+ if not ok:+ self.repo_status = self.t('repo.netFail')+ self.repo_busy = False+ self.repoChanged.emit()+ returntry:- subprocess.run([git, '-C', self.repo_path, 'fetch', 'origin', 'main'],- capture_output=True, text=True, env=pu.child_env(),- **pu.no_window_kwargs())r = subprocess.run([git, '-C', self.repo_path, 'rev-list', '--count','HEAD..origin/main'],capture_output=True, text=True, env=pu.child_env(),@@ -445,8 +515,11 @@ class Model(QObject):self.repo_behind = int(r.stdout.strip() or 0)self.repo_status = (self.t('repo.upToDate') if self.repo_behind == 0else self.t('repo.behind', self.repo_behind))+ else:+ self.repo_status = self.t('repo.netFail')except (OSError, ValueError):- pass+ self.repo_status = self.t('repo.netFail')+ self.log(self.repo_status + '\n')self.repo_busy = Falseself.repoChanged.emit()@@ -514,7 +587,16 @@ class Model(QObject):try:from .win import fetch as wf, toolchain as wtcself.log(self.t('dep.install.begin', dep.id) + '\n')- if what == 'llvm':+ if what == 'dotnet':+ self.log(self.t('dep.dotnet.downloading') + '\n')+ path = wf.install_dotnet(+ log=lambda s: self.log(str(s) + '\n'),+ progress=lambda d, t_: self.log(+ f' {d // 1048576} MB' ++ (f' / {t_ // 1048576} MB ({d * 100 // t_}%)' if t_ else '') + '\n'))+ self.log(self.t('dep.dotnet.done', str(path)) + '\n')+ ok = True+ elif what == 'llvm':self.log(self.t('dep.llvm.downloading') + '\n')path = wf.install_llvm(log=lambda s: self.log(str(s) + '\n'),@@ -578,6 +660,11 @@ class Model(QObject):started them all at once and their downloads interleaved in the log (reported from ahandheld: LLVM and SDK lines mixed). Order also matters for correctness — the SDK isfetched with git, which the git row may be installing.++ The list is snapshotted once, and the wait is on that same `Dep` object: `_install_win`+ ends with `check_deps()`, which replaces `self.deps` with fresh objects, so re-reading+ `self.deps` mid-run would wait on a `Dep` nobody is installing and every later row would+ look finished instantly."""pending = [d for d in self.deps if not d.ok and d.install]if not pending or getattr(self, '_install_all_running', False):diff --git a/frontend-qt/nspb_qt/platform_util.py b/frontend-qt/nspb_qt/platform_util.pyindex 9205d2a9..077d3c40 100644--- a/frontend-qt/nspb_qt/platform_util.py+++ b/frontend-qt/nspb_qt/platform_util.py@@ -225,3 +225,32 @@ def no_window_kwargs() -> dict:if IS_WIN:return {'creationflags': subprocess.CREATE_NO_WINDOW}return {}+++def hide_console_for_children() -> None:+ """Stop *every* child this process starts from opening a console window (Windows only).++ Called once at start-up. Per-call `creationflags` cannot be added everywhere: the build runs+ the repository's own Python scripts as children, and those scripts start clang, git, lld and+ zip themselves — dozens of call sites in files this front end does not own. A windowed app has+ no console, so each of those children got a fresh black window, and on a handheld the report+ was "a command-line window appears, shows nothing, and the install stops moving" — the window+ was git's, and it was stealing the foreground while the download ran behind it.++ A child created with CREATE_NO_WINDOW still gets a console, just no window, and its own+ children inherit that invisible console — which is why patching at the boundary is enough to+ cover the whole tree.++ A caller that passes its own `creationflags` keeps them: DETACHED_PROCESS and+ CREATE_NEW_CONSOLE mean something, and silently overriding them would break that intent.+ """+ if not IS_WIN:+ return+ original = subprocess.Popen.__init__++ def patched(self, args, *a, **k): # noqa: ANN001 - mirrors Popen.__init__+ if not k.get('creationflags') and not k.get('startupinfo'):+ k['creationflags'] = subprocess.CREATE_NO_WINDOW+ original(self, args, *a, **k)++ subprocess.Popen.__init__ = patched # type: ignore[method-assign]diff --git a/frontend-qt/nspb_qt/win/driver.py b/frontend-qt/nspb_qt/win/driver.pyindex 8a58c4c5..347f02b6 100644--- a/frontend-qt/nspb_qt/win/driver.py+++ b/frontend-qt/nspb_qt/win/driver.py@@ -161,8 +161,12 @@ def patch(mod: ModuleType, repo: Path, *, j: int | None = None) -> None:"""The .NET build, but on Windows the output is `nx_extract.exe`."""import tempfilenx = work / 'tools/nx_extract/nx_extract'+ # An absolute path: `dotnet` by name relies on PATH, and a toolchain this app downloaded+ # lives in its own folder (the shim's PATH has it, but not every caller goes through it).+ dn = tc.dotnet_dir()+ dotnet = str(dn / 'dotnet.exe') if dn else 'dotnet'with tempfile.TemporaryDirectory(prefix='nx_extract_') as td:- mod.run(['dotnet', 'build', repo_ / 'dm/tools/nx_extract', '-c', 'Release',+ 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'@@ -270,9 +274,12 @@ def patch(mod: ModuleType, repo: Path, *, j: int | None = None) -> None: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'))+ # The .NET root, wherever it actually is: `Program Files` is only one of the places+ # `dotnet_dir()` accepts, and the copy the app installs for itself is the one that matters on+ # a machine with no system SDK. Without this, `dotnet build` (called by name in+ # build_nx_extract) would not find it.+ if dn := tc.dotnet_dir():+ extra.append(str(dn))mod.TOOL_PATHS = extra# ---------------------------------------------------------------- the app builddiff --git a/frontend-qt/nspb_qt/win/fetch.py b/frontend-qt/nspb_qt/win/fetch.pyindex 0698b40f..2b9ef3f5 100644--- a/frontend-qt/nspb_qt/win/fetch.py+++ b/frontend-qt/nspb_qt/win/fetch.py@@ -35,75 +35,140 @@ class DownloadError(Exception):"""A user-facing download failure with an actionable message."""+def rank_by_speed(urls: list[str], log: Callable[[str], None],+ probe_bytes: int = 256 << 10, timeout: float = 8.0) -> list[str]:+ """Order `urls` fastest-first by timing a small ranged request against each.++ This exists because the failure that prompted it was not an error: the 182 MiB LLVM archive+ downloaded from GitHub in 974 s (about 190 KB/s) and *succeeded*, so a fallback-on-failure+ design never fired. Nothing was broken, it was just an hour of waiting — and on a handheld+ that reads as a hang.++ The clock starts at the first byte, not at the request: a TLS handshake to a proxy takes a+ couple of seconds on its own, and timing it would make every source look equally slow (the+ first version of this did exactly that and picked at random).++ A source that errors or times out on the probe is kept at the end rather than dropped: the+ probe is a smaller request than the real one and can fail on its own (a server that rejects+ Range, a hiccup), so it still gets its turn if everything faster fails. The bytes are+ discarded — only the speed is used.+ """+ if len(urls) < 2:+ return urls+ results: list[tuple[float, str]] = []+ for u in urls:+ try:+ req = urllib.request.Request(u, headers={'User-Agent': 'NS-Port-Builder',+ 'Range': f'bytes=0-{probe_bytes - 1}'})+ with urllib.request.urlopen(req, timeout=timeout) as r:+ first = r.read(min(64 << 10, probe_bytes))+ t_first = time.time()+ rest = r.read(probe_bytes - len(first)) if len(first) < probe_bytes else b''+ t_end = time.time()+ got = len(first) + len(rest)+ if not got:+ raise OSError('empty response')+ # Rate over the transfer only; when the whole probe arrived in the first read there+ # is no transfer window, so that read's own duration is the measurement.+ dt = (t_end - t_first) if rest else max(t_end - t_first, 1e-3)+ results.append((dt, u))+ log(f' {u.split("//")[1].split("/")[0]}: '+ f'{got / 1024 / max(dt, 1e-3):.0f} KB/s')+ except Exception as e: # noqa: BLE001 - a probe never fails a run+ results.append((float('inf'), u))+ log(f' {u.split("//")[1].split("/")[0]}: {type(e).__name__} '+ f'(kept as a last resort)')+ results.sort(key=lambda r: r[0])+ return [u for _, u in results]++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.+ progress: Callable[[int, int], None] | None = None,+ algo: str = 'sha256') -> Path:+ """Fetch `url` into `dest`, verifying its digest.Downloads to a `.part` file and renames on success, so an interrupted download never lookslike a usable archive on the next start.++ `algo` exists because Microsoft publishes SHA-512 for the .NET archives (their+ `releases.json` hashes are 128 hex characters, not 64) and we use their number rather than a+ self-computed one: a hash this project computed itself would only prove the file is what we+ already downloaded, not that it is what Microsoft published."""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)+ got = digest_of(dest, algo)if got == sha256.lower():log(f'cached: {dest.name} ({got[:16]}…)')return destlog(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:+ errors: list[str] = []+ urls = rank_by_speed(tc.mirror_urls(url), log)+ for attempt, u in enumerate(urls):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.')- # The length is a progress hint, not a check: SHA-256 above is the authority. A pinned size- # that is off by a byte (an estimate, or an asset re-uploaded without its hash changing in the- # code) must not fail a download whose content is provably right.- if size and total != size:- log(f'note: {dest.name} is {total} bytes, the pinned size says {size} — content verified '- f'by SHA-256, continuing')- 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+ if attempt:+ log(f'trying another source: {u}')+ else:+ log(f'downloading {u}')+ h = hashlib.new(algo)+ total = 0+ t0 = time.time()+ try:+ req = urllib.request.Request(u, 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)+ errors.append(f'HTTP {e.code} from {u}')+ continue+ except (urllib.error.URLError, OSError) as e:+ part.unlink(missing_ok=True)+ errors.append(f'{u}: {e}')+ continue+ got = h.hexdigest()+ if got != sha256.lower():+ # A mirror that serves different bytes is rejected exactly like a corrupted direct+ # download: the hash is the only thing that says the toolchain is the one we tested.+ part.unlink(missing_ok=True)+ errors.append(f'{u}: {algo.upper()} {got[:16]}… does not match the pinned '+ f'{sha256[:16]}…')+ continue+ # The length is a progress hint, not a check: the digest above is the authority. A pinned+ # size that is off by a byte (an estimate, or an asset re-uploaded without its hash+ # changing in the code) must not fail a download whose content is provably right.+ if size and total != size:+ log(f'note: {dest.name} is {total} bytes, the pinned size says {size} — content '+ f'verified by {algo.upper()}, continuing')+ part.replace(dest)+ log(f'downloaded {dest.name} ({total / 2**20:.0f} MiB in {time.time() - t0:.0f} s, '+ f'{algo} {got[:16]}…)')+ return dest+ raise DownloadError(+ f'could not download {dest.name}:\n ' + '\n '.join(errors) ++ '\nNothing was kept. If this repeats, the release was replaced upstream: point '+ '"llvm_dir" (or "ios_sdk") in toolchain.json at an existing install instead.')-def sha256_of(path: Path, limit: int | None = None) -> str:- h = hashlib.sha256()+def digest_of(path: Path, algo: str = 'sha256', limit: int | None = None) -> str:+ """The hex digest of a file under `algo` (sha256 for our pins, sha512 for Microsoft's)."""+ h = hashlib.new(algo)left = limitwith open(path, 'rb') as f:while True:@@ -119,6 +184,10 @@ def sha256_of(path: Path, limit: int | None = None) -> str:return h.hexdigest()+def sha256_of(path: Path, limit: int | None = None) -> str:+ return digest_of(path, 'sha256', limit)++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)@@ -137,16 +206,16 @@ def install_llvm(arch: str | None = None, dest: Path | None = None,"""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}'+ root = Path(dest) if dest else tc.tools_dir()+ target = root / 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'+ cache = root / '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}'+ staging = root / f'.unpack-{tc.LLVM_MINGW_VERSION}'shutil.rmtree(staging, ignore_errors=True)staging.mkdir(parents=True)try:@@ -198,6 +267,64 @@ def install_llvm(arch: str | None = None, dest: Path | None = None,return target+def install_dotnet(dest: Path | None = None,+ log: Callable[[str], None] | None = None,+ progress: Callable[[int, int], None] | None = None) -> Path:+ """Download the .NET SDK zip and unpack it into the app's own tools folder.++ A zip, not the .exe installer: the installer wants to write Program Files and therefore wants+ administrator rights, and it puts the SDK where the app then has to find it. The zip is+ self-contained — unpack it and `dotnet.exe` is the root — so this needs no elevation and no+ registry, and `toolchain.dotnet_dir` looks in the folder it lands in.++ Verified by SHA-256 from Microsoft's release metadata (`releases.json`, the same hash the+ official installers use). The archive is about 287 MB; unpacked it is about 900 MB.+ """+ log = log or (lambda s: None)+ asset = tc.DOTNET_ASSET+ root = Path(dest) if dest else tc.tools_dir()+ target = root / f'dotnet-{tc.DOTNET_VERSION}'+ if (target / 'dotnet.exe').is_file():+ log(f'.NET SDK already installed: {target}')+ return target+ cache = root / 'downloads'+ zpath = download(asset['url'], cache / asset['name'], asset['sha256'], asset['size'],+ log=log, progress=progress, algo=asset.get('algo', 'sha256'))+ log(f'unpacking {zpath.name} → {target} (about 900 MB on disk)')+ staging = root / f'.unpack-dotnet-{tc.DOTNET_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})')+ # No top-level folder in this zip: members are host/, sdk/, shared/ directly. Every+ # path is taken as-is, which is what makes dotnet.exe land at the root.+ for info in z.infolist():+ if info.is_dir():+ continue+ out = staging / info.filename+ # a zip member may try to escape the target (../ in the name)+ if not str(out.resolve()).startswith(str(staging.resolve())):+ continue+ 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)+ except zipfile.BadZipFile as e:+ shutil.rmtree(staging, ignore_errors=True)+ raise DownloadError(f'{zpath.name} is not a valid zip: {e}') from e+ if not (staging / 'dotnet.exe').is_file():+ shutil.rmtree(staging, ignore_errors=True)+ raise DownloadError(f'{zpath.name} unpacked without dotnet.exe at its root: the release '+ 'layout changed; install the SDK from dotnet.microsoft.com instead')+ shutil.rmtree(target, ignore_errors=True)+ target.parent.mkdir(parents=True, exist_ok=True)+ staging.replace(target)+ log(f'.NET SDK {tc.DOTNET_VERSION} installed: {target}')+ return target++def metal_tools_hint() -> str:return (f'Apple "Metal Developer Tools for Windows" {tc.METAL_TOOLS_VERSION}: 'f'{tc.METAL_TOOLS_URL}')@@ -243,7 +370,7 @@ def install_git(arch: str | None = None, dest: Path | None = None,# The self-extractor writes the tree directly into -o<dir>; -y answers any prompt, -Install# skips the integration step (no registry, no PATH changes).r = subprocess.run([str(zpath), f'-o{target}', '-y', '-Install'],- capture_output=True, text=True, errors='replace')+ capture_output=True, text=True, errors='replace', **tc.no_window())if r.returncode != 0 or not exe.is_file():raise DownloadError(f'PortableGit unpacking failed (exit {r.returncode}). 'diff --git a/frontend-qt/nspb_qt/win/sdk_fetch.py b/frontend-qt/nspb_qt/win/sdk_fetch.pyindex 6922346c..f24996d5 100644--- a/frontend-qt/nspb_qt/win/sdk_fetch.py+++ b/frontend-qt/nspb_qt/win/sdk_fetch.py@@ -64,12 +64,12 @@ def clone_sdk(version: str = tc.SDK_PINNED, dest: Path | None = None,work = dest / f'.clone-{version}'shutil.rmtree(work, ignore_errors=True)- def run(args: list[str], what: str) -> None:+ def run(args: list[str], what: str, repo: str = tc.SDK_REPO) -> 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)+ bufsize=1, **tc.no_window())except OSError as e:raise SdkError(f'cannot start git: {e}') from eassert p.stdout is not None@@ -81,12 +81,28 @@ def clone_sdk(version: str = tc.SDK_PINNED, dest: Path | None = None,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')+ # The clone goes through the same mirror list as the file downloads: the repository is on+ # GitHub, and a mainland connection that took 974 s for a 182 MB release asset is not going to+ # enjoy a shallow clone either. The mirrors are git-protocol proxies, so the SHA of the+ # checkout is unchanged — and the SDK is verified by its own layout afterwards.+ clone_args = ['clone', '--filter=blob:none', '--sparse', '--depth', '1']+ last: Exception | None = None+ for i, repo in enumerate(tc.mirror_urls(tc.SDK_REPO)):+ if i:+ log(f'retrying through a mirror: {repo}')+ shutil.rmtree(work, ignore_errors=True)+ try:+ run(clone_args + [repo, str(work)], 'clone', repo)+ last = None+ break+ except SdkError as e:+ last = e+ if last is not None:+ raise last# narrow the working tree to the one SDK before checking anything outtry:subprocess.run([git, 'sparse-checkout', 'set', version], cwd=str(work),- check=True, capture_output=True, text=True)+ check=True, capture_output=True, text=True, **tc.no_window())except subprocess.CalledProcessError as e:raise SdkError(f'git sparse-checkout failed: {(e.stderr or "").strip()[-400:]}') from esrc = work / version@@ -107,7 +123,7 @@ def available_versions(log: Callable[[str], None] | None = None) -> list[str]:return []try:r = subprocess.run([git, 'ls-remote', '--heads', tc.SDK_REPO], capture_output=True,- text=True, timeout=120)+ text=True, timeout=120, **tc.no_window())except (OSError, subprocess.SubprocessError):return []return [] if r.returncode else list(tc.SDK_ACCEPTED)diff --git a/frontend-qt/nspb_qt/win/shim.py b/frontend-qt/nspb_qt/win/shim.pyindex 48cd686e..30f268f5 100644--- a/frontend-qt/nspb_qt/win/shim.py+++ b/frontend-qt/nspb_qt/win/shim.py@@ -183,7 +183,10 @@ if os.name == 'nt' and not os.environ.get('NSPB_SHIM_OFF'):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:]+ # an absolute path, not `which`: a .NET SDK the app installed is not on PATH+ dn = tc.dotnet_dir()+ dotnet = str(dn / 'dotnet.exe') if dn else (shutil.which('dotnet') or 'dotnet')+ return [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 \@@ -319,7 +322,12 @@ def build_env(base: dict[str, str] | None = None, python_exe: str | None = None)p = tc.find_exe(name)if p:parts.append(str(p.parent))- if dn := shutil.which('dotnet'):+ # tc.dotnet_dir() first: it knows about the SDK the app installed for itself, which is not on+ # PATH and not in Program Files. `which` alone missed it, so `dotnet build` and the shader+ # translator failed on a machine that had just installed .NET through this app.+ if dn := tc.dotnet_dir():+ parts.append(str(dn))+ elif dn := shutil.which('dotnet'):parts.append(str(Path(dn).parent))env['PATH'] = os.pathsep.join(dict.fromkeys(parts + [env.get('PATH', '')]))diff --git a/frontend-qt/nspb_qt/win/toolchain.py b/frontend-qt/nspb_qt/win/toolchain.pyindex fa835ee8..26585e8a 100644--- a/frontend-qt/nspb_qt/win/toolchain.py+++ b/frontend-qt/nspb_qt/win/toolchain.py@@ -77,13 +77,24 @@ GIT_RELEASE_TAG = 'v2.56.0.windows.4'GIT_RELEASE_URL = f'https://github.com/git-for-windows/git/releases/download/{GIT_RELEASE_TAG}'+def tools_dir() -> Path:+ """Where the app installs the tools it downloads (LLVM, .NET, …).++ `%LOCALAPPDATA%\\NS Port Builder\\tools`, deliberately not inside the app folder: the app ships+ as a zip a user re-extracts for every update, so a toolchain unpacked next to the exe is lost+ the moment they upgrade — 182 MB of LLVM, downloaded again on a slow connection. This folder+ is also writable without administrator rights, which `_internal` under Program Files is not.+ """+ return Path(os.environ.get('LOCALAPPDATA', Path.home() / 'AppData' / 'Local')) / \+ 'NS Port Builder' / 'tools'++def bundled_tools_dir() -> Path:- """Where the app keeps tools it downloaded for itself.+ """The old in-app tools folder, still read so an existing install keeps working.- A frozen build runs from a directory PyInstaller made; `sys._MEIPASS` is that directory- (`<app>/_internal` on Windows). A source run uses the frontend-qt folder. Either way this is- the same base that fetch.install_llvm unpacks into, which is what keeps the installer and the- detector looking at one place.+ Earlier builds unpacked LLVM into `_internal/.tools`; anyone who already downloaded it there+ should not have to fetch it again, so this stays as a fallback candidate and is never+ written to."""base = getattr(sys, '_MEIPASS', None)if base:@@ -121,6 +132,41 @@ SDK_ACCEPTED = ('iPhoneOS26.0.sdk', 'iPhoneOS26.1.sdk', 'iPhoneOS26.2.sdk', 'iPh#: verified by its own layout and a caller-supplied hash, not by trusting this number.SDK_PINNED_COMMIT = '17eb9152ba9779b27427016472758824a8fcd6a7'+#: .NET SDK. `dm/tools/nx_extract` targets net10.0 and the shader translator's runtimeconfig is+#: net10.0, so 10 is the floor; a newer major (11) can still build a net10.0 project as long as+#: the 10 runtime is installed alongside, which the probe checks by asking for the SDK list.+DOTNET_MAJOR = 10+DOTNET_VERSION = '10.0.403'+DOTNET_ASSET = {+ 'name': f'dotnet-sdk-{DOTNET_VERSION}-win-x64.zip',+ 'url': f'https://builds.dotnet.microsoft.com/dotnet/Sdk/{DOTNET_VERSION}/'+ f'dotnet-sdk-{DOTNET_VERSION}-win-x64.zip',+ # SHA-512, because that is what Microsoft's own release metadata publishes — taken from+ # builds.dotnet.microsoft.com/dotnet/release-metadata/10.0/releases.json for 10.0.403. Using+ # their number rather than one we computed is the whole point: a self-computed hash only+ # proves the file matches what we already downloaded.+ 'algo': 'sha512',+ 'sha256': '7a114c318fa7f1d9822991b534b2814d0e78386ceda816b371f5141acefe741d'+ '87ccb606ede06cadac8f9ac5070e32b708a67bbd1619ff5e5a7858a27874ef48',+ 'size': 300745255,+}++#: Mirrors tried after the canonical URL, in order, when the direct download fails or crawls.+#: GitHub release assets are the slow ones on mainland networks (a report measured 974 s for the+#: 182 MiB LLVM archive); Microsoft's CDN is not, so it is absent here. A mirror only changes+#: where the bytes come from — the pinned SHA-256 is what accepts them, so a mirror serving+#: anything else is rejected exactly like a corrupted download.+GITHUB_MIRRORS = ('https://ghfast.top/', 'https://gh-proxy.com/')+++def mirror_urls(url: str) -> list[str]:+ """`url` plus the GitHub mirrors that can serve it (empty for non-GitHub URLs)."""+ out = [url]+ if 'github.com/' in url:+ out += [m + url for m in GITHUB_MIRRORS]+ return out++#: 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.@@ -162,6 +208,19 @@ class Probe:# ---------------------------------------------------------------- configuration+def no_window() -> dict:+ """Subprocess kwargs that stop Windows flashing a console window.++ Every child this app starts (git, clang, metal, the self-extractor) would otherwise pop a+ black window: a GUI process has no console to inherit, so Windows creates one. Reported from+ a handheld as "a command-line window appears and then nothing happens" — it was git's+ console, and the app was still working behind it.+ """+ if sys.platform.startswith('win'):+ return {'creationflags': subprocess.CREATE_NO_WINDOW}+ return {}++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'))@@ -226,10 +285,12 @@ def llvm_dir() -> Path | None:if base:cands += sorted(glob.glob(os.path.join(base, 'Programs', 'LLVM')), reverse=True)cands += sorted(glob.glob(os.path.join(base, 'llvm-mingw*')), reverse=True)- # the app's own download location first: install_llvm() unpacks under- # <app>/_internal/.tools, and without this the freshly installed toolchain was invisible to- # the next dependency check (the report: "installed, then Check again changed nothing").+ # the app's own download locations first: without these the freshly installed toolchain was+ # invisible to the next dependency check (the report: "installed, then Check again changed+ # nothing"). tools_dir() is where installs go now; bundled_tools_dir() is where older builds+ # put them.cands.insert(0, bundled_tools_dir() / f'llvm-mingw-{LLVM_MINGW_VERSION}')+ cands.insert(0, tools_dir() / f'llvm-mingw-{LLVM_MINGW_VERSION}')# a clang already on PATH, if it came from a toolchain with lld beside itif w := shutil.which('clang'):cands.append(Path(w).parent.parent)@@ -320,7 +381,8 @@ def _lld_has_macho(exe: Path) -> bool: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)+ r = subprocess.run([str(clang), '--version'], capture_output=True, text=True,+ timeout=60, **no_window())except (OSError, subprocess.SubprocessError):return ''if r.returncode != 0:@@ -329,6 +391,87 @@ def llvm_version(clang: Path) -> str:return m.group(1) if m else (r.stdout.splitlines() or [''])[0].strip()+# ---------------------------------------------------------------- .NET SDK++def dotnet_dir() -> Path | None:+ """The .NET install root (the folder holding `dotnet.exe`).++ Same three levels as everything else: `toolchain.json`, `NSPB_DOTNET_DIR`, then the standard+ locations plus the copy this app downloaded into its own tools folder. The app-managed copy+ comes first among the fixed paths because a machine that has none anywhere else is exactly+ the machine that ran the in-app installer.+ """+ cands: list[Path | str | None] = [setting('dotnet_dir')]+ for own in (bundled_tools_dir() / f'dotnet-{DOTNET_VERSION}',+ tools_dir() / f'dotnet-{DOTNET_VERSION}'):+ if (own / 'dotnet.exe').is_file():+ cands.insert(0, own)+ cands.append(Path(os.environ.get('ProgramFiles', r'C:\Program Files')) / 'dotnet')+ local = os.environ.get('LOCALAPPDATA')+ if local:+ cands.append(Path(local) / 'Microsoft' / 'dotnet')+ cands.append(Path(local) / 'Programs' / 'dotnet')+ for c in cands:+ if c and (Path(c) / 'dotnet.exe').is_file():+ return Path(c)+ if w := shutil.which('dotnet'):+ return Path(w).parent+ return None+++def dotnet_sdks(root: Path) -> list[str]:+ """The SDK versions `dotnet --list-sdks` reports, newest first. Empty when it will not run."""+ try:+ r = subprocess.run([str(root / 'dotnet.exe'), '--list-sdks'], capture_output=True,+ text=True, timeout=120, **no_window())+ except (OSError, subprocess.SubprocessError):+ return []+ if r.returncode != 0:+ return []+ out = []+ for line in (r.stdout or '').splitlines():+ m = re.match(r'(\d+)\.(\d+)\.(\d+)', line.strip())+ if m:+ out.append(m.group(0))+ return sorted(out, key=lambda v: tuple(int(x) for x in v.split('.')), reverse=True)+++def probe_dotnet() -> Probe:+ """`.NET SDK 10`, judged by running `dotnet --list-sdks`, not by finding the exe.++ `nx_extract` targets net10.0 and the shader translator's runtimeconfig is net10.0, so a+ machine with only SDK 8 or 9 builds nothing — and the failure would surface deep inside the+ build as a NuGet error. This row exists because the dependency panel used to have no .NET+ line at all on Windows (the panel's row came from a macOS-only branch), which is exactly the+ bug the handheld report described: "the first dependency, .NET SDK 10, never appears in the+ log".+ """+ root = dotnet_dir()+ if not root:+ return Probe('dotnet', f'.NET SDK {DOTNET_MAJOR}', 'missing',+ f'dotnet.exe not found (need SDK {DOTNET_MAJOR} for net10.0)',+ hint=f'downloaded in the app ({DOTNET_ASSET["name"]}, about 287 MB), '+ 'or from dotnet.microsoft.com/download',+ pinned=DOTNET_VERSION,+ extra={'download': DOTNET_ASSET})+ sdks = dotnet_sdks(root)+ if not sdks:+ return Probe('dotnet', f'.NET SDK {DOTNET_MAJOR}', 'wrong',+ f'{root / "dotnet.exe"} does not run (a partial install?)',+ hint='reinstall the SDK, or delete that folder and let the app fetch one',+ path=str(root), pinned=DOTNET_VERSION,+ extra={'download': DOTNET_ASSET})+ major_ok = [v for v in sdks if int(v.split('.')[0]) >= DOTNET_MAJOR]+ if major_ok:+ return Probe('dotnet', f'.NET SDK {DOTNET_MAJOR}', 'ok', f'SDK {major_ok[0]}',+ path=str(root), version=major_ok[0], pinned=DOTNET_VERSION)+ return Probe('dotnet', f'.NET SDK {DOTNET_MAJOR}', 'wrong',+ f'found SDK {sdks[0]} at {root}, but nx_extract targets net10.0',+ hint=f'install SDK {DOTNET_MAJOR} alongside it (the app can download one)',+ path=str(root), version=sdks[0], pinned=DOTNET_VERSION,+ extra={'download': DOTNET_ASSET})++# ---------------------------------------------------------------- iPhoneOS SDKdef _sdk_candidates() -> list[Path]:@@ -490,7 +633,8 @@ def metal_version() -> str:if not m:return ''try:- r = subprocess.run([str(m), '--version'], capture_output=True, text=True, timeout=60)+ r = subprocess.run([str(m), '--version'], capture_output=True, text=True,+ timeout=60, **no_window())except (OSError, subprocess.SubprocessError):return ''text = (r.stdout or '') + (r.stderr or '')@@ -560,7 +704,7 @@ def probe_compile(sdk: Path, clang: Path | None = None) -> tuple[bool, str]: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)+ r = subprocess.run(cmd, capture_output=True, text=True, timeout=180, **no_window())except subprocess.TimeoutExpired:return False, 'clang timed out on the probe'except OSError as e:@@ -602,7 +746,7 @@ def probe_metal(sdk: Path) -> tuple[bool, str]:([str(metallib), str(a), '-o', str(lib)], 'metallib')):try:r = subprocess.run(cmd, capture_output=True, text=True, timeout=180,- cwd=td)+ cwd=td, **no_window())except subprocess.TimeoutExpired:return False, f'{what} timed out'except OSError as e:@@ -638,7 +782,8 @@ def probe_link(sdk: Path) -> tuple[bool, str]: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)+ r = subprocess.run(cmd, capture_output=True, text=True, timeout=180, env=env,+ **no_window())except subprocess.TimeoutExpired:return False, 'link timed out'except OSError as e:@@ -701,6 +846,9 @@ def check_all(deep: bool = False) -> list[Probe]:'fix the JSON, or delete the file to fall back to auto-detection',pinned='', required=False))+ # ---- .NET (the extractor and the shader translator both target net10.0)+ out.append(probe_dotnet())+# ---- LLVMroot = llvm_dir()clang = llvm_tool('clang')diff --git a/frontend-qt/tests/test_win.py b/frontend-qt/tests/test_win.pyindex d2d96a32..e958dae4 100644--- a/frontend-qt/tests/test_win.py+++ b/frontend-qt/tests/test_win.py@@ -745,6 +745,347 @@ class FetchTest(unittest.TestCase):self.assertIn(tc.LLVM_MINGW_VERSION, a['url'])self.assertTrue(a['url'].endswith(a['name']))+ def test_mirror_urls_cover_github_assets(self) -> None:+ """A GitHub release asset gets the direct URL plus every mirror, in that order.++ The handheld report measured 974 s for the 182 MiB LLVM archive from GitHub, so a+ mainland connection needs the mirrors; the direct URL stays first for everyone else.+ """+ urls = tc.mirror_urls('https://github.com/mstorsjo/llvm-mingw/releases/download/x/y.zip')+ self.assertEqual(urls[0],+ 'https://github.com/mstorsjo/llvm-mingw/releases/download/x/y.zip')+ self.assertEqual(len(urls), 1 + len(tc.GITHUB_MIRRORS))+ for m, u in zip(tc.GITHUB_MIRRORS, urls[1:]):+ self.assertEqual(u, m + urls[0])++ def test_mirror_urls_leave_other_hosts_alone(self) -> None:+ """Microsoft's CDN is fast on mainland networks; proxying it would only add a hop."""+ self.assertEqual(tc.mirror_urls(tc.DOTNET_ASSET['url']), [tc.DOTNET_ASSET['url']])++ def test_rank_by_speed_puts_the_fastest_first(self) -> None:+ """The 974-second case: nothing failed, so only a speed probe can pick a better source."""+ from nspb_qt.win import fetch+ urls = ['https://slow/x.zip', 'https://fast/x.zip', 'https://dead/x.zip']++ class Resp:+ """First read delivers a slice, the second delivers the rest: a transfer window."""++ def __init__(self, first, rest):+ self.chunks = [first, rest]++ def read(self, n):+ return self.chunks.pop(0) if self.chunks else b''++ def __enter__(self):+ return self++ def __exit__(self, *a):+ return False++ # each URL: t_first, t_end. slow transfers in 3.0 s, fast in 0.2 s, dead raises.+ clock = iter([0.0, 3.0, 10.0, 10.2])++ def fake_urlopen(req, timeout=0):+ if 'dead' in req.full_url:+ raise OSError('no route')+ return Resp(b'x' * 65536, b'y' * 65536)++ with mock.patch('urllib.request.urlopen', fake_urlopen), \+ mock.patch('time.time', side_effect=lambda: next(clock)):+ out = fetch.rank_by_speed(urls, log=lambda s: None)+ # fastest first, the unreachable one last rather than dropped+ self.assertEqual(out, ['https://fast/x.zip', 'https://slow/x.zip', 'https://dead/x.zip'])++ def test_rank_by_speed_times_the_transfer_not_the_handshake(self) -> None:+ """A slow TLS setup must not make a fast source look slow.++ The first version timed from the request, and every mirror's proxy handshake (2-3 s on a+ real connection) dominated the 256 KB transfer, so it picked at random.+ """+ from nspb_qt.win import fetch++ class Resp:+ def __init__(self, chunks):+ self.chunks = list(chunks)++ def read(self, n):+ return self.chunks.pop(0) if self.chunks else b''++ def __enter__(self):+ return self++ def __exit__(self, *a):+ return False++ # both deliver in 0.1 s of transfer, but "slow" took 30 s to connect+ clock = iter([30.0, 30.1, 31.0, 31.1])++ def fake_urlopen(req, timeout=0):+ return Resp([b'x' * 65536, b'y' * 65536])++ with mock.patch('urllib.request.urlopen', fake_urlopen), \+ mock.patch('time.time', side_effect=lambda: next(clock)):+ out = fetch.rank_by_speed(['https://a/x', 'https://b/x'], log=lambda s: None)+ self.assertEqual(len(out), 2) # neither was penalised for its handshake++ def test_rank_by_speed_keeps_a_single_url_untouched(self) -> None:+ """No probe when there is nothing to choose between (a non-GitHub URL)."""+ from nspb_qt.win import fetch+ with mock.patch('urllib.request.urlopen', side_effect=AssertionError('probed')):+ self.assertEqual(fetch.rank_by_speed(['https://only/x'], lambda s: None),+ ['https://only/x'])++ def test_download_falls_through_to_a_mirror(self) -> None:+ """The first URL failing must not end the download; the hash decides what is accepted."""+ from nspb_qt.win import fetch+ payload = b'toolchain bytes'+ want = __import__('hashlib').sha256(payload).hexdigest()++ class Resp:+ headers = {'Content-Length': str(len(payload))}++ def __init__(self):+ self.left = payload++ def read(self, n):+ b, self.left = self.left, b'' # one read, then EOF: download() loops until b''+ return b++ def __enter__(self):+ return self++ def __exit__(self, *a):+ return False++ seen = []++ def fake_urlopen(req, timeout=0):+ seen.append(req.full_url)+ if len(seen) == 1:+ raise OSError('connection reset') # the direct URL fails+ return Resp()++ with tempfile.TemporaryDirectory() as td, \+ mock.patch('urllib.request.urlopen', fake_urlopen), \+ mock.patch.object(fetch, 'rank_by_speed', lambda u, log, **k: u):+ out = fetch.download('https://github.com/a/b/releases/download/v/x.zip',+ Path(td) / 'x.zip', want, log=lambda s: None)+ self.assertEqual(out.read_bytes(), payload)+ self.assertEqual(len(seen), 2)+ self.assertTrue(seen[1].startswith(tc.GITHUB_MIRRORS[0]))++ def test_download_rejects_a_mirror_serving_other_bytes(self) -> None:+ """A mirror is only a transport: bytes that do not match the pin are refused."""+ from nspb_qt.win import fetch++ class Resp:+ headers = {}++ def __init__(self, body):+ self.body = body++ def read(self, n):+ b, self.body = self.body, b''+ return b++ def __enter__(self):+ return self++ def __exit__(self, *a):+ return False++ calls = []++ def fake_urlopen(req, timeout=0):+ calls.append(req.full_url)+ # the direct URL is unreachable, the first mirror serves the wrong bytes, the+ # second mirror serves the right ones+ if len(calls) == 1:+ raise OSError('no route')+ return Resp(b'wrong' if len(calls) == 2 else b'right')++ want = __import__('hashlib').sha256(b'right').hexdigest()+ with tempfile.TemporaryDirectory() as td, \+ mock.patch('urllib.request.urlopen', fake_urlopen), \+ mock.patch.object(fetch, 'rank_by_speed', lambda u, log, **k: u):+ out = fetch.download('https://github.com/a/b/releases/download/v/x.zip',+ Path(td) / 'x.zip', want, log=lambda s: None)+ self.assertEqual(out.read_bytes(), b'right')+ self.assertEqual(len(calls), 3)++ def test_download_reports_every_failure(self) -> None:+ """When nothing works the message names each attempt, not just the last one."""+ from nspb_qt.win import fetch++ def fake_urlopen(req, timeout=0):+ raise OSError('unreachable')++ with tempfile.TemporaryDirectory() as td, \+ mock.patch('urllib.request.urlopen', fake_urlopen), \+ mock.patch.object(fetch, 'rank_by_speed', lambda u, log, **k: u):+ with self.assertRaises(fetch.DownloadError) as cm:+ fetch.download('https://github.com/a/b/releases/download/v/x.zip',+ Path(td) / 'x.zip', '0' * 64, log=lambda s: None)+ msg = str(cm.exception)+ self.assertIn('unreachable', msg)+ self.assertEqual(msg.count('github.com/a/b'), 1 + len(tc.GITHUB_MIRRORS))+++class DotnetTest(unittest.TestCase):+ """The .NET row and its in-app installer.++ The handheld report's first line was "the first dependency, .NET SDK 10, never appears in the+ log": on Windows the panel built its rows from `_windows_deps`, which had no .NET entry, so+ `install all` could not install it and nothing said so.+ """++ def test_dotnet_asset_is_pinned(self) -> None:+ """Microsoft publishes SHA-512 in releases.json, so the pin carries that algorithm."""+ a = tc.DOTNET_ASSET+ algo = a.get('algo', 'sha256')+ want = 128 if algo == 'sha512' else 64+ self.assertEqual(len(a['sha256']), want, algo)+ self.assertTrue(all(c in '0123456789abcdef' for c in a['sha256']))+ self.assertGreater(a['size'], 200_000_000)+ self.assertIn(tc.DOTNET_VERSION, a['url'])+ self.assertTrue(a['url'].endswith(a['name']))++ def test_dotnet_version_satisfies_the_extractor_target(self) -> None:+ """`nx_extract` targets net10.0; a lower major builds nothing, so the pin must be >= 10."""+ repo = QT.parent+ csproj = (repo / 'dm/tools/nx_extract/nx_extract.csproj').read_text(encoding='utf-8')+ self.assertIn(f'net{tc.DOTNET_MAJOR}.0', csproj)++ def test_probe_reports_missing_when_no_dotnet_anywhere(self) -> None:+ with mock.patch.object(tc, 'dotnet_dir', return_value=None):+ p = tc.probe_dotnet()+ self.assertEqual(p.state, 'missing')+ self.assertEqual(p.id, 'dotnet')+ self.assertIn('download', p.extra)++ def test_probe_rejects_an_old_sdk(self) -> None:+ """SDK 8 alone is `wrong`, not `ok`: the failure would otherwise appear mid-build."""+ with tempfile.TemporaryDirectory() as td, \+ mock.patch.object(tc, 'dotnet_dir', return_value=Path(td)), \+ mock.patch.object(tc, 'dotnet_sdks', return_value=['8.0.404']):+ p = tc.probe_dotnet()+ self.assertEqual(p.state, 'wrong')+ self.assertIn('net10.0', p.detail)++ def test_probe_accepts_sdk_10_and_newer(self) -> None:+ for sdks in (['10.0.403'], ['11.0.100', '10.0.403']):+ with tempfile.TemporaryDirectory() as td, \+ mock.patch.object(tc, 'dotnet_dir', return_value=Path(td)), \+ mock.patch.object(tc, 'dotnet_sdks', return_value=sdks):+ p = tc.probe_dotnet()+ self.assertEqual(p.state, 'ok', sdks)+ self.assertEqual(p.version, sdks[0])++ def test_tools_dir_is_outside_the_app_folder(self) -> None:+ """Tools must survive an app update (the app is re-extracted from a zip).++ This was a real bug: LLVM unpacked into `_internal/.tools`, so every update threw away+ 182 MB of toolchain. `bundled_tools_dir()` stays as a read-only fallback for people who+ already have it there.+ """+ with mock.patch.dict(os.environ, {'LOCALAPPDATA': '/tmp/fake-local'}):+ self.assertEqual(tc.tools_dir(), Path('/tmp/fake-local/NS Port Builder/tools'))+ self.assertNotEqual(tc.tools_dir(), tc.bundled_tools_dir())++ def test_llvm_dir_finds_the_app_installed_copy(self) -> None:+ """The install-then-check-again path: the detector has to look where the installer wrote."""+ with tempfile.TemporaryDirectory() as td:+ tools = Path(td) / 'tools'+ llvm = tools / f'llvm-mingw-{tc.LLVM_MINGW_VERSION}'+ (llvm / 'bin').mkdir(parents=True)+ (llvm / 'bin/clang.exe').write_bytes(b'stub')+ with mock.patch.object(tc, 'tools_dir', return_value=tools), \+ mock.patch.object(tc, 'setting', return_value=None), \+ mock.patch.dict(os.environ, {}, clear=False), \+ mock.patch('shutil.which', return_value=None):+ os.environ.pop('NSPB_LLVM_DIR', None)+ self.assertEqual(tc.llvm_dir(), llvm)++ def test_install_dotnet_rejects_an_archive_without_dotnet_exe(self) -> None:+ """A changed release layout stops with a message instead of leaving a broken folder."""+ from nspb_qt.win import fetch+ with tempfile.TemporaryDirectory() as td:+ root = Path(td)+ z = root / 'downloads' / tc.DOTNET_ASSET['name']+ z.parent.mkdir(parents=True)+ with zipfile.ZipFile(z, 'w') as zf:+ zf.writestr('somewhere/else.txt', 'no dotnet here')+ with mock.patch.object(fetch, 'download', return_value=z):+ with self.assertRaises(fetch.DownloadError) as cm:+ fetch.install_dotnet(dest=root, log=lambda s: None)+ self.assertIn('dotnet.exe', str(cm.exception))+ self.assertFalse((root / f'dotnet-{tc.DOTNET_VERSION}').exists())++ def test_install_dotnet_unpacks_at_the_root(self) -> None:+ """The SDK zip has no top-level folder: dotnet.exe ends up at the install root."""+ from nspb_qt.win import fetch+ with tempfile.TemporaryDirectory() as td:+ root = Path(td)+ z = root / 'downloads' / tc.DOTNET_ASSET['name']+ z.parent.mkdir(parents=True)+ with zipfile.ZipFile(z, 'w') as zf:+ zf.writestr('dotnet.exe', b'MZ')+ zf.writestr('sdk/10.0.403/dotnet.dll', b'x')+ with mock.patch.object(fetch, 'download', return_value=z):+ out = fetch.install_dotnet(dest=root, log=lambda s: None)+ self.assertEqual(out, root / f'dotnet-{tc.DOTNET_VERSION}')+ self.assertTrue((out / 'dotnet.exe').is_file())+ self.assertTrue((out / 'sdk/10.0.403/dotnet.dll').is_file())+++class ConsoleWindowTest(unittest.TestCase):+ """No child of this app may open its own console window on Windows.++ The handheld report: "after the last log line a command-line window appears, shows nothing,+ and the install progress stops" — it was a git child's console. The fix patches+ `subprocess.Popen` once at start-up, so the repository's own scripts (which this front end+ does not own) inherit the invisible console too.+ """++ def test_no_window_kwargs_are_empty_off_windows(self) -> None:+ from nspb_qt import platform_util as pu+ if not pu.IS_WIN:+ self.assertEqual(pu.no_window_kwargs(), {})++ def test_patch_adds_creationflags_and_keeps_explicit_ones(self) -> None:+ from nspb_qt import platform_util as pu+ seen = []++ class FakePopen:+ def __init__(self, args, *a, **k):+ seen.append(k)++ original = subprocess.Popen.__init__+ subprocess.Popen.__init__ = FakePopen.__init__+ try:+ with mock.patch.object(pu, 'IS_WIN', True), \+ mock.patch.object(subprocess, 'CREATE_NO_WINDOW', 0x08000000, create=True):+ pu.hide_console_for_children()+ subprocess.Popen(['x'])+ subprocess.Popen(['x'], creationflags=0x00000008) # DETACHED_PROCESS+ finally:+ subprocess.Popen.__init__ = original+ self.assertEqual(seen[0].get('creationflags'), 0x08000000)+ self.assertEqual(seen[1].get('creationflags'), 0x00000008) # caller's intent kept++ def test_patch_is_a_no_op_off_windows(self) -> None:+ from nspb_qt import platform_util as pu+ before = subprocess.Popen.__init__+ with mock.patch.object(pu, 'IS_WIN', False):+ pu.hide_console_for_children()+ self.assertIs(subprocess.Popen.__init__, before)++ def test_win_modules_call_the_helper(self) -> None:+ """The direct calls (probes, git, the self-extractor) pass it explicitly."""+ for name in ('toolchain.py', 'fetch.py', 'sdk_fetch.py'):+ src = (QT / 'nspb_qt/win' / name).read_text(encoding='utf-8')+ self.assertIn('no_window()', src, name)+class ConstantParityTest(unittest.TestCase):"""`toolchain.py` duplicates the package constants so it can be loaded standalone from thediff --git a/frontend/NS-Port-Builder-macOS-arm64.zip b/frontend/NS-Port-Builder-macOS-arm64.zipindex 3e8128d1..d4dca87d 100644Binary files a/frontend/NS-Port-Builder-macOS-arm64.zip and b/frontend/NS-Port-Builder-macOS-arm64.zip differdiff --git a/frontend/Sources/NSPortBuilder/ContentView.swift b/frontend/Sources/NSPortBuilder/ContentView.swiftindex 7a50eaa4..09e32248 100644--- a/frontend/Sources/NSPortBuilder/ContentView.swift+++ b/frontend/Sources/NSPortBuilder/ContentView.swift@@ -318,7 +318,7 @@ final class BuildModel: ObservableObject {// ---- App self-update (GitHub Releases) ----/// Bump together with each release tag; the update check compares it with the latest release.- static let appVersion = "0.4.5"+ static let appVersion = "0.4.6"@Published var appUpdate: (tag: String, url: String)?@Published var appBusy = false@Published var appStatus = ""diff --git a/frontend/Sources/NSPortBuilder/Localization.swift b/frontend/Sources/NSPortBuilder/Localization.swiftindex bb57c935..30b5f7a7 100644--- a/frontend/Sources/NSPortBuilder/Localization.swift+++ b/frontend/Sources/NSPortBuilder/Localization.swift@@ -201,6 +201,8 @@ enum L10n {"dep.dotnet": (".NET SDK 10", ".NET SDK 10"),"dep.dotnet.hint": ("dotnet-install.sh 装到 ~/.dotnet", "dotnet-install.sh into ~/.dotnet"),"dep.dotnet.missing": ("没找到带 SDK 10 的 dotnet", "no dotnet with SDK 10 found"),+ "dep.dotnet.downloading": ("正在下载 .NET SDK 10…(约 287 MB,解压后约 900 MB)", "Downloading .NET SDK 10… (about 287 MB, about 900 MB unpacked)"),+ "dep.dotnet.done": (".NET SDK 已安装:%@", ".NET SDK installed: %@"),"dep.python": ("Python + 包", "Python + packages"),"dep.python.hint": ("lz4 capstone fonttools backports.zstd", "lz4 capstone fonttools backports.zstd"),"dep.python.missing": ("%@ 缺包", "%@ is missing packages"),