Play your own Switch games on iPhone/iPad — one-click macOS app, no terminal. | 把 Switch 游戏装进 iPhone:图形界面一键构建,不用命令行。Bring your own game.
Swift apple-siliconcustom-formathomebrewiosipaipadipadosiphonemetalnative-portnintendo-switchnxnativeromfsswitch-games
Windows: the Metal probe works under a Chinese user name, and the panel stops crying wolf
LNPANDY20da7e91e483
diff --git a/frontend-qt/nspb_qt/localization.py b/frontend-qt/nspb_qt/localization.pyindex ba5982fb..56cbd82a 100644--- a/frontend-qt/nspb_qt/localization.py+++ b/frontend-qt/nspb_qt/localization.py@@ -207,6 +207,10 @@ TABLE: dict[str, tuple[str, str]] = {'dep.checkFailed': ('依赖检测失败——详情见日志(不是「已就绪」)', 'Dependency check failed — see the log (this is not a pass)'),'dep.allReady': ('全部就绪', 'All ready'),'dep.missing': ('缺 %d 项', '%d missing'),+ 'dep.onlyOptional': ('必备项都齐了(%d 项可选未装,只影响部分游戏)',+ 'everything required is installed (%d optional missing, only some games need them)'),+ 'dep.missingOptional': ('缺 %d 项(另有 %d 项可选,只影响部分游戏)',+ '%d missing (%d optional, only some games need them)'),'dep.llvm': ('LLVM-MinGW(交叉编译)', 'LLVM-MinGW (cross compiler)'),'dep.llvm.hint': ('Windows 上编译 iOS 二进制用(app 内自动下载)', 'builds the iOS binary on Windows (downloaded in-app)'),'dep.llvm.downloading': ('正在下载 LLVM-MinGW…(约 250 MB)', 'Downloading LLVM-MinGW… (about 250 MB)'),@@ -243,7 +247,10 @@ TABLE: dict[str, tuple[str, str]] = {'dep.xcodegen.hint': ('Xcode 工程生成', 'generates the Xcode project'),'dep.zstd': ('brew: zstd', 'brew: zstd'),'dep.spirv.win': ('spirv-cross', 'spirv-cross'),- 'dep.spirv.hint.win': ('仅 OpenGL 游戏需要——<a href="https://vulkan.lunarg.com/sdk/home">Vulkan SDK</a> 自带(装完在 toolchain.json 里指一下 Bin 目录)', 'only OpenGL games need it — the <a href="https://vulkan.lunarg.com/sdk/home">Vulkan SDK</a> ships it (point "spirv_cross_dir" in toolchain.json at its Bin folder)'),+ 'dep.spirv.hint.win': ('仅 OpenGL 游戏(如 Balatro、Digimon)需要,Metal 游戏用不到。装 <a href="https://vulkan.lunarg.com/sdk/home">Vulkan SDK</a> 即可,本程序会自动在 %VULKAN_SDK%\\Bin 和 C:\\VulkanSDK\\<版本>\\Bin 里找到它,不用改任何配置',+ 'only OpenGL games (Balatro, Digimon) need it; Metal games never do. Install the '+ '<a href="https://vulkan.lunarg.com/sdk/home">Vulkan SDK</a> and this app finds it in '+ '%VULKAN_SDK%\\Bin or C:\\VulkanSDK\\<version>\\Bin by itself — no configuration'),'dep.zstd.win': ('zstd', 'zstd'),'dep.zstd.hint.win': ('解压——点「安装」由 App 下载(facebook/zstd 官方 Windows 版)', "decompression — press Install and the app fetches it (facebook/zstd's official Windows build)"),'dep.metal.hint.win': ('需要 <a href="https://developer.apple.com/download/all/">Apple 开发者下载页</a> 的「Metal Developer Tools for Windows」(需 Apple ID)', 'needs <a href="https://developer.apple.com/download/all/">Apple developer downloads</a>: "Metal Developer Tools for Windows" (Apple ID required)'),diff --git a/frontend-qt/nspb_qt/model.py b/frontend-qt/nspb_qt/model.pyindex 6aea490a..fd999500 100644--- a/frontend-qt/nspb_qt/model.py+++ b/frontend-qt/nspb_qt/model.py@@ -37,6 +37,8 @@ class Dep:detail: str = '' # a path, or a localisation key, or "key:arg"install: list[str] = field(default_factory=list) # command that fixes it, empty = manualinstalling: bool = False+ required: bool = True # a missing optional row (spirv-cross for Metal games, glslangValidator)+ # is not part of "缺 N 项": it does not stop the build in front of you@propertydef ok(self) -> bool:@@ -386,24 +388,24 @@ class Model(QObject):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.- # Titles and hints are the Windows ones here ('brew: …' is the macOS row's wording, and- # the report read "brew: spirv-cross" on a handheld); zstd is installable in-app, and- # spirv-cross points at the Vulkan SDK — Apple-style gated downloads are not the only- # thing this panel cannot fetch silently.+ # Cross-platform tools. zstd is required (every build unpacks with it) and installable+ # in-app. spirv-cross is needed only by an OpenGL game and glslangValidator only by that+ # same path, so neither is required: a Metal title builds without them, and counting them+ # in "缺 N 项" told a user with a complete Metal toolchain that three things were wrong+ # (the report's screenshot: only spirv-cross was genuinely absent).+ #+ # Both are marked optional but shown in the state they are really in — a green dot on a+ # tool that is not installed read as "present" and hid the one row worth acting on.for pid, key, hint, req, install in (- ('spirv-cross', 'dep.spirv.win', 'dep.spirv.hint.win', True, []),+ ('spirv-cross', 'dep.spirv.win', 'dep.spirv.hint.win', False, []),('zstd', 'dep.zstd.win', 'dep.zstd.hint.win', True, ['__win__:zstd']),('glslangValidator', 'dep.glslang', 'dep.glslang.hint', False, [])):p = by_id.get(pid)if p:d = Dep(pid, key, hint,- DepState.OK if p.ok else DepState.MISSING, p.path if p.ok else '',- install=[] if p.ok else install)- 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')+ DepState.OK if p.ok else DepState.MISSING,+ p.path if p.ok else (self.t('dep.optionalMissing') if not req else ''),+ install=[] if p.ok else install, required=req)out.append(d)# Windows-on-ARM gets a visible note: the tools are x86-64 and run emulated.if note := wtc.host_arch_note():diff --git a/frontend-qt/nspb_qt/style.py b/frontend-qt/nspb_qt/style.pyindex 39281004..f6681be1 100644--- a/frontend-qt/nspb_qt/style.py+++ b/frontend-qt/nspb_qt/style.py@@ -12,6 +12,9 @@ CARD = '#252a31' # a card's fillCARD_EDGE = '#31373f' # a card's hairlineTEXT = '#e6e9ed'MUTED = '#8b949e'+PATH = '#6b7480' # a filesystem path in a dependency row: dimmer than prose, so the eye+ # reads the hint beside it first (the report asked for exactly this)+HINT = '#9aa4b0' # a hint or explanation: a step brighter than the path it sits next toGREEN = '#34c759' # ok / doneORANGE = '#ff9f0a' # attentionRED = '#ff453a' # missing / failed@@ -75,8 +78,8 @@ QPushButton#danger {{/* ---- labels ---- */QLabel#title {{ font-size: 17pt; font-weight: 700; background: transparent; }}QLabel#subtitle {{ color: {MUTED}; font-size: 9pt; background: transparent; }}-QLabel#note {{ color: {MUTED}; font-size: 8pt; background: transparent; }}-QLabel#mono {{ color: {MUTED}; font-family: Menlo, Consolas, monospace; font-size: 8pt; background: transparent; }}+QLabel#note {{ color: {HINT}; font-size: 8pt; background: transparent; }}+QLabel#mono {{ color: {PATH}; font-family: Menlo, Consolas, monospace; font-size: 8pt; background: transparent; }}QLabel#ok {{ color: {GREEN}; font-weight: 600; background: transparent; }}QLabel#warn {{ color: {ORANGE}; font-weight: 600; }}QLabel#bad {{ color: {RED}; font-weight: 600; background: transparent; }}diff --git a/frontend-qt/nspb_qt/ui.py b/frontend-qt/nspb_qt/ui.pyindex 64bf7ad6..f3dbe82e 100644--- a/frontend-qt/nspb_qt/ui.py+++ b/frontend-qt/nspb_qt/ui.py@@ -420,8 +420,19 @@ class MainWindow(QMainWindow):self.deps_summary.setText('● ' + self.m.t('dep.allReady'))self.deps_summary.setStyleSheet(f'color: {GREEN}; font-weight: 600;')else:- n = sum(1 for d in self.m.deps if not d.ok)- self.deps_summary.setText(self.m.t('dep.missing', n))+ # Required only: an optional tool (glslangValidator for OpenGL games) or one that+ # only some titles need (spirv-cross) was counted here, so a machine that could+ # build the game in front of it read "缺 3 项" and looked broken.+ n = sum(1 for d in self.m.deps if not d.ok and getattr(d, 'required', True))+ optional = sum(1 for d in self.m.deps if not d.ok and not getattr(d, 'required', True))+ if n == 0 and optional:+ # nothing is actually blocking: saying "缺 0 项(另有 2 项可选)" reads like a+ # problem where there is none+ self.deps_summary.setText(self.m.t('dep.onlyOptional', optional))+ self.deps_summary.setStyleSheet(f'color: {GREEN}; font-weight: 600;')+ return+ self.deps_summary.setText(self.m.t('dep.missingOptional', n, optional) if optional+ else self.m.t('dep.missing', n))self.deps_summary.setStyleSheet(f'color: {RED}; font-weight: 600;')else:self.deps_summary.setText(self.m.t('dep.checking'))diff --git a/frontend-qt/nspb_qt/win/toolchain.py b/frontend-qt/nspb_qt/win/toolchain.pyindex d623e165..e45d7022 100644--- a/frontend-qt/nspb_qt/win/toolchain.py+++ b/frontend-qt/nspb_qt/win/toolchain.py@@ -437,7 +437,7 @@ def clang_compiles(clang: Path) -> tuple[bool, str]:directory only, which is the capability every later step depends on. Same shape of probethat was green on the machine where --version failed."""- with tempfile.TemporaryDirectory(prefix='nspb-clang-') as td:+ with ascii_temp_dir('nspb-clang-') as td:c = Path(td) / 'probe.c'o = Path(td) / 'probe.o'c.write_text('int dm_clang_probe(void) { return 42; }\n', encoding='utf-8')@@ -760,6 +760,25 @@ def find_exe(name: str) -> Path | None:for cand in (f'{name}.exe', name):if w := shutil.which(cand):return Path(w)+ # The Vulkan SDK does not put Bin on PATH, and asking the user to write a JSON path was the+ # old answer to that — unusable for someone who just installed the SDK. Its layout is fixed:+ # %VULKAN_SDK%\Bin, else C:\VulkanSDK\<version>\Bin, newest first.+ if name in ('spirv-cross', 'glslangValidator'):+ roots = [os.environ.get('VULKAN_SDK', '')]+ base = Path(os.environ.get('ProgramFiles', r'C:\Program Files')) / 'VulkanSDK'+ if base.is_dir():+ try:+ roots += [str(base / v) for v in sorted((d.name for d in base.iterdir() if d.is_dir()),+ key=lambda s: [int(x) for x in re.findall(r'\d+', s)] or [0],+ reverse=True)]+ except OSError:+ pass+ for root in roots:+ if not root:+ continue+ for cand in (Path(root) / 'Bin' / f'{name}.exe', Path(root) / f'{name}.exe'):+ if cand.is_file():+ return candreturn None@@ -799,7 +818,7 @@ def probe_compile(sdk: Path, clang: Path | None = None) -> tuple[bool, str]: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:+ with ascii_temp_dir('nspb-probe-') as td:c = Path(td) / 'probe.m'o = Path(td) / 'probe.o'c.write_text(src, encoding='utf-8')@@ -830,6 +849,49 @@ def probe_compile(sdk: Path, clang: Path | None = None) -> tuple[bool, str]:return True, f'arm64 Mach-O object, {o.stat().st_size} bytes'+def ascii_temp_dir(prefix: str = 'nspb-'):+ """A temporary directory whose path is pure ASCII, for tools that cannot open anything else.++ Apple's Windows ports of metal.exe and metallib.exe (LLVM-based) fail with+ "LLVM ERROR: Error opening '<path>'" when the path holds characters outside ASCII, and on a+ Chinese Windows the default TEMP is C:\\Users\\<中文名>\\AppData\\Local\\Temp — so the Metal+ probe failed on a machine where the toolchain was installed correctly (the report's two+ screenshots: everything green, Metal Toolchain found, then "metallib failed: LLVM ERROR").+ clang and ld64.lld handle the same path fine, which is why only this probe broke.++ Order: the normal TEMP when it is ASCII (the common case), then the public temp folder, then+ the drive root. The caller gets a TemporaryDirectory that it must keep open for the tool's+ lifetime; the fallbacks are only used when the default really cannot work.+ """+ import tempfile as _tf+ def ok(p: str) -> bool:+ try:+ p.encode('ascii')+ return True+ except UnicodeEncodeError:+ return False+ candidates = [tempfile.gettempdir()]+ if os.name == 'nt':+ candidates += [os.environ.get('PUBLIC', r'C:\Users\Public') + r'\Temp', r'C:\Windows\Temp', 'C:\\Temp']+ for base in candidates:+ if not base or not ok(base):+ continue+ try:+ Path(base).mkdir(parents=True, exist_ok=True)+ return _tf.TemporaryDirectory(prefix=prefix, dir=base)+ except OSError:+ continue+ # Nothing ASCII is writable: fall back to the default (created first — the caller may be on a+ # system where gettempdir() names a folder that does not exist yet) and let the tool say what+ # it says.+ default = tempfile.gettempdir()+ try:+ Path(default).mkdir(parents=True, exist_ok=True)+ except OSError:+ pass+ return _tf.TemporaryDirectory(prefix=prefix, dir=default)++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')@@ -838,7 +900,7 @@ def probe_metal(sdk: Path) -> tuple[bool, str]: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:+ with ascii_temp_dir('nspb-metal-') as td:m = Path(td) / 'probe.metal'a = Path(td) / 'probe.air'lib = Path(td) / 'probe.metallib'@@ -874,7 +936,7 @@ def probe_link(sdk: Path) -> tuple[bool, str]: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:+ with ascii_temp_dir('nspb-link-') as td:c = Path(td) / 'probe.c'out = Path(td) / 'probe'c.write_text(src, encoding='utf-8')@@ -1037,7 +1099,7 @@ def check_all(deep: bool = False) -> list[Probe]:# ---- the rest of the toolchainfor name, label, hint, req in (- ('spirv-cross', 'spirv-cross', 'Vulkan SDK for Windows (vulkan.lunarg.com), or a GitHub release', True),+ ('spirv-cross', 'spirv-cross', 'Vulkan SDK for Windows (vulkan.lunarg.com), or a GitHub release', False),('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)diff --git a/frontend-qt/tests/test_ascii_temp.py b/frontend-qt/tests/test_ascii_temp.pynew file mode 100644index 00000000..d86e7d74--- /dev/null+++ b/frontend-qt/tests/test_ascii_temp.py@@ -0,0 +1,54 @@+"""A tool that cannot open a non-ASCII path gets an ASCII temp directory.++Apple's Windows ports of metal.exe and metallib.exe are LLVM-based and fail with+"LLVM ERROR: Error opening '<path>'" when the path holds characters outside ASCII. On a Chinese+Windows the default TEMP is C:\\Users\\<中文名>\\AppData\\Local\\Temp, so the Metal probe reported a+broken toolchain on a machine where Metal Developer Tools were installed correctly and found — the+report's second screenshot: Metal Toolchain green, then "metallib failed: LLVM ERROR: Error opening+...\\probe.air". clang and ld64.lld read the same path fine, which is why only that probe broke.+"""+from __future__ import annotations++import os+import sys+import tempfile+import unittest+from pathlib import Path+from unittest import mock++ROOT = Path(__file__).resolve().parents[2]+sys.path.insert(0, str(ROOT / 'frontend-qt'))++from nspb_qt.win import toolchain # noqa: E402+++def ascii_only(path: str) -> bool:+ return path.encode('ascii', 'ignore').decode() == path+++class AsciiTempDir(unittest.TestCase):+ def test_an_ascii_temp_is_used_as_it_is(self):+ with mock.patch.object(tempfile, 'gettempdir', return_value='/tmp'):+ with toolchain.ascii_temp_dir('probe-') as d:+ self.assertTrue(str(d).startswith('/tmp/'), d)+ self.assertTrue(ascii_only(str(d)))++ def test_a_non_ascii_temp_is_skipped_when_an_ascii_one_exists(self):+ """The reported case: TEMP is C:\\Users\\<中文名>\\… and PUBLIC is available."""+ with mock.patch.object(tempfile, 'gettempdir', return_value='/tmp/中文名'), \+ mock.patch.object(toolchain.os, 'name', 'nt'), \+ mock.patch.dict(os.environ, {'PUBLIC': '/tmp'}):+ with toolchain.ascii_temp_dir('probe-') as d:+ self.assertTrue(ascii_only(str(d)), f'{d} is not ASCII')+ self.assertNotIn('中文', str(d))++ def test_it_still_yields_a_directory_when_nothing_is_ascii(self):+ """No ASCII option: a directory is still created, so the tool can fail on its own terms."""+ with mock.patch.object(tempfile, 'gettempdir', return_value='/tmp/中文名'), \+ mock.patch.object(toolchain.os, 'name', 'darwin'):+ with toolchain.ascii_temp_dir('probe-') as d:+ self.assertTrue(os.path.isdir(d), d)+++if __name__ == '__main__':+ unittest.main()