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 four things the second handheld report found
LNPANDY4b12f2cb7b16
diff --git a/frontend-qt/nspb_qt/localization.py b/frontend-qt/nspb_qt/localization.pyindex 7d49640b..bcdeaddc 100644--- a/frontend-qt/nspb_qt/localization.py+++ b/frontend-qt/nspb_qt/localization.py@@ -37,6 +37,7 @@ TABLE: dict[str, tuple[str, str]] = {'app.netFail': ('网络失败(GitHub 不通?稍后再试)', 'Network failed (GitHub unreachable? try again later)'),'repo.destBusy': ('%@ 已存在且不是本项目——换个位置,或点「选择仓库…」', '%@ already exists and is not this project — use another place, or Choose repository…'),'repo.firstHint': ('第一次用?点「下载仓库」自动获取项目(约一分钟,需要网络)', 'First time here? Download repository fetches the project for you (about a minute, needs network)'),+ 'repo.update': ('检查并更新', 'Check and update'),'repo.check': ('检查更新', 'Check for updates'),'repo.checking': ('正在检查更新…', 'Checking for updates…'),'repo.upToDate': ('已是最新版本', 'Up to date'),@@ -92,6 +93,7 @@ TABLE: dict[str, tuple[str, str]] = {'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…'),+ 'dep.checkFailed': ('依赖检测失败——详情见日志(不是「已就绪」)', 'Dependency check failed — see the log (this is not a pass)'),'dep.allReady': ('全部就绪', 'All ready'),'dep.missing': ('缺 %d 项', '%d missing'),'dep.llvm': ('LLVM-MinGW(交叉编译)', 'LLVM-MinGW (cross compiler)'),@@ -137,6 +139,8 @@ TABLE: dict[str, tuple[str, str]] = {'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.phase.download': ('下载', 'Download'),+ 'dep.phase.unpack': ('解压', 'Unpack'),'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 07963624..a6346f34 100644--- a/frontend-qt/nspb_qt/model.py+++ b/frontend-qt/nspb_qt/model.py@@ -2,6 +2,7 @@from __future__ import annotationsimport os+import reimport shutilimport subprocessimport sys@@ -263,7 +264,17 @@ class Model(QObject):@propertydef all_deps_ok(self) -> bool:- return self.deps_checked and all(d.ok for d in self.deps)+ """Every required row passed — and an empty list is not "all good".++ `all([])` is True, so when the dependency check threw and left `self.deps = []` (the+ handler below), the panel reported "All ready" while nothing had been checked at all.+ The handheld report was exactly that: ".NET and LLVM installed, then it says every+ dependency is fine — I have not even installed Metal." A check that produced no rows has+ proved nothing, so it is not a pass.+ """+ if not self.deps_checked or not self.deps:+ return False+ return all(d.ok for d in self.deps)# ---- Windows toolchain rows@@ -450,42 +461,21 @@ class Model(QObject):threading.Thread(target=work, daemon=True).start()- def pull_repo(self) -> None:- """Fast-forward the checkout to origin/main. The build's own files live outside the- repository, so this never disturbs a previous build."""- git = self.git_binary()- if not git or not self.repo_ok or not self.repo_is_git:- return- self.repo_busy = True- self.repo_status = self.t('repo.pulling')- self.repoChanged.emit()- self.log(self.t('repo.pulling') + '\n')-- def work() -> None:- out = ''- try:- r = subprocess.run([git, '-C', self.repo_path, 'pull', '--ff-only', 'origin', 'main'],- capture_output=True, text=True, env=pu.child_env(),- **pu.no_window_kwargs())- out = (r.stdout or '') + (r.stderr or '')- self.repo_status = self.t('repo.pulled') if r.returncode == 0 else self.t('repo.pullFail')- except OSError as e:- out, self.repo_status = str(e), self.t('repo.pullFail')- self.repo_busy = False- if out:- self.log(out + '\n')- self.repoChanged.emit()+ def update_repo(self) -> None:+ """Fetch, and fast-forward when there is anything to fast-forward.- threading.Thread(target=work, daemon=True).start()+ One button, because "check" and "pull" were never two decisions: the only reason to press+ the first was to find out whether to press the second, and a user who has just been told+ "12 new commits" is going to press it. Reported as "why does Check for updates not just+ pull — the extra Pull button is pointless", and it is right.- def check_repo_updates(self) -> None:- """How far behind origin/main the checkout is (0 = current).+ The order still matters and is unchanged: `fetch` first (that is what learns about+ origin/main), then `rev-list` to see the gap, then `pull --ff-only` only when the gap is+ non-zero. `--ff-only` never merges and never touches local commits, so a checkout with+ changes of its own is refused rather than rewritten.- `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's own progress is streamed: over a slow link the fetch alone takes tens of seconds and+ the button used to go grey in silence."""git = self.git_binary()if not git or not self.repo_ok or not self.repo_is_git:@@ -494,46 +484,73 @@ class Model(QObject):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+ def stream(args: list[str], what: str) -> bool:+ """Run git, logging its output as it arrives (progress uses \\r)."""+ self.log(f'$ git -C {self.repo_path} {" ".join(args)}\n')try:- p = subprocess.Popen([git, '-C', self.repo_path, 'fetch', '--progress',- 'origin', 'main'],+ p = subprocess.Popen([git, '-C', self.repo_path] + args,stdout=subprocess.PIPE, stderr=subprocess.STDOUT,- text=True, errors='replace', env=pu.child_env(),- **pu.no_window_kwargs())+ text=True, errors='replace', encoding='utf-8',+ env=pu.child_env(), **pu.no_window_kwargs())assert p.stdout is not None+ # git rewrites one progress line per percent per phase ("Counting objects: 7%",+ # "Receiving objects: 62%", …). Logging each of those turned one fetch into+ # hundreds of lines (reported). Keep the phase changes, the final 100%, and every+ # fifth percent; drop the rest.+ seen: dict[str, int] = {}for line in p.stdout:- # git rewrites a progress line with \r; the log is line-based- if s := line.replace('\r', '\n').strip():+ for s in line.replace('\r', '\n').split('\n'):+ s = s.strip()+ if not s:+ continue+ m = re.match(r'^(remote: )?([A-Za-z][\w ]*?):\s+(\d+)%', s)+ if m:+ phase, pct = m.group(2), int(m.group(3))+ last = seen.get(phase)+ if pct != 100 and last is not None and pct < last + 5:+ continue+ seen[phase] = pctself.log(s + '\n')p.wait()- ok = p.returncode == 0+ return p.returncode == 0except 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()- return+ return False++ def work() -> None:try:- r = subprocess.run([git, '-C', self.repo_path, 'rev-list', '--count',- 'HEAD..origin/main'],- capture_output=True, text=True, env=pu.child_env(),- **pu.no_window_kwargs())- if r.returncode == 0:- self.repo_behind = int(r.stdout.strip() or 0)- self.repo_status = (self.t('repo.upToDate') if self.repo_behind == 0- else self.t('repo.behind', self.repo_behind))- else:+ if not stream(['fetch', '--progress', 'origin', 'main'], 'fetch'):self.repo_status = self.t('repo.netFail')- except (OSError, ValueError):- self.repo_status = self.t('repo.netFail')- self.log(self.repo_status + '\n')- self.repo_busy = False- self.repoChanged.emit()+ return+ try:+ r = subprocess.run([git, '-C', self.repo_path, 'rev-list', '--count',+ 'HEAD..origin/main'],+ capture_output=True, text=True, env=pu.child_env(),+ **pu.no_window_kwargs())+ behind = int(r.stdout.strip() or 0) if r.returncode == 0 else -1+ except (OSError, ValueError):+ behind = -1+ if behind < 0:+ self.repo_status = self.t('repo.netFail')+ return+ self.repo_behind = behind+ if behind == 0:+ self.repo_status = self.t('repo.upToDate')+ self.log(self.repo_status + '\n')+ return+ self.repo_status = self.t('repo.pulling')+ self.repoChanged.emit()+ self.log(self.t('repo.pulling') + '\n')+ if stream(['pull', '--ff-only', 'origin', 'main'], 'pull'):+ self.repo_behind = 0+ self.repo_status = self.t('repo.pulled')+ else:+ self.repo_status = self.t('repo.pullFail')+ self.log(self.repo_status + '\n')+ finally:+ self.repo_busy = False+ self.repoChanged.emit()threading.Thread(target=work, daemon=True).start()@@ -601,6 +618,9 @@ class Model(QObject):dep.installing = Trueself.depsChanged.emit()+ def progress_logger(label: str):+ return self._progress_logger(label)+def work() -> None:ok = Falsetry:@@ -610,18 +630,16 @@ class Model(QObject):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'))+ progress=progress_logger(self.t('dep.phase.download')),+ unpack_progress=progress_logger(self.t('dep.phase.unpack')))self.log(self.t('dep.dotnet.done', str(path)) + '\n')ok = Trueelif what == 'llvm':self.log(self.t('dep.llvm.downloading') + '\n')path = wf.install_llvm(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'))+ progress=progress_logger(self.t('dep.phase.download')),+ unpack_progress=progress_logger(self.t('dep.phase.unpack')))self.log(self.t('dep.llvm.done', str(path)) + '\n')ok = Trueelif what == 'ios_sdk':@@ -644,6 +662,26 @@ class Model(QObject):threading.Thread(target=work, daemon=True).start()+ def _progress_logger(self, label: str):+ """A progress callback that logs at 5% steps, not on every chunk.++ The download calls back once per MiB, so a 287 MB SDK produced ~280 lines at 1% each and+ buried everything else in the log (reported). Each call gets its own counter, so the+ download and the unpack that follows both start at 0% and each produce about ten lines.+ """+ seen = {'pct': -5}++ def report(done: int, total: int) -> None:+ if not total:+ return+ pct = done * 100 // total+ if pct < seen['pct'] + 5 and pct != 100:+ return+ seen['pct'] = pct+ self.log(f' {label} {pct}% ({done // 1048576} / {total // 1048576} MB)\n')++ return report+def _make_venv(self, base: str) -> bool:"""Create or reuse the app's venv and install the build packages into it."""vpy = pu.venv_python()diff --git a/frontend-qt/nspb_qt/ui.py b/frontend-qt/nspb_qt/ui.pyindex aa8da03d..c1f4b9e8 100644--- a/frontend-qt/nspb_qt/ui.py+++ b/frontend-qt/nspb_qt/ui.py@@ -141,16 +141,15 @@ class MainWindow(QMainWindow):self.choose_btn.clicked.connect(self._choose_repo)row.addWidget(self.choose_btn)lay.addLayout(row)- # A machine without a clone gets Download; a clone gets Check/Pull. Same as the macOS app.+ # A machine without a clone gets Download; a clone gets one update button (fetch, then+ # fast-forward if there is anything to take — see Model.update_repo).actions = QHBoxLayout()actions.setSpacing(8)self.download_btn = QPushButton(self.m.t('repo.download'))self.download_btn.clicked.connect(lambda: self.m.clone_repo())- self.check_btn = QPushButton(self.m.t('repo.check'))- self.check_btn.clicked.connect(self.m.check_repo_updates)- self.pull_btn = QPushButton(self.m.t('repo.pull'))- self.pull_btn.clicked.connect(self.m.pull_repo)- for b in (self.download_btn, self.check_btn, self.pull_btn):+ self.update_btn = QPushButton(self.m.t('repo.update'))+ self.update_btn.clicked.connect(self.m.update_repo)+ for b in (self.download_btn, self.update_btn):actions.addWidget(b)actions.addStretch(1)lay.addLayout(actions)@@ -293,12 +292,11 @@ class MainWindow(QMainWindow):else:self.repo_dot.setStyleSheet(f'color: {RED};')self.repo_status.setText(self.m.repo_status or self.m.t('repo.firstHint'))- # Download when there is no usable checkout; Check/Pull when there is a git one.+ # Download when there is no usable checkout; one update button when there is a git one.self.download_btn.setVisible(not self.m.repo_ok)- self.check_btn.setVisible(self.m.repo_ok and self.m.repo_is_git)- self.pull_btn.setVisible(self.m.repo_ok and self.m.repo_is_git)+ self.update_btn.setVisible(self.m.repo_ok and self.m.repo_is_git)busy = self.m.repo_busy or self.m.running- for b in (self.download_btn, self.check_btn, self.pull_btn, self.choose_btn):+ for b in (self.download_btn, self.update_btn, self.choose_btn):b.setEnabled(not busy)if getattr(self.m, 'log_path', None):self.log_path_label.setText(self.m.t('log.at', str(self.m.log_path)))@@ -373,7 +371,12 @@ class MainWindow(QMainWindow):h.addWidget(hint)self.deps_container.addWidget(row)if self.m.deps_checked:- if self.m.all_deps_ok:+ if not self.m.deps:+ # The check produced no rows at all, which means it failed — never report that as+ # "all ready" (see Model.all_deps_ok) or as "0 missing".+ self.deps_summary.setText('⚠ ' + self.m.t('dep.checkFailed'))+ self.deps_summary.setStyleSheet(f'color: {RED}; font-weight: 600;')+ elif self.m.all_deps_ok:self.deps_summary.setText('● ' + self.m.t('dep.allReady'))self.deps_summary.setStyleSheet(f'color: {GREEN}; font-weight: 600;')else:diff --git a/frontend-qt/nspb_qt/win/fetch.py b/frontend-qt/nspb_qt/win/fetch.pyindex 2b9ef3f5..32d630c1 100644--- a/frontend-qt/nspb_qt/win/fetch.py+++ b/frontend-qt/nspb_qt/win/fetch.py@@ -196,7 +196,8 @@ def _strip_root(member: str) -> str: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:+ progress: Callable[[int, int], None] | None = None,+ unpack_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@@ -223,9 +224,13 @@ def install_llvm(arch: str | None = None, dest: Path | None = None,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+ # Unpacking 1 GiB takes long enough to look stuck (reported: "can unpacking also+ # have progress"). Count uncompressed bytes against the archive's own total, which+ # is the only measure that advances evenly — a file count stalls on the big files.+ members = [i for i in z.infolist() if not i.is_dir()]+ grand = sum(i.file_size for i in members) or 1+ done = 0+ for info in members:rel = _strip_root(info.filename)if not rel:continue@@ -233,6 +238,9 @@ def install_llvm(arch: str | None = None, dest: Path | None = None,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)+ done += info.file_size+ if unpack_progress:+ unpack_progress(done, grand)# the zip stores no Unix modes: mark everything in bin/ executableif out.parent.name == 'bin':try:@@ -269,7 +277,8 @@ def install_llvm(arch: str | None = None, dest: Path | None = None,def install_dotnet(dest: Path | None = None,log: Callable[[str], None] | None = None,- progress: Callable[[int, int], None] | None = None) -> Path:+ progress: Callable[[int, int], None] | None = None,+ unpack_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@@ -301,9 +310,10 @@ def install_dotnet(dest: Path | None = None,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+ members = [i for i in z.infolist() if not i.is_dir()]+ grand = sum(i.file_size for i in members) or 1+ done = 0+ for info in members: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())):@@ -311,6 +321,9 @@ def install_dotnet(dest: Path | None = None,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)+ done += info.file_size+ if unpack_progress:+ unpack_progress(done, grand)except zipfile.BadZipFile as e:shutil.rmtree(staging, ignore_errors=True)raise DownloadError(f'{zpath.name} is not a valid zip: {e}') from ediff --git a/frontend-qt/nspb_qt/win/sdk_fetch.py b/frontend-qt/nspb_qt/win/sdk_fetch.pyindex f24996d5..ac6cf72b 100644--- a/frontend-qt/nspb_qt/win/sdk_fetch.py+++ b/frontend-qt/nspb_qt/win/sdk_fetch.py@@ -36,6 +36,30 @@ class SdkError(Exception):"""A user-facing failure: the message says what to do next, not just what broke."""+def rmtree(path: Path) -> None:+ """Remove a tree, clearing the read-only bits git leaves on Windows.++ `shutil.rmtree` fails on a read-only file and `ignore_errors=True` then leaves the directory+ half-removed. Git marks its pack files read-only, so the stale clone survived every cleanup+ and the next `git clone` refused the non-empty destination. Retried once after chmodding the+ survivors, and only then given up on.+ """+ import stat+ if not path.exists():+ return++ def clear(func, p, _exc): # onerror: drop the read-only bit and retry+ try:+ os.chmod(p, stat.S_IWRITE | stat.S_IREAD)+ func(p)+ except OSError:+ pass++ shutil.rmtree(path, onerror=clear)+ if path.exists(): # a file locked by another process (an indexer)+ shutil.rmtree(path, ignore_errors=True)++# ---------------------------------------------------------------- git routedef clone_sdk(version: str = tc.SDK_PINNED, dest: Path | None = None,@@ -59,17 +83,20 @@ def clone_sdk(version: str = tc.SDK_PINNED, dest: Path | None = None,dest.mkdir(parents=True, exist_ok=True)target = dest / versionif tc.is_sdk_dir(target):- log(f'SKD already present: {target}')+ log(f'SDK already present: {target}')return targetwork = dest / f'.clone-{version}'- shutil.rmtree(work, ignore_errors=True)+ rmtree(work)def run(args: list[str], what: str, repo: str = tc.SDK_REPO) -> None:log(f'$ git {" ".join(args)}')try:+ # encoding='utf-8': git always writes UTF-8, while a Chinese Windows console decodes+ # with GBK, which turned `C:\Users\QC-北\…` into `C:\Users\QC-鍖梊…` in the log — and+ # a bug report full of mojibake is a bug report nobody can act on.p = subprocess.Popen([git] + args, cwd=str(dest), stdout=subprocess.PIPE,stderr=subprocess.STDOUT, text=True, errors='replace',- bufsize=1, **tc.no_window())+ encoding='utf-8', bufsize=1, **tc.no_window())except OSError as e:raise SdkError(f'cannot start git: {e}') from eassert p.stdout is not None@@ -90,7 +117,12 @@ def clone_sdk(version: str = tc.SDK_PINNED, dest: Path | 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)+ # Every attempt starts from nothing. This has to be a real removal: git marks its pack+ # files read-only, and `shutil.rmtree(ignore_errors=True)` silently leaves those behind on+ # Windows. The next clone then dies with "destination path already exists and is not an+ # empty directory" on all three sources, which is what the report showed — the retries+ # were never given a chance.+ rmtree(work)try:run(clone_args + [repo, str(work)], 'clone', repo)last = None@@ -98,6 +130,7 @@ def clone_sdk(version: str = tc.SDK_PINNED, dest: Path | None = None,except SdkError as e:last = eif last is not None:+ rmtree(work)raise last# narrow the working tree to the one SDK before checking anything outtry:diff --git a/frontend-qt/nspb_qt/win/toolchain.py b/frontend-qt/nspb_qt/win/toolchain.pyindex 26585e8a..86706a1f 100644--- a/frontend-qt/nspb_qt/win/toolchain.py+++ b/frontend-qt/nspb_qt/win/toolchain.py@@ -387,8 +387,14 @@ def llvm_version(clang: Path) -> str: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()+ # `r.stdout` is None when capture came back empty — `text=True` with no output, or a+ # redirected stdout on Windows. `re.search` then raises TypeError, which used to take the+ # whole dependency check down (the report: "dependency check failed: TypeError: expected+ # string or bytes-like object, got 'NoneType'"). stderr is worth reading too: a clang that+ # writes its banner there still tells us its version.+ text = (r.stdout or '') + (r.stderr or '')+ m = re.search(r'clang version (\d+\.\d+\.\d+)', text)+ return m.group(1) if m else (text.splitlines() or [''])[0].strip()# ---------------------------------------------------------------- .NET SDKdiff --git a/frontend-qt/tests/test_win.py b/frontend-qt/tests/test_win.pyindex e958dae4..f474b1fe 100644--- a/frontend-qt/tests/test_win.py+++ b/frontend-qt/tests/test_win.py@@ -931,6 +931,153 @@ class FetchTest(unittest.TestCase):self.assertEqual(msg.count('github.com/a/b'), 1 + len(tc.GITHUB_MIRRORS))+class ToolchainProbeRobustnessTest(unittest.TestCase):+ """Probes must survive a tool that prints nothing on stdout.++ The second handheld report's log ended with eight repetitions of+ `dependency check failed: TypeError: expected string or bytes-like object, got 'NoneType'`+ from `llvm_version` — `subprocess.run(text=True)` leaves `stdout` as None when the child+ writes nothing there, and `re.search` on None raises. The check died, `deps` became empty,+ and `all([])` is True, so the panel said every dependency was ready while nothing at all had+ been verified (the report: "I have not even installed Metal").+ """++ def test_llvm_version_survives_empty_stdout(self) -> None:+ fake = subprocess.CompletedProcess(['clang'], 0, None, '')+ with mock.patch('subprocess.run', return_value=fake):+ self.assertEqual(tc.llvm_version(Path('clang.exe')), '')++ def test_llvm_version_reads_stderr_too(self) -> None:+ """A clang that prints its banner on stderr still tells us its version."""+ fake = subprocess.CompletedProcess(['clang'], 0, None,+ 'clang version 23.1.4\nTarget: x86_64-pc-windows')+ with mock.patch('subprocess.run', return_value=fake):+ self.assertEqual(tc.llvm_version(Path('clang.exe')), '23.1.4')++ def test_llvm_version_still_reads_stdout(self) -> None:+ fake = subprocess.CompletedProcess(['clang'], 0,+ 'clang version 23.1.4 (https://llvm.org)', '')+ with mock.patch('subprocess.run', return_value=fake):+ self.assertEqual(tc.llvm_version(Path('clang.exe')), '23.1.4')++ def test_metal_version_survives_empty_output(self) -> None:+ fake = subprocess.CompletedProcess(['metal'], 0, None, None)+ with mock.patch.object(tc, 'metal_tool', return_value=Path('metal.exe')), \+ mock.patch('subprocess.run', return_value=fake):+ self.assertEqual(tc.metal_version(), '')++ def _all_deps_ok(self, deps, checked):+ """Evaluate Model.all_deps_ok without needing PySide6 installed."""+ try:+ from nspb_qt.model import Dep, DepState, Model+ except ModuleNotFoundError as e: # pragma: no cover - a bare interpreter+ if 'PySide6' in str(e):+ self.skipTest('PySide6 is not installed')+ raise++ class Fake(Model):+ def __init__(self):+ self.deps = deps+ self.deps_checked = checked++ return Fake().all_deps_ok++ def test_empty_dep_list_is_not_all_ready(self) -> None:+ """`all([])` is True — a check that produced no rows has proved nothing."""+ self.assertFalse(self._all_deps_ok([], True))++ def test_unchecked_is_not_all_ready(self) -> None:+ try:+ from nspb_qt.model import Dep, DepState+ except ModuleNotFoundError as e:+ if 'PySide6' in str(e):+ self.skipTest('PySide6 is not installed')+ raise+ good = [Dep('a', 'k', 'h', DepState.OK, '')]+ self.assertFalse(self._all_deps_ok(good, False))+ self.assertTrue(self._all_deps_ok(good, True))+ self.assertFalse(self._all_deps_ok([Dep('a', 'k', 'h', DepState.MISSING, '')], True))+++class SdkCleanupTest(unittest.TestCase):+ """A retry must start from an empty directory, even with git's read-only pack files.++ The report's log showed the same clone failing three times — direct, then two mirrors — all+ with "destination path already exists and is not an empty directory". `shutil.rmtree(...,+ ignore_errors=True)` cannot delete the read-only files git writes on Windows and silently+ left them behind, so every retry hit the previous attempt's leftovers.+ """++ def test_rmtree_clears_readonly_files(self) -> None:+ from nspb_qt.win.sdk_fetch import rmtree+ with tempfile.TemporaryDirectory() as td:+ root = Path(td) / 'clone'+ (root / 'objects' / 'pack').mkdir(parents=True)+ pack = root / 'objects' / 'pack' / 'x.pack'+ pack.write_bytes(b'read only')+ pack.chmod(0o444) # what git does on Windows+ rmtree(root)+ self.assertFalse(root.exists())++ def test_rmtree_is_quiet_when_absent(self) -> None:+ from nspb_qt.win.sdk_fetch import rmtree+ with tempfile.TemporaryDirectory() as td:+ rmtree(Path(td) / 'never-existed') # must not raise+++class ProgressStepTest(unittest.TestCase):+ """Downloads and unpacks log at 5% steps, not on every chunk.++ The report: a 287 MB SDK download printed a line per MiB (about 280 lines), burying the rest+ of the log. Unpacking had no progress at all ("can unpacking also have progress").+ """++ def test_the_model_filters_progress_to_five_percent_steps(self) -> None:+ """The 5%-step filter lives in Model._install_win's progress logger.++ `fetch.download` must keep calling back on every chunk (it has no idea what a useful+ logging granularity is, and the callback also drives any future progress bar), so the+ filtering is tested where it belongs. The report: a 287 MB SDK printed ~280 lines.+ """+ try:+ from nspb_qt.model import Model+ except ModuleNotFoundError as e:+ if 'PySide6' in str(e):+ self.skipTest('PySide6 is not installed')+ raise++ logged: list[str] = []+ m = Model.__new__(Model) # no QObject init: only log() is used+ m.log = logged.append+ report = Model._progress_logger(m, 'Download')++ for mb in range(0, 288): # one callback per MiB, like the real download+ report(mb * 1048576, 287 * 1048576)+ # 0,5,…,95,100 — at most 21 lines for 288 callbacks+ self.assertLessEqual(len(logged), 21)+ self.assertGreaterEqual(len(logged), 10)+ self.assertTrue(any('100%' in s for s in logged))+ self.assertTrue(all('Download' in s for s in logged))++ def test_unpack_progress_reaches_100(self) -> None:+ 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' * 1000)+ zf.writestr('sdk/a.dll', b'x' * 5000)+ seen: list[tuple[int, int]] = []+ with mock.patch.object(fetch, 'download', return_value=z):+ fetch.install_dotnet(dest=root, log=lambda s: None,+ unpack_progress=lambda d, t: seen.append((d, t)))+ self.assertTrue(seen)+ done, total = seen[-1]+ self.assertEqual(done, total) # the last report is the whole archive+ self.assertGreaterEqual(total, 6000)++class DotnetTest(unittest.TestCase):"""The .NET row and its in-app installer.diff --git a/frontend/Sources/NSPortBuilder/Localization.swift b/frontend/Sources/NSPortBuilder/Localization.swiftindex 30b5f7a7..f4098764 100644--- a/frontend/Sources/NSPortBuilder/Localization.swift+++ b/frontend/Sources/NSPortBuilder/Localization.swift@@ -75,6 +75,7 @@ enum L10n {"%@ already exists and is not this project — use another place, or Choose repository…"),"repo.firstHint": ("第一次用?点「下载仓库」自动获取项目(约一分钟,需要网络)","First time here? Download repository fetches the project for you (about a minute, needs network)"),+ "repo.update": ("检查并更新", "Check and update"),"repo.check": ("检查更新", "Check for updates"),"repo.checking": ("正在检查更新…", "Checking for updates…"),"repo.upToDate": ("已是最新版本", "Up to date"),@@ -149,6 +150,7 @@ enum L10n {"dep.title": ("设备依赖", "Device dependencies"),"dep.checking": ("检测中…", "Checking…"),+ "dep.checkFailed": ("依赖检测失败——详情见日志(不是「已就绪」)", "Dependency check failed — see the log (this is not a pass)"),"dep.allReady": ("全部就绪", "All ready"),"dep.missing": ("缺 %d 项", "%d missing"),"dep.llvm": ("LLVM-MinGW(交叉编译)", "LLVM-MinGW (cross compiler)"),@@ -203,6 +205,8 @@ enum L10n {"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.phase.download": ("下载", "Download"),+ "dep.phase.unpack": ("解压", "Unpack"),"dep.python": ("Python + 包", "Python + packages"),"dep.python.hint": ("lz4 capstone fonttools backports.zstd", "lz4 capstone fonttools backports.zstd"),"dep.python.missing": ("%@ 缺包", "%@ is missing packages"),