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
feat(win): rename Windows executable to NX2Apple.exe and add self-update
LNPANDY7bda7071b0bd
diff --git a/.github/workflows/build-qt.yml b/.github/workflows/build-qt.ymlindex 72042aa6..aa64f794 100644--- a/.github/workflows/build-qt.yml+++ b/.github/workflows/build-qt.yml@@ -8,8 +8,8 @@# tag so the artifact is always available under Actions, and it becomes a release download only# once the reports from real hardware are clean.#-# - push a tag vX.Y.Z / workflow_dispatch → build, upload as a workflow artifact-name: Build NS Port Builder (Qt, Windows testing)+# - push a tag vX.Y.Z / workflow_dispatch → build, upload as a workflow artifact and attach to the release+name: Build NX2Apple (Qt, Windows)on:push:@@ -87,6 +87,25 @@ jobs:engine-tree/dm/gfx/tools/spirv_cross_bin/glslangValidator.exe --versionrm -rf glslang.zip bin+ - name: Version from the tag+ if: startsWith(github.ref, 'refs/tags/v')+ shell: bash+ env:+ TAG: ${{ github.ref_name }}+ run: |+ set -euo pipefail+ src=$(sed -n "s/^APP_VERSION = '\(.*\)'/\1/p" frontend-qt/nspb_qt/app_update.py)+ v="${TAG#v}"+ if [[ "$v" =~ ^(.+)-rc([1-9][0-9]*)$ ]]; then+ base="${BASH_REMATCH[1]}"+ else+ base="$v"+ fi+ if [ "$base" != "$src" ]; then+ echo "::error::tag says $base but APP_VERSION says $src: bump the source first"+ exit 1+ fi+- name: Buildworking-directory: frontend-qtshell: bash@@ -101,12 +120,13 @@ jobs:# place). Collect only the modules this app imports, plus the platform plugin# directory a windowed build would otherwise miss.pyinstaller --noconfirm --clean --windowed \- --name "NS Port Builder" \+ --name "NX2Apple" \--icon "nspb_qt/assets/app_icon.ico" \--collect-submodules PySide6.QtCore \--collect-submodules PySide6.QtGui \--collect-submodules PySide6.QtWidgets \--collect-submodules nspb_qt \+ --hidden-import nspb_qt.app_update \--hidden-import nspb_qt.win.toolchain \--hidden-import nspb_qt.win.fetch \--hidden-import nspb_qt.win.sdk_fetch \@@ -174,19 +194,19 @@ jobs:# so they go.cd frontend-qt/distfor drop in Qt6Pdf Qt6Quick Qt6QuickWidgets Qt6Qml Qt6QmlModels Qt6QmlWorkerScript Qt6VirtualKeyboard; do- rm -f "NS Port Builder/$drop.dll" 2>/dev/null || true+ rm -f "NX2Apple/$drop.dll" 2>/dev/null || truedone- du -sh "NS Port Builder" 2>/dev/null || true+ du -sh "NX2Apple" 2>/dev/null || true- name: Packageshell: bashrun: |cd frontend-qt/dist- cp -r ../wheels "NS Port Builder/wheels"+ cp -r ../wheels "NX2Apple/wheels"# The engine tree goes inside the app folder: the launcher finds it at# <exe_dir>/engine (and also at <exe_dir>/../engine) and skips the repo/sync route entirely.- cp -r ../../engine-tree "NS Port Builder/engine"- powershell -Command "Compress-Archive -Path 'NS Port Builder' -DestinationPath '../NX2Apple-windows-x64.zip'"+ cp -r ../../engine-tree "NX2Apple/engine"+ powershell -Command "Compress-Archive -Path 'NX2Apple' -DestinationPath '../NX2Apple-windows-x64.zip'"- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2with:diff --git a/frontend-qt/README.md b/frontend-qt/README.mdindex 65f8c731..f41d7d9a 100644--- a/frontend-qt/README.md+++ b/frontend-qt/README.md@@ -1,4 +1,4 @@-# NS Port Builder — Qt front end (Windows and macOS)+# NX2Apple — Qt front end (Windows and macOS)The SwiftUI app in `../frontend/` is the macOS-native one. This is the **cross-platform**counterpart: same job, same strings, built with PySide6 so Windows users get a native window.@@ -68,8 +68,10 @@ the bundle's `fonts` folder (`build-qt.yml`). If the file is missing the systemSDK symlinks were materialized by hand. The current unmodified frontend is not yet verified endto end; other games and longer-term performance remain unverified. 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.+- Self-update (`nspb_qt/app_update.py`): checks `releases/latest` for `NX2Apple-windows-x64.zip`,+ verifies the SHA-256 digest when present, unpacks and swaps the bundle in place via a detached+ updater script after the running process exits. Repository download and update buttons also exist+ (`Download repository`, `Check for updates`), logging what git is doing.- No per-stage progress bar, no cancel-with-cleanup (cancel terminates the child).## Layoutdiff --git a/frontend-qt/nspb_qt/app_update.py b/frontend-qt/nspb_qt/app_update.pynew file mode 100644index 00000000..01c23706--- /dev/null+++ b/frontend-qt/nspb_qt/app_update.py@@ -0,0 +1,336 @@+"""Self-update for the Windows Qt launcher: release check, zip verification, staging, and relaunch.++Mirrors the rules of `frontend/Sources/NXCore/AppUpdate.swift` so both desktop launchers+compare versions, match release assets, and verify SHA-256 digests identically.+"""+from __future__ import annotations++from dataclasses import dataclass+import hashlib+import json+import os+from pathlib import Path, PurePosixPath+import re+import shutil+import subprocess+import sys+import tempfile+import urllib.error+import urllib.request+import zipfile++#: Bump together with each release tag and `AppUpdateStore.appVersion` in Swift.+APP_VERSION = '1.2.2'++LATEST_RELEASE_URL = 'https://api.github.com/repos/LNPANDY/NX2Apple/releases/latest'+RELEASES_PAGE_URL = 'https://github.com/LNPANDY/NX2Apple/releases/latest'++#: Accepted Windows release zip names, newest first.+ASSET_NAMES = (+ 'NX2Apple-windows-x64.zip',+ 'NS-Port-Builder-qt-windows-x64.zip',+)++#: Accepted executable names inside the unpacked Windows bundle, newest first.+EXE_NAMES = (+ 'NX2Apple.exe',+ 'NS Port Builder.exe',+)+++@dataclass(frozen=True)+class Release:+ tag: str+ url: str+ digest: str | None = None+ notes: str = ''+ html_url: str = RELEASES_PAGE_URL+++@dataclass(frozen=True)+class CheckResult:+ kind: str # 'unreachable' | 'up_to_date' | 'found' | 'no_asset'+ release: Release | None = None+ tag: str = ''+++@dataclass(frozen=True)+class StagedUpdate:+ release: Release+ app_dir: Path+ exe_name: str+ staging_root: Path+++class StageError(Exception):+ """Raised when downloading, verifying, or unpacking an update fails.++ `key` is the localization key in `frontend/l10n/*.json` taking the release tag.+ """++ def __init__(self, key: str) -> None:+ super().__init__(key)+ self.key = key+++def _parse_version(s: str) -> tuple[list[int], int | None]:+ v = s.strip().lstrip('vV')+ rc: int | None = None+ m = re.match(r'^(.+?)-rc([1-9]\d*)$', v, re.I)+ if m:+ v, rc = m.group(1), int(m.group(2))+ nums: list[int] = []+ for part in v.split('.'):+ digits = ''.join(ch for ch in part if ch.isdigit())+ nums.append(int(digits) if digits else 0)+ return nums, rc+++def is_newer(tag: str, current: str) -> bool:+ """True when `tag` ('v1.2.2') is a newer version than `current` ('1.2.0' or '1.2.2-rc3')."""+ if not tag or not current:+ return False+ a_nums, a_rc = _parse_version(tag)+ b_nums, b_rc = _parse_version(current)+ length = max(len(a_nums), len(b_nums))+ for i in range(length):+ x = a_nums[i] if i < len(a_nums) else 0+ y = b_nums[i] if i < len(b_nums) else 0+ if x != y:+ return x > y+ if a_rc is None and b_rc is not None:+ return True+ if a_rc is not None and b_rc is not None:+ return a_rc > b_rc+ return False+++def release_from_json(obj: dict) -> Release | None:+ """Extract the Windows release asset and its SHA-256 digest from a GitHub release object."""+ if not isinstance(obj, dict) or obj.get('draft') or obj.get('prerelease'):+ return None+ tag = str(obj.get('tag_name') or '').strip()+ assets = obj.get('assets')+ if not tag or not isinstance(assets, list):+ return None+ html_url = str(obj.get('html_url') or RELEASES_PAGE_URL).strip() or RELEASES_PAGE_URL+ notes = str(obj.get('body') or '')+ for wanted in ASSET_NAMES:+ for a in assets:+ if isinstance(a, dict) and a.get('name') == wanted:+ u = a.get('browser_download_url')+ if isinstance(u, str) and u.strip():+ digest = a.get('digest')+ return Release(+ tag=tag,+ url=u.strip(),+ digest=digest.strip() if isinstance(digest, str) and digest.strip() else None,+ notes=notes,+ html_url=html_url,+ )+ return None+++def check_release(data: bytes | str | None, current: str = APP_VERSION) -> CheckResult:+ """Compare GitHub's `releases/latest` response against `current`."""+ if not data:+ return CheckResult('unreachable')+ try:+ text = data.decode('utf-8', errors='replace') if isinstance(data, (bytes, bytearray)) else str(data)+ obj = json.loads(text)+ except (ValueError, TypeError):+ return CheckResult('up_to_date')+ if not isinstance(obj, dict) or obj.get('draft') or obj.get('prerelease'):+ return CheckResult('up_to_date')+ tag = str(obj.get('tag_name') or '').strip()+ if not is_newer(tag, current):+ return CheckResult('up_to_date')+ rel = release_from_json(obj)+ if rel is None:+ return CheckResult('no_asset', tag=tag)+ return CheckResult('found', release=rel, tag=tag)+++def fetch_latest_json(url: str = LATEST_RELEASE_URL, timeout: float = 15.0) -> bytes | None:+ """Fetch the latest release metadata from GitHub."""+ req = urllib.request.Request(+ url,+ headers={+ 'Accept': 'application/vnd.github+json',+ 'User-Agent': f'NX2Apple/{APP_VERSION}',+ },+ )+ try:+ with urllib.request.urlopen(req, timeout=timeout) as resp:+ return resp.read()+ except (urllib.error.URLError, OSError, ValueError):+ return None+++def sha256_file(path: Path) -> str | None:+ """Return the lowercase hex SHA-256 of `path`, or None on I/O error."""+ h = hashlib.sha256()+ try:+ with open(path, 'rb') as f:+ while True:+ chunk = f.read(1 << 20)+ if not chunk:+ break+ h.update(chunk)+ return h.hexdigest().lower()+ except OSError:+ return None+++def check_digest(path: Path, expected: str | None) -> str:+ """Compare `path` against `expected` ('sha256:<hex>'). Returns 'match' | 'mismatch' | 'missing'."""+ if not expected or not expected.lower().startswith('sha256:'):+ return 'missing'+ want = expected[len('sha256:'):].strip().lower()+ if not want:+ return 'missing'+ if len(want) != 64 or any(c not in '0123456789abcdef' for c in want):+ return 'mismatch'+ have = sha256_file(path)+ if have is None:+ return 'mismatch'+ return 'match' if have == want else 'mismatch'+++def fresh_staging_root(base_temp: Path | None = None) -> Path:+ """Return an empty staging directory for unpacking an update."""+ root = (base_temp or Path(tempfile.gettempdir())) / 'nx2apple-update'+ shutil.rmtree(root, ignore_errors=True)+ root.mkdir(parents=True, exist_ok=True)+ return root+++def _safe_extract_zip(zip_path: Path, dest_dir: Path) -> None:+ """Extract `zip_path` into `dest_dir`, rejecting any path traversal entries."""+ dest_resolved = dest_dir.resolve()+ with zipfile.ZipFile(zip_path, 'r') as zf:+ for info in zf.infolist():+ norm = PurePosixPath(info.filename.replace('\\', '/'))+ if norm.is_absolute() or '..' in norm.parts:+ raise zipfile.BadZipFile(f'unsafe zip entry: {info.filename}')+ target = (dest_resolved / Path(*norm.parts)).resolve()+ if target != dest_resolved and dest_resolved not in target.parents:+ raise zipfile.BadZipFile(f'escaped zip entry: {info.filename}')+ zf.extractall(dest_resolved)+++def _find_bundled_app_dir(unpacked_dir: Path) -> tuple[Path, str] | None:+ """Locate the unpacked PyInstaller app directory containing `NX2Apple.exe` and `_internal/`."""+ candidates = [unpacked_dir]+ try:+ candidates.extend( sorted(p for p in unpacked_dir.iterdir() if p.is_dir()) )+ except OSError:+ return None+ for cand in candidates:+ if not (cand / '_internal').is_dir():+ continue+ for exe_name in EXE_NAMES:+ if (cand / exe_name).is_file():+ return cand, exe_name+ return None+++def stage_zip(+ zip_path: Path,+ release: Release,+ staging_root: Path,+ require_digest: bool = False,+) -> StagedUpdate:+ """Verify `zip_path`, unpack it inside `staging_root`, and validate the bundle layout."""+ verdict = check_digest(zip_path, release.digest)+ if verdict == 'mismatch':+ zip_path.unlink(missing_ok=True)+ raise StageError('app.digestMismatch')+ if verdict == 'missing' and require_digest:+ zip_path.unlink(missing_ok=True)+ raise StageError('app.noDigest')++ unpacked = staging_root / 'unpacked'+ shutil.rmtree(unpacked, ignore_errors=True)+ unpacked.mkdir(parents=True, exist_ok=True)+ try:+ _safe_extract_zip(zip_path, unpacked)+ except (zipfile.BadZipFile, OSError) as exc:+ zip_path.unlink(missing_ok=True)+ shutil.rmtree(unpacked, ignore_errors=True)+ raise StageError('app.unpackFail') from exc+ zip_path.unlink(missing_ok=True)++ found = _find_bundled_app_dir(unpacked)+ if found is None:+ shutil.rmtree(unpacked, ignore_errors=True)+ raise StageError('app.notOurApp')+ app_dir, exe_name = found+ return StagedUpdate(release=release, app_dir=app_dir, exe_name=exe_name, staging_root=staging_root)+++#: Pure-ASCII PowerShell script that waits for the running process to exit, copies the staged+#: update into place with robocopy (retrying locked files), removes a legacy exe name when+#: transitioning from `NS Port Builder.exe` to `NX2Apple.exe`, and relaunches the new executable.+WINDOWS_RELAUNCH_PS1 = (+ "$pidToWait = [int]$env:NX_PID; "+ "for ($i = 0; $i -lt 150; $i++) { "+ "if (-not (Get-Process -Id $pidToWait -ErrorAction SilentlyContinue)) { break }; "+ "Start-Sleep -Milliseconds 200 "+ "}; "+ "Start-Sleep -Milliseconds 400; "+ "& robocopy $env:NX_STAGED $env:NX_TARGET /E /IS /IT /IM /NFL /NDL /NJH /NJS /R:10 /W:1 | Out-Null; "+ "$newExe = Join-Path $env:NX_TARGET $env:NX_NEW_EXE; "+ "if (($env:NX_OLD_EXE -ne $env:NX_NEW_EXE) -and (Test-Path -LiteralPath $newExe)) { "+ "$oldExe = Join-Path $env:NX_TARGET $env:NX_OLD_EXE; "+ "Remove-Item -LiteralPath $oldExe -Force -ErrorAction SilentlyContinue "+ "}; "+ "Remove-Item Env:_MEIPASS,Env:_MEIPASS2,Env:PYTHONHOME,Env:PYTHONPATH,Env:QT_PLUGIN_PATH,Env:QML2_IMPORT_PATH "+ "-ErrorAction SilentlyContinue; "+ "$launchExe = if (Test-Path -LiteralPath $newExe) { $newExe } else { Join-Path $env:NX_TARGET $env:NX_OLD_EXE }; "+ "if (Test-Path -LiteralPath $launchExe) { "+ "Start-Process -FilePath $launchExe -WorkingDirectory $env:NX_TARGET "+ "}; "+ "if ($env:NX_STAGE_ROOT -and (Test-Path -LiteralPath $env:NX_STAGE_ROOT)) { "+ "Remove-Item -LiteralPath $env:NX_STAGE_ROOT -Recurse -Force -ErrorAction SilentlyContinue "+ "}"+)+++def relaunch_windows_update(+ staged: StagedUpdate,+ current_exe: Path | None = None,+ pid: int | None = None,+ popen=subprocess.Popen,+) -> bool:+ """Spawn a detached background process on Windows to swap `staged` in after `pid` exits."""+ exe_path = (current_exe or Path(sys.executable)).resolve()+ target_dir = exe_path.parent+ env = os.environ.copy()+ for k in ('_MEIPASS', '_MEIPASS2', 'PYTHONHOME', 'PYTHONPATH', 'QT_PLUGIN_PATH', 'QML2_IMPORT_PATH'):+ env.pop(k, None)+ env['NX_PID'] = str(os.getpid() if pid is None else pid)+ env['NX_STAGED'] = str(staged.app_dir)+ env['NX_TARGET'] = str(target_dir)+ env['NX_OLD_EXE'] = exe_path.name+ env['NX_NEW_EXE'] = staged.exe_name+ env['NX_STAGE_ROOT'] = str(staged.staging_root)++ kwargs: dict = {+ 'stdin': subprocess.DEVNULL,+ 'stdout': subprocess.DEVNULL,+ 'stderr': subprocess.DEVNULL,+ 'close_fds': True,+ 'env': env,+ }+ if os.name == 'nt':+ flags = getattr(subprocess, 'CREATE_NO_WINDOW', 0x08000000) | getattr(subprocess, 'DETACHED_PROCESS', 0x00000008)+ kwargs['creationflags'] = flags+ try:+ popen(+ ['powershell', '-NoProfile', '-NonInteractive', '-WindowStyle', 'Hidden', '-Command', WINDOWS_RELAUNCH_PS1],+ **kwargs,+ )+ return True+ except OSError:+ return Falsediff --git a/frontend-qt/nspb_qt/engine.py b/frontend-qt/nspb_qt/engine.pyindex cb11fac5..1dd87c98 100644--- a/frontend-qt/nspb_qt/engine.py+++ b/frontend-qt/nspb_qt/engine.py@@ -92,7 +92,7 @@ def bundled_engine() -> str:Empty string when it is not there or does not look like an engine tree.Also resolves when imported from an external Python (the build's venv) inside a PyInstaller- on-dir layout (`<root>/NS Port Builder/_internal/nspb_qt/engine.py`), where `sys.frozen` is+ on-dir layout (`<root>/NX2Apple/_internal/nspb_qt/engine.py`), where `sys.frozen` isFalse in the child interpreter."""bases: list[Path] = []diff --git a/frontend-qt/nspb_qt/model.py b/frontend-qt/nspb_qt/model.pyindex 4399fe02..a4f5d868 100644--- a/frontend-qt/nspb_qt/model.py+++ b/frontend-qt/nspb_qt/model.py@@ -15,6 +15,7 @@ from pathlib import Pathfrom PySide6.QtCore import QSettings, Q_ARG, QMetaObject, QObject, Qt, QThread, Signal, Slot+from . import app_updatefrom . import build_failure as bffrom . import enginefrom . import input_staging@@ -80,6 +81,7 @@ class Model(QObject):runningChanged = Signal(bool)finished = Signal(bool, str) # ok, noteappUpdateFound = Signal(str, str) # tag, url+ appRelaunching = Signal()libraryChanged = Signal()#: Set by the window: asks for a folder (QFileDialog lives in the UI layer) and returns the@@ -125,6 +127,10 @@ class Model(QObject):self.repo_busy = Falseself.repo_behind: int | None = Noneself.repo_status = ''+ self.app_update: app_update.Release | None = None+ self.app_update_busy = False+ self.app_update_status = ''+ self._app_update_checked = Falseself._proc: subprocess.Popen | None = Noneself._thread: threading.Thread | None = Noneself._line_buf = ''@@ -514,6 +520,9 @@ class Model(QObject):self.depsChanged.emit()except RuntimeError:pass+ if getattr(sys, 'frozen', False) and not self._app_update_checked:+ self._app_update_checked = True+ self.check_app_update(silent=True)@propertydef all_deps_ok(self) -> bool:@@ -855,6 +864,135 @@ class Model(QObject):threading.Thread(target=work, daemon=True).start()+ # ---- app self-update (Windows release zip check + in-place swap) ----++ def check_app_update(self, silent: bool = False) -> None:+ """Check GitHub's latest release for a newer Windows build."""+ if self.app_update_busy:+ return+ self.app_update_busy = True+ if not silent:+ self.app_update_status = self.t('app.checking')+ try:+ self.repoChanged.emit()+ except RuntimeError:+ pass++ def work() -> None:+ try:+ data = app_update.fetch_latest_json()+ outcome = app_update.check_release(data, current=app_update.APP_VERSION)+ if outcome.kind == 'found' and outcome.release is not None:+ rel = outcome.release+ self.app_update = rel+ if getattr(sys, 'frozen', False):+ self.app_update_status = self.t('app.found', rel.tag)+ else:+ self.app_update_status = self.t('app.devBuild', rel.tag)+ self.log(self.app_update_status + '\n')+ try:+ self.appUpdateFound.emit(rel.tag, rel.html_url)+ except RuntimeError:+ pass+ elif outcome.kind == 'no_asset':+ if not silent:+ self.app_update_status = self.t('app.noAsset', outcome.tag)+ elif outcome.kind == 'unreachable':+ if not silent:+ self.app_update_status = self.t('app.netFail')+ else:+ if not silent:+ self.app_update_status = self.t('app.upToDate')+ finally:+ self.app_update_busy = False+ try:+ self.repoChanged.emit()+ except RuntimeError:+ pass++ threading.Thread(target=work, daemon=True).start()++ def perform_app_update(self) -> None:+ """Download, verify, unpack, and relaunch the staged Windows release."""+ rel = self.app_update+ if rel is None or self.app_update_busy:+ return+ if self.running:+ self.app_update_status = self.t('app.waitForBuild')+ try:+ self.repoChanged.emit()+ except RuntimeError:+ pass+ return+ if not (pu.IS_WIN and getattr(sys, 'frozen', False)):+ self.app_update_status = self.t('app.devBuild', rel.tag)+ try:+ self.repoChanged.emit()+ except RuntimeError:+ pass+ return++ self.app_update_busy = True+ self.app_update_status = self.t('app.downloading', rel.tag)+ self.log(self.app_update_status + '\n')+ try:+ self.repoChanged.emit()+ except RuntimeError:+ pass++ def work() -> None:+ try:+ from .win import fetch as wf+ root = app_update.fresh_staging_root()+ zip_path = root / 'update.zip'+ try:+ wf.download(+ rel.url,+ zip_path,+ progress=lambda d, tot: self.log(+ f' {d // 1048576} MB'+ + (f' / {tot // 1048576} MB ({d * 100 // tot}%)' if tot else '')+ + '\n'+ ),+ )+ except Exception as exc:+ self.log(f'{exc}\n')+ self.app_update_status = self.t('app.stageNetFail', rel.tag)+ return++ try:+ staged = app_update.stage_zip(zip_path, rel, root, require_digest=False)+ except app_update.StageError as err:+ if err.key == 'app.digestMismatch':+ self.app_update_status = self.t('app.digestMismatch', rel.tag)+ elif err.key == 'app.noDigest':+ self.app_update_status = self.t('app.noDigest', rel.tag)+ elif err.key == 'app.notOurApp':+ self.app_update_status = self.t('app.notOurApp', rel.tag)+ else:+ self.app_update_status = self.t('app.unpackFail', rel.tag)+ self.log(self.app_update_status + '\n')+ return++ self.app_update_status = self.t('app.relaunching', rel.tag)+ self.log(self.app_update_status + '\n')+ if app_update.relaunch_windows_update(staged):+ try:+ self.appRelaunching.emit()+ except RuntimeError:+ pass+ else:+ self.app_update_status = self.t('app.relaunchFail', rel.tag)+ self.log(self.app_update_status + '\n')+ finally:+ self.app_update_busy = False+ try:+ self.repoChanged.emit()+ except RuntimeError:+ pass++ threading.Thread(target=work, daemon=True).start()+# ---- installing what is missing ----def install_dep(self, dep: Dep) -> None:diff --git a/frontend-qt/nspb_qt/ui.py b/frontend-qt/nspb_qt/ui.pyindex 4bb484c3..ef81f095 100644--- a/frontend-qt/nspb_qt/ui.py+++ b/frontend-qt/nspb_qt/ui.py@@ -2,6 +2,7 @@from __future__ import annotationsimport os+import sysfrom pathlib import Pathfrom PySide6.QtCore import QPoint, QTimer, QUrl, Qt@@ -33,9 +34,8 @@ from . import inputsfrom . import library as libfrom . import platform_util as pufrom . import style+from .app_update import APP_VERSIONfrom .build_notes import TEXT, TITLE, stale_reason--APP_VERSION = '1.2.0'from .i18n import Langfrom .model import Dep, DepState, Modelfrom .sheets import CheatsDialog, DeleteGameDialog, FreeSpaceDialog, OnboardingDialog@@ -214,6 +214,7 @@ class MainWindow(QMainWindow):self.m.logAppended.connect(self._append_log)self.m.finished.connect(self._on_finished)self.m.appUpdateFound.connect(self._on_app_update)+ self.m.appRelaunching.connect(QApplication.quit)self.m.libraryChanged.connect(self._refresh_library)if self.m.log_path:@@ -1670,13 +1671,22 @@ class MainWindow(QMainWindow):r_ver = QWidget()rv_lay = QHBoxLayout(r_ver)rv_lay.setContentsMargins(18, 12, 18, 12)- rv_lay.addWidget(_dot(style.GREEN))+ self.ver_dot = _dot(style.GREEN)+ rv_lay.addWidget(self.ver_dot)+ vcol = QVBoxLayout()+ vcol.setSpacing(2)self.ver_title_lbl = QLabel(self.m.t('app.version', APP_VERSION))self.ver_title_lbl.setObjectName('rowTitle')- rv_lay.addWidget(self.ver_title_lbl, 1)self.ver_status_lbl = QLabel(self.m.t('app.upToDate'))self.ver_status_lbl.setObjectName('muted')- rv_lay.addWidget(self.ver_status_lbl)+ self.ver_status_lbl.setWordWrap(True)+ vcol.addWidget(self.ver_title_lbl)+ vcol.addWidget(self.ver_status_lbl)+ rv_lay.addLayout(vcol, 1)+ self.ver_action_btn = QPushButton(self.m.t('repo.update'))+ self.ver_action_btn.setFixedWidth(184)+ self.ver_action_btn.clicked.connect(self._on_version_action_clicked)+ rv_lay.addWidget(self.ver_action_btn)grp.add_row(r_ver)return grp@@ -1870,7 +1880,17 @@ class MainWindow(QMainWindow):self.setup_row_note.setText(t('settings.setupNote'))self.run_onboarding_btn.setText(t('settings.setupBtn'))self.ver_title_lbl.setText(t('app.version', APP_VERSION))- self.ver_status_lbl.setText(t('app.upToDate'))+ self.ver_status_lbl.setText(self.m.app_update_status or t('app.upToDate'))+ if self.m.app_update is not None:+ _set_dot(self.ver_dot, style.ORANGE)+ self.ver_action_btn.setText(t('app.updateBtn', self.m.app_update.tag))+ self.update_btn.setText(t('app.updateBtn', self.m.app_update.tag))+ self.update_btn.setEnabled(not self.m.app_update_busy and not self.m.running)+ self.update_btn.show()+ else:+ _set_dot(self.ver_dot, style.GREEN)+ self.ver_action_btn.setText(t('repo.update'))+ self.ver_action_btn.setEnabled(not self.m.app_update_busy and not self.m.running)self._refresh_engine_banner()self._refresh_repo()@@ -2288,6 +2308,21 @@ class MainWindow(QMainWindow):else:self.m.override.cancel()+ def _trigger_app_update(self, fallback_url: str = '') -> None:+ rel = self.m.app_update+ if rel is not None and pu.IS_WIN and getattr(sys, 'frozen', False):+ self.m.perform_app_update()+ return+ url = fallback_url or (rel.html_url if rel is not None else '')+ if url:+ QDesktopServices.openUrl(QUrl(url))++ def _on_version_action_clicked(self) -> None:+ if self.m.app_update is not None:+ self._trigger_app_update(self.m.app_update.html_url)+ else:+ self.m.check_app_update(silent=False)+def _on_app_update(self, tag: str, url: str) -> None:self.update_btn.setText(self.m.t('app.updateBtn', tag))self.update_btn.setToolTip(url)@@ -2295,7 +2330,7 @@ class MainWindow(QMainWindow):self.update_btn.clicked.disconnect()except (RuntimeError, TypeError):pass- self.update_btn.clicked.connect(lambda: QDesktopServices.openUrl(QUrl(url)))+ self.update_btn.clicked.connect(lambda: self._trigger_app_update(url))self.update_btn.show()# ================================================================ File Pickers & Build Triggerdiff --git a/frontend-qt/tests/test_app_update.py b/frontend-qt/tests/test_app_update.pynew file mode 100644index 00000000..891f7383--- /dev/null+++ b/frontend-qt/tests/test_app_update.py@@ -0,0 +1,168 @@+"""Tests for Windows executable naming (`NX2Apple.exe`) and self-update (`nspb_qt.app_update`)."""+from __future__ import annotations++import hashlib+import json+import os+from pathlib import Path+import re+import shutil+import sys+import tempfile+import unittest+import zipfile++sys.path.insert(0, str(Path(__file__).resolve().parents[1]))++from nspb_qt import app_update # noqa: E402++ROOT = Path(__file__).resolve().parents[2]+++class AppUpdateTests(unittest.TestCase):+ def setUp(self) -> None:+ self.tmp = Path(tempfile.mkdtemp(prefix='qt-app-update-'))+ self.addCleanup(shutil.rmtree, self.tmp, True)++ def test_qt_app_version_matches_swift_app_update_store(self) -> None:+ swift_store = (ROOT / 'frontend' / 'Sources' / 'NXModel' / 'AppUpdateStore.swift').read_text(encoding='utf-8')+ m = re.search(r'static let appVersion = "([^"]+)"', swift_store)+ self.assertIsNotNone(m, 'AppUpdateStore.appVersion not found')+ self.assertEqual(app_update.APP_VERSION, m.group(1))++ def test_build_qt_workflow_builds_nx2apple_exe_not_ns_port_builder(self) -> None:+ wf = (ROOT / '.github' / 'workflows' / 'build-qt.yml').read_text(encoding='utf-8')+ self.assertIn('--name "NX2Apple"', wf)+ self.assertNotIn('--name "NS Port Builder"', wf)+ self.assertIn("Compress-Archive -Path 'NX2Apple' -DestinationPath '../NX2Apple-windows-x64.zip'", wf)++ def test_is_newer_compares_numeric_segments_and_release_candidates(self) -> None:+ self.assertTrue(app_update.is_newer('v1.2.2', '1.2.0'))+ self.assertTrue(app_update.is_newer('v1.2.10', '1.2.2'))+ self.assertFalse(app_update.is_newer('v1.2.2', '1.2.2'))+ self.assertFalse(app_update.is_newer('v1.2.1', '1.2.2'))+ # A final release is newer than a release candidate of the same version+ self.assertTrue(app_update.is_newer('v1.2.2', '1.2.2-rc4'))+ self.assertTrue(app_update.is_newer('v1.2.2-rc4', '1.2.2-rc3'))+ self.assertFalse(app_update.is_newer('v1.2.2-rc3', '1.2.2'))++ def test_check_release_matches_nx2apple_windows_zip_and_digest(self) -> None:+ payload = {+ 'tag_name': 'v1.3.0',+ 'draft': False,+ 'prerelease': False,+ 'html_url': 'https://github.com/LNPANDY/NX2Apple/releases/tag/v1.3.0',+ 'body': 'Release notes',+ 'assets': [+ {+ 'name': 'NX2Apple-macOS-arm64.zip',+ 'browser_download_url': 'https://example.com/mac.zip',+ },+ {+ 'name': 'NX2Apple-windows-x64.zip',+ 'browser_download_url': 'https://example.com/NX2Apple-windows-x64.zip',+ 'digest': 'sha256:' + 'a' * 64,+ },+ ],+ }+ res = app_update.check_release(json.dumps(payload).encode('utf-8'), current='1.2.2')+ self.assertEqual(res.kind, 'found')+ assert res.release is not None+ self.assertEqual(res.release.tag, 'v1.3.0')+ self.assertEqual(res.release.url, 'https://example.com/NX2Apple-windows-x64.zip')+ self.assertEqual(res.release.digest, 'sha256:' + 'a' * 64)++ def test_check_release_reports_no_asset_when_windows_zip_missing(self) -> None:+ payload = {+ 'tag_name': 'v1.3.0',+ 'draft': False,+ 'prerelease': False,+ 'assets': [+ {+ 'name': 'NX2Apple-macOS-arm64.zip',+ 'browser_download_url': 'https://example.com/mac.zip',+ },+ ],+ }+ res = app_update.check_release(json.dumps(payload), current='1.2.2')+ self.assertEqual(res.kind, 'no_asset')+ self.assertEqual(res.tag, 'v1.3.0')++ def test_stage_zip_verifies_sha256_and_locates_nx2apple_exe(self) -> None:+ zip_path = self.tmp / 'NX2Apple-windows-x64.zip'+ with zipfile.ZipFile(zip_path, 'w') as zf:+ zf.writestr('NX2Apple/NX2Apple.exe', b'MZ-fake-exe')+ zf.writestr('NX2Apple/_internal/python312.dll', b'fake-dll')+ digest = 'sha256:' + hashlib.sha256(zip_path.read_bytes()).hexdigest()+ rel = app_update.Release(tag='v1.3.0', url='https://example.com/win.zip', digest=digest)+ staging = app_update.fresh_staging_root(self.tmp)+ staged = app_update.stage_zip(zip_path, rel, staging, require_digest=True)+ self.assertEqual(staged.exe_name, 'NX2Apple.exe')+ self.assertTrue((staged.app_dir / 'NX2Apple.exe').is_file())+ self.assertTrue((staged.app_dir / '_internal' / 'python312.dll').is_file())++ def test_stage_zip_rejects_mismatched_digest(self) -> None:+ zip_path = self.tmp / 'bad.zip'+ with zipfile.ZipFile(zip_path, 'w') as zf:+ zf.writestr('NX2Apple/NX2Apple.exe', b'MZ')+ zf.writestr('NX2Apple/_internal/x', b'1')+ rel = app_update.Release(tag='v1.3.0', url='https://example.com/win.zip', digest='sha256:' + '0' * 64)+ staging = app_update.fresh_staging_root(self.tmp)+ with self.assertRaises(app_update.StageError) as ctx:+ app_update.stage_zip(zip_path, rel, staging)+ self.assertEqual(ctx.exception.key, 'app.digestMismatch')+ self.assertFalse(zip_path.exists())++ def test_stage_zip_rejects_zip_slip_traversal(self) -> None:+ zip_path = self.tmp / 'slip.zip'+ with zipfile.ZipFile(zip_path, 'w') as zf:+ zf.writestr('../escaped.exe', b'MZ')+ rel = app_update.Release(tag='v1.3.0', url='https://example.com/win.zip', digest=None)+ staging = app_update.fresh_staging_root(self.tmp)+ with self.assertRaises(app_update.StageError) as ctx:+ app_update.stage_zip(zip_path, rel, staging)+ self.assertEqual(ctx.exception.key, 'app.unpackFail')++ def test_relaunch_windows_update_passes_unicode_env_and_strips_meipass(self) -> None:+ staged_dir = self.tmp / 'staged' / 'NX2Apple'+ staged_dir.mkdir(parents=True)+ install_dir = self.tmp / 'C_Games_中文目录' / 'NS Port Builder'+ install_dir.mkdir(parents=True)+ old_exe = install_dir / 'NS Port Builder.exe'+ old_exe.write_text('old')++ staged = app_update.StagedUpdate(+ release=app_update.Release(tag='v1.3.0', url='https://example.com/win.zip'),+ app_dir=staged_dir,+ exe_name='NX2Apple.exe',+ staging_root=self.tmp / 'staged',+ )+ captured: list[tuple[list[str], dict]] = []++ def fake_popen(cmd, **kwargs):+ captured.append((cmd, kwargs))++ old_env = os.environ.get('_MEIPASS2')+ os.environ['_MEIPASS2'] = '/tmp/stale-meipass'+ try:+ ok = app_update.relaunch_windows_update(staged, current_exe=old_exe, pid=4321, popen=fake_popen)+ finally:+ if old_env is None:+ os.environ.pop('_MEIPASS2', None)+ else:+ os.environ['_MEIPASS2'] = old_env++ self.assertTrue(ok)+ self.assertEqual(len(captured), 1)+ cmd, kwargs = captured[0]+ self.assertEqual(cmd[0], 'powershell')+ env = kwargs['env']+ self.assertNotIn('_MEIPASS2', env)+ self.assertEqual(env['NX_PID'], '4321')+ self.assertEqual(env['NX_OLD_EXE'], 'NS Port Builder.exe')+ self.assertEqual(env['NX_NEW_EXE'], 'NX2Apple.exe')+ self.assertEqual(env['NX_TARGET'], str(old_exe.resolve().parent))+++if __name__ == '__main__':+ unittest.main()diff --git a/frontend-qt/tests/test_engine_layout.py b/frontend-qt/tests/test_engine_layout.pyindex eaa4ea8c..5189ed22 100644--- a/frontend-qt/tests/test_engine_layout.py+++ b/frontend-qt/tests/test_engine_layout.py@@ -85,7 +85,7 @@ class BundledEngine(unittest.TestCase):self.addCleanup(shutil.rmtree, self.r, True)self.app = self.r / 'app'self.app.mkdir()- self.exe = self.app / 'NS Port Builder.exe'+ self.exe = self.app / 'NX2Apple.exe'self.exe.write_text('x')self.set_frozen(True)