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
Build-failure hints: rows that name the reason and offer Build anyway for three stops
LNPANDY3526c2f14482
diff --git a/frontend-qt/nspb_qt/build_failure.py b/frontend-qt/nspb_qt/build_failure.pynew file mode 100644index 00000000..984f7c2d--- /dev/null+++ b/frontend-qt/nspb_qt/build_failure.py@@ -0,0 +1,112 @@+"""The NSP script's early stops, turned into hints (the SwiftUI app's BuildFailure.swift).++The script prints a `[RED]` line and exits 1 for each stop (a BuildError), and the window used to show the+last line of the log. The classifier reads the whole log tail: for a damaged NSP the last line is only+"nx_extract exit code 3" and the message is above it. No Qt in here, so the tests run anywhere.++TABLE is the same table as BuildFailure.swift's (a test compares the two). frontend/Tests/Fixtures/+build_failures.json holds the script's real message for every row, and a test checks that each fragment is+still in the vendored script, so a sync that rewords a message fails there.+"""+from __future__ import annotations++import re+from dataclasses import dataclass++ROSETTA = 'rosetta'+TRANSLATOR = 'translator'+IOS_SDK = 'iosSDK'+CLT_SELECTED = 'cltSelected'+OTHER_METAL = 'otherMetal'+SHADER_REGRESSION = 'shaderRegression'+DAMAGED_NSP = 'damagedNSP'+A32_PROGRAM = 'a32Program'+UNKNOWN = 'unknown'++# (id, kind, regular expression searched in the log)+TABLE: list[tuple[str, str, str]] = [+ ('rosetta.intel', ROSETTA, r'is an Intel one running under Rosetta'),+ ('translator.run', TRANSLATOR, r'the shader translator does not run'),+ ('translator.start', TRANSLATOR, r'the shader translator does not start'),+ ('ios.sdk', IOS_SDK, r'the iOS SDK is not installed'),+ ('clt.selected', CLT_SELECTED, r'the selected developer folder is the Command Line Tools'),+ ('metal.other', OTHER_METAL, r'Metal compiler is not the one the shaders were tested with'),+ ('shaders.regression', SHADER_REGRESSION, r'a change to the translation chain broke them'),+ ('nsp.damaged', DAMAGED_NSP, r"files fail the NCA's hash check"),+ ('arm32.program', A32_PROGRAM, r'is a 32-bit ARM program'),+]++# The script's override for a stop, offered as "Build anyway". The others cannot be built around.+OVERRIDE_FLAGS = {+ OTHER_METAL: '--allow-other-metal',+ SHADER_REGRESSION: '--allow-shader-regressions',+ DAMAGED_NSP: '--allow-damaged',+}++KINDS = [ROSETTA, TRANSLATOR, IOS_SDK, CLT_SELECTED, OTHER_METAL, SHADER_REGRESSION, DAMAGED_NSP, A32_PROGRAM]++_A32_NAME = re.compile(r'^(?:\[RED\] )?(.+?) \([0-9A-Fa-f]{16}\) is a 32-bit ARM program', re.M)+++@dataclass(frozen=True)+class Failure:+ kind: str+ game: str | None = None # a32Program: the game, when the message names it++ @property+ def what_key(self) -> str:+ return f'fail.{self.kind}.what'++ @property+ def next_key(self) -> str:+ return f'fail.{self.kind}.next'++ @property+ def flag(self) -> str | None:+ return OVERRIDE_FLAGS.get(self.kind)+++def classify(log: str) -> Failure:+ """UNKNOWN when no row matches: the caller then keeps showing the last line of the log."""+ for _id, kind, pattern in TABLE:+ if re.search(pattern, log):+ m = _A32_NAME.search(log) if kind == A32_PROGRAM else None+ name = m.group(1).strip() if m else None+ return Failure(kind, None if name in (None, '', '?') else name)+ return Failure(UNKNOWN)+++def arguments(args: list[str], flag: str | None) -> list[str]:+ """The build arguments with the one-off override added: exactly one `--allow-*`, or none."""+ rest = [a for a in args if not a.startswith('--allow-')]+ return rest + [flag] if flag and flag.startswith('--allow-') else rest+++class OverrideState:+ """"Build anyway": nothing is armed until the confirmation, and the arm serves one build only."""++ def __init__(self) -> None:+ self.confirming: Failure | None = None+ self._armed: str | None = None++ def request(self, failure: Failure | None) -> bool:+ """Ask for confirmation (the window shows the dialog). False for a stop that has no override."""+ if failure is None or failure.flag is None:+ return False+ self.confirming = failure+ return True++ def cancel(self) -> None:+ self.confirming = None++ def confirm(self) -> bool:+ if self.confirming is None:+ return False+ self._armed = self.confirming.flag+ self.confirming = None+ return True++ def take(self) -> str | None:+ """The flag the next build runs with, once."""+ flag, self._armed = self._armed, None+ return flagdiff --git a/frontend-qt/nspb_qt/localization.py b/frontend-qt/nspb_qt/localization.pyindex 016139e5..9ab13c38 100644--- a/frontend-qt/nspb_qt/localization.py+++ b/frontend-qt/nspb_qt/localization.py@@ -12,6 +12,8 @@ TABLE: dict[str, tuple[str, str, str]] = {'onboarding.welcome.note': ('约 15 分钟,即可在 Mac 上原生运行你的 Switch 游戏。', 'Play your Switch games natively on your Mac, in about 15 minutes.', 'Spela dina Switch-spel direkt på din Mac på ungefär 15 minuter.'),'onboarding.platform.title': ('你想在哪里玩?', 'Where do you want to play?', 'Var vill du spela?'),'onboarding.platform.note': ('选择游玩设备,我们会准备所需的工具。', 'Choose where you will play. We will prepare just what you need.', 'Välj var du ska spela. Vi förbereder bara det du behöver.'),+ 'onboarding.nvn.os': ('部分游戏需要 Xcode 27.1,而它需要 macOS 26.6 或更高版本。在这台 Mac 上,使用 NVN 的游戏无法构建,其他游戏不受影响。', 'Some games need Xcode 27.1, which needs macOS 26.6 or later. On this Mac, games that use NVN won’t build, but others will.', 'Some games need Xcode 27.1, which needs macOS 26.6 or later. On this Mac, games that use NVN won’t build, but others will.'),+ 'onboarding.nvn.xcode': ('这个 Xcode 低于 27.1,而使用 NVN 的游戏需要 27.1。如果你的 macOS 支持,请在 App Store 中更新 Xcode。其他游戏用当前版本即可构建。', 'This Xcode is older than 27.1, which games that use NVN need. Update Xcode in the App Store if your macOS allows it. Other games build with this one.', 'This Xcode is older than 27.1, which games that use NVN need. Update Xcode in the App Store if your macOS allows it. Other games build with this one.'),'onboarding.xcode.title': ('准备好你的 Mac。', 'Let’s get your Mac ready.', 'Gör din Mac redo.'),'onboarding.xcode.note': ('Xcode 提供构建游戏所需的 Apple 工具。我们将引导你完成设置。', 'Xcode provides Apple’s tools for building your games. We will guide you through the setup.', 'Xcode tillhandahåller Apples verktyg för att bygga dina spel. Vi guidar dig genom inställningen.'),'onboarding.keys.title': ('添加你的密钥。', 'Bring your own keys.', 'Ange dina nycklar.'),@@ -57,7 +59,7 @@ TABLE: dict[str, tuple[str, str, str]] = {'onboarding.xcode.checking': ('正在检查 Xcode…', 'Checking Xcode…', 'Kontrollerar Xcode …'),'onboarding.xcode.checkingNote': ('正在查找游戏所需的工具。', 'Looking for the tools your games need.', 'Söker efter verktygen som dina spel behöver.'),'onboarding.xcode.missing': ('先获取 Xcode。', 'First, get Xcode.', 'Hämta först Xcode.'),- 'onboarding.xcode.missingNote': ('从 App Store 下载 Xcode。这是设置中最大的下载项目。', 'Download Xcode from the App Store. This is the largest part of setup.', 'Hämta Xcode från App Store. Det är den största delen av inställningen.'),+ 'onboarding.xcode.missingNote': ('从 App Store 下载 Xcode(免费)——这是设置中最大的下载项。下载完成后我们会自动继续。首次打开 Xcode 会提示安装 iOS SDK——让它装完。', 'Download Xcode from the App Store (free) — this is the largest part of setup. We will continue automatically when it is installed. The first launch of Xcode will prompt to install the iOS SDK — let it finish.', 'Hämta Xcode från App Store. Det är den största delen av inställningen.'),'onboarding.xcode.downloading': ('正在等待 Xcode…', 'Waiting for Xcode…', 'Väntar på Xcode …'),'onboarding.xcode.downloadNote': ('请让 App Store 继续下载。Xcode 安装完成后,我们会自动继续。', 'Leave the App Store download running. We will continue automatically when Xcode is installed.', 'Låt nedladdningen i App Store fortsätta. Vi fortsätter automatiskt när Xcode är installerat.'),'onboarding.xcode.needsSetup': ('完成 Xcode 的最后一步。', 'One last step for Xcode.', 'Ett sista steg för Xcode.'),@@ -71,6 +73,7 @@ TABLE: dict[str, tuple[str, str, str]] = {'onboarding.setup.ios': ('iOS 平台', 'iOS platform', 'iOS-plattform'),'onboarding.background.title': ('正在后台准备', 'Preparing in the background', 'Förbereder i bakgrunden'),'onboarding.background.note': ('这些工具将在设置 Xcode 时准备就绪。', 'These tools get ready while you set up Xcode.', 'De här verktygen förbereds medan du ställer in Xcode.'),+ 'onboarding.background.installing': ('正在安装…', 'Installing…', 'Installing…'),'onboarding.background.python': ('Python', 'Python', 'Python'),'onboarding.background.dotnet': ('.NET', '.NET', '.NET'),'onboarding.background.tools': ('构建工具', 'Build tools', 'Byggverktyg'),@@ -98,6 +101,108 @@ TABLE: dict[str, tuple[str, str, str]] = {'onboarding.demo.library': ('游戏库将在此打开。', 'Your library would open here.', 'Ditt spelbibliotek skulle öppnas här.'),'onboarding.demo.note': ('这是预览。未读取任何文件,也未安装任何工具。', 'This is a preview. No files were read and no tools were installed.', 'Det här är en förhandsvisning. Inga filer lästes och inga verktyg installerades.'),'onboarding.demo.resume': ('继续设置', 'Resume setup', 'Fortsätt inställningen'),+ 'console.kind.gamepad': ('游戏手柄', 'Gamepad', 'Gamepad'),+ 'console.kind.fullSize': ('全尺寸手柄', 'Full-size pad', 'Full-size pad'),+ 'console.kind.paired': ('双体手柄', 'Paired controllers', 'Paired controllers'),+ 'console.kind.xbox': ('Xbox 型手柄', 'Xbox-style pad', 'Xbox-style pad'),+ 'console.kind.keyboard': ('键盘', 'Keyboard', 'Keyboard'),+ 'console.batteryPercent': ('%d%%', '%d%%', '%d%%'),+ 'console.batteryLevel': ('电量百分之 %d', 'Battery %d percent', 'Battery %d percent'),+ 'console.batteryCharging': ('电量百分之 %d,正在充电', 'Battery %d percent, charging', 'Battery %d percent, charging'),+ 'console.charging': ('正在充电', 'Charging', 'Charging'),+ 'console.batteryUnknown': ('未报告电量', 'Battery not reported', 'Battery not reported'),+ 'console.identify': ('识别', 'Identify', 'Identify'),+ 'console.identifying': ('正在识别…', 'Identifying…', 'Identifying…'),+ 'console.identifyingName': ('正在识别 %@…', 'Identifying %@…', 'Identifying %@…'),+ 'console.assign': ('分配玩家', 'Assign player', 'Assign player'),+ 'console.disconnect': ('断开连接', 'Disconnect', 'Disconnect'),+ 'console.playerMode': ('玩家模式', 'Player mode', 'Player mode'),+ 'console.mergeAll': ('所有手柄均为玩家 1', 'All controllers are player 1', 'All controllers are player 1'),+ 'console.mergeNote': ('打开后,每个手柄都按玩家 1 输入。关闭时,每个手柄各有自己的玩家。仅对在 Mac 上运行的游戏生效。', 'Every controller sends player 1’s input. When off, each controller is its own player. Applies to games running on this Mac.', 'Every controller sends player 1’s input. When off, each controller is its own player. Applies to games running on this Mac.'),+ 'console.disconnectHint': ('在 macOS 的蓝牙设置中断开这个手柄。', 'Disconnect it in the macOS Bluetooth settings.', 'Disconnect it in the macOS Bluetooth settings.'),+ 'console.promptSetting': ('插入手柄时提示进入主机模式', 'Offer console mode when a controller connects', 'Offer console mode when a controller connects'),+ 'console.promptSettingNote': ('每次启动最多提示一次。', 'At most once each time the launcher starts.', 'At most once each time the launcher starts.'),+ 'console.menuLeave': ('退出主机模式', 'Leave Console Mode', 'Leave Console Mode'),+ 'console.promptNever': ('不再提示', 'Don’t ask again', 'Don’t ask again'),+ 'console.notBuilt': ('尚未构建', 'Not built yet', 'Not built yet'),+ 'console.needsDataBadge': ('需要游戏数据', 'Needs game data', 'Needs game data'),+ 'console.iphoneOnly': ('仅 iPhone 版', 'iPhone only', 'iPhone only'),+ 'console.iphoneOnlyNote': ('这款游戏只构建了 iPhone 版。请在桌面模式的“构建”页面构建 Mac 版,之后就能在这里游玩。', 'This game is built for iPhone only. Build it for Mac on the Builds page in desktop mode, then play it here.', 'This game is built for iPhone only. Build it for Mac on the Builds page in desktop mode, then play it here.'),+ 'console.explanationTitle': ('暂时无法游玩', 'Not ready to play', 'Not ready to play'),+ 'console.connectedNextPlayer': ('%@ 已连接,玩家 %d', '%@ connected, player %d', '%@ connected, player %d'),+ 'console.noFreePlayer': ('四位玩家都已占用。请打开手柄页面调整。', 'All four players are taken. Open Controllers to change them.', 'All four players are taken. Open Controllers to change them.'),+ 'console.controllersRowNote': ('查看已连接的手柄,识别、分配玩家。', 'See connected controllers, identify them and assign players.', 'See connected controllers, identify them and assign players.'),+ 'console.controllersOpen': ('打开…', 'Open…', 'Open…'),+ 'console.promptSelectBefore': ('随时按', 'Press', 'Press'),+ 'console.promptSelectAfter': ('键即可切换。', 'anytime to switch.', 'anytime to switch.'),+ 'console.mergeOff': ('现在每个手柄各是一位玩家。', 'Each controller is now its own player.', 'Each controller is now its own player.'),+ 'console.assignedTo': ('%@ 是玩家 %d', '%@ is player %d', '%@ is player %d'),+ 'console.assignCancelled': ('已取消分配玩家。', 'Player assignment cancelled.', 'Player assignment cancelled.'),+ 'console.assignTimeout': ('没有按键。请重新选择玩家再试一次。', 'No button was pressed. Choose a player to try again.', 'No button was pressed. Choose a player to try again.'),+ 'console.mergeEach': ('每个手柄对应一位玩家', 'Each controller is its own player', 'Each controller is its own player'),+ 'console.mockPress': ('模拟按下按钮', 'Simulate a button press', 'Simulate a button press'),+ 'console.connectedUnassigned': ('%@ 已连接', '%@ connected', '%@ connected'),+ 'console.connected': ('%@ 已连接,玩家 %d', '%@ connected, player %d', '%@ connected, player %d'),+ 'console.disconnected': ('%@ 已断开连接', '%@ disconnected', '%@ disconnected'),+ 'console.demoXbox': ('Xbox 手柄', 'Xbox controller', 'Xbox controller'),+ 'console.demoKeyboard': ('键盘', 'Keyboard', 'Keyboard'),+ 'console.demoPaired': ('双体手柄', 'Paired controllers', 'Paired controllers'),+ 'console.shaders': ('正在编译着色器', 'Compiling shaders', 'Compiling shaders'),+ 'console.shadersProgress': ('正在编译着色器 · %d / %d', 'Compiling shaders · %d of %d', 'Compiling shaders · %d of %d'),+ 'console.openingGame': ('正在打开游戏窗口…', 'Opening game window…', 'Opening game window…'),+ 'console.simulatedShaders': ('此预览中的进度为模拟进度', 'Simulated progress in this preview', 'Simulated progress in this preview'),+ 'console.brand': ('NX2Apple', 'NX2Apple', 'NX2Apple'),+ 'console.entry': ('主机模式', 'Console mode', 'Console mode'),+ 'console.connectionTitle': ('切换到主机模式?', 'Switch to console mode?', 'Switch to console mode?'),+ 'console.connectionNote': ('手柄已连接。在大屏幕上选择并畅玩游戏。', 'A controller is connected. Your games, ready for the big screen.', 'A controller is connected. Your games, ready for the big screen.'),+ 'console.later': ('留在桌面模式', 'Stay on desktop', 'Stay on desktop'),+ 'console.library': ('你的游戏', 'YOUR GAMES', 'YOUR GAMES'),+ 'console.ready': ('可以开始游戏', 'Ready to play', 'Ready to play'),+ 'console.setup': ('在 Mac 上完成设置', 'Set up on your Mac', 'Set up on your Mac'),+ 'console.unavailable': ('需要处理', 'Needs attention', 'Needs attention'),+ 'console.needsBuild': ('先在 Mac 上构建此游戏,然后回来开始游戏。', 'Build this game on your Mac, then come back to play.', 'Build this game on your Mac, then come back to play.'),+ 'console.needsData': ('先在桌面模式中选择游戏数据,然后回来开始游戏。', 'Choose this game’s data in desktop mode, then come back to play.', 'Choose this game’s data in desktop mode, then come back to play.'),+ 'console.broken': ('此游戏需要在桌面模式中处理。', 'This game needs attention in desktop mode.', 'This game needs attention in desktop mode.'),+ 'console.platform.mac': ('Mac', 'Mac', 'Mac'),+ 'console.platform.iphone': ('iPhone', 'iPhone', 'iPhone'),+ 'console.version': ('版本 %@', 'Version %@', 'Version %@'),+ 'console.play': ('开始游戏', 'Play', 'Play'),+ 'console.playHint': ('开始游戏,或了解如何完成设置。', 'Play, or learn how to finish setup.', 'Play, or learn how to finish setup.'),+ 'console.options': ('游戏选项', 'Game options', 'Game options'),+ 'console.controllers': ('手柄', 'Controllers', 'Controllers'),+ 'console.desktop': ('返回桌面', 'Back to desktop', 'Back to desktop'),+ 'console.close': ('返回', 'Back', 'Back'),+ 'console.empty': ('还没有游戏', 'No games yet', 'No games yet'),+ 'console.emptyNote': ('在 Mac 上构建一个游戏。', 'Build one on your Mac.', 'Build one on your Mac.'),+ 'console.starting': ('正在启动 %@…', 'Starting %@…', 'Starting %@…'),+ 'console.startingNote': ('正在准备游戏', 'Getting your game ready', 'Getting your game ready'),+ 'console.noOptions': ('此游戏没有启动选项。', 'This game has no launch options.', 'This game has no launch options.'),+ 'console.adjustHint': ('使用左右方向键调整。', 'Use left or right to adjust.', 'Use left or right to adjust.'),+ 'console.on': ('开启', 'On', 'On'),+ 'console.off': ('关闭', 'Off', 'Off'),+ 'console.noControllers': ('未连接手柄', 'No controllers connected', 'No controllers connected'),+ 'console.player': ('玩家 %d', 'Player %d', 'Player %d'),+ 'console.playerShort': ('P%d', 'P%d', 'P%d'),+ 'console.unassigned': ('未分配', 'Unassigned', 'Unassigned'),+ 'console.pressToAssign': ('按下一个按钮以分配玩家 %d。', 'Press a button to assign player %d.', 'Press a button to assign player %d.'),+ 'console.controllerNote': ('选择玩家,然后按下该玩家手柄上的按钮。', 'Choose a player, then press a button on their controller.', 'Choose a player, then press a button on their controller.'),+ 'console.desktopPreview': ('已返回桌面模式', 'Back on desktop', 'Back on desktop'),+ 'console.desktopPreviewNote': ('预览已结束。游戏库保持不变。', 'Preview complete. Your library stays as it is.', 'Preview complete. Your library stays as it is.'),+ 'console.return': ('返回主机模式', 'Return to console', 'Return to console'),+ 'console.resolution': ('分辨率缩放', 'Resolution scale', 'Resolution scale'),+ 'console.frameRate': ('帧率', 'Frame rate', 'Frame rate'),+ 'console.fps30': ('30 帧/秒', '30 fps', '30 fps'),+ 'console.fps60': ('60 帧/秒', '60 fps', '60 fps'),+ 'console.language': ('游戏语言', 'Game language', 'Game language'),+ 'console.english': ('英语', 'English', 'English'),+ 'console.chinese': ('中文', 'Chinese', 'Chinese'),+ 'console.japanese': ('日语', 'Japanese', 'Japanese'),+ 'console.fullscreen': ('全屏', 'Full screen', 'Full screen'),+ 'console.rumble': ('手柄振动', 'Controller vibration', 'Controller vibration'),+ 'console.demoBroken': ('上次构建未完成。请在 Mac 上重新构建。', 'The last build did not finish. Rebuild it on your Mac.', 'The last build did not finish. Rebuild it on your Mac.'),+ 'console.demoController': ('无线手柄', 'Wireless controller', 'Wireless controller'),+ 'console.demoController2': ('全尺寸手柄', 'Full-size controller', 'Full-size controller'),+ 'console.demoController3': ('USB 手柄', 'USB controller', 'USB controller'),'library.readyIOS': ('可用于 iPhone', 'Ready for iPhone', 'Klar för iPhone'),'library.stopping': ('正在停止…', 'Stopping…', 'Avslutar …'),'build.setup': ('完成设置', 'Finish setup', 'Slutför inställningen'),@@ -121,7 +226,7 @@ TABLE: dict[str, tuple[str, str, str]] = {'dev.noDevices': ('没有与这台 Mac 配对的 iPhone 或 iPad(需要 Xcode)。', 'No iPhone or iPad paired with this Mac (needs Xcode).', 'Ingen iPhone eller iPad är parkopplad med den här Mac-datorn (Xcode krävs).'),'dev.refresh': ('刷新', 'Refresh', 'Uppdatera'),'dev.team': ('签名团队', 'Signing team', 'Signeringsteam'),- 'dev.noTeam': ('Xcode 里没有 Apple ID,也没有开发证书。请在 Xcode → 设置 → 账户中登录。', 'No Apple ID in Xcode and no development certificate. Sign in to Xcode → Settings → Accounts.', 'Det finns inget Apple-ID i Xcode och inget utvecklarcertifikat. Logga in i Xcode → Inställningar → Konton.'),+ 'dev.noTeam': ('Xcode 里没有 Apple ID,也没有开发证书。打开 Xcode → Settings → Apple Accounts(Xcode 菜单没有中文),登录 Apple ID 后选 Personal Team → Download Manual Profiles。证书不会立刻出现——等 30 秒左右再按「重新检测」。如果等了还没有,在 Manage Certificates 里点 + 手动创建一个 Apple Development 证书。', 'No Apple ID in Xcode and no development certificate. Open Xcode → Settings → Apple Accounts (Xcode menus are English-only), sign in with your Apple ID, select Personal Team → Download Manual Profiles. The certificate does not appear immediately — wait ~30 seconds and press Check again. If it still does not appear, click + in Manage Certificates to create an Apple Development certificate manually.', 'Det finns inget Apple-ID i Xcode och inget utvecklarcertifikat. Logga in i Xcode → Inställningar → Konton.'),'dev.teamNoCert': ('这个团队还没有开发证书:第一次安装时 Xcode 会自动创建(Mac 需要联网)。', 'This team has no development certificate yet: Xcode creates it at the first install (the Mac needs to be online).', 'Det här teamet saknar utvecklarcertifikat. Xcode skapar det automatiskt vid första installationen och Mac-datorn måste vara ansluten till internet.'),'dev.personalTeam': ('个人团队', 'Personal team', 'Personligt team'),'dev.note': ('Xcode 会为这台设备签名并直接安装,游戏数据(romfs.img)复制到 App 的“文稿”中,与侧载相同。第一次复制大型游戏需要几分钟。第一次需要在设备上开启开发者模式,并信任开发者(设置 → 通用 → VPN 与设备管理)。', 'Xcode signs the game for this device and installs it there, then copies the game data (romfs.img) into the app’s Documents, as for sideloading. The first copy of a large game takes a few minutes. The first time, turn on Developer Mode on the device and trust the developer (Settings → General → VPN & Device Management).', 'Xcode signerar spelet för den här enheten och installerar det där. Därefter kopieras speldata (romfs.img) till appens Dokument, som vid sidoinläsning. Första kopieringen av ett stort spel tar några minuter. Aktivera utvecklarläge på enheten och lita på utvecklaren första gången (Inställningar → Allmänt → VPN och enhetshantering).'),@@ -167,6 +272,32 @@ TABLE: dict[str, tuple[str, str, str]] = {'dev.signFailed': ('签名失败:%@', 'Signing failed: %@', 'Signeringen misslyckades: %@'),'dev.installFailed': ('安装失败:%@', 'Installing failed: %@', 'Installationen misslyckades: %@'),'dev.noProject': ('没有找到:%@', 'Not found: %@', 'Hittades inte: %@'),+ 'dev.reinstall': ('重装', 'Reinstall', 'Reinstall'),+ 'dev.reinstallStage': ('重装到 %@', 'Reinstalling on %@', 'Reinstalling on %@'),+ 'dev.reinstalled': ('已重新安装到 %@(游戏数据保留)', 'Reinstalled on %@ (the game data is kept)', 'Reinstalled on %@ (the game data is kept)'),+ 'dev.reinstallFailed': ('重装失败:%@(签名已过期时请重新签名并安装)', 'Reinstalling failed: %@ (if the signature has expired, sign and install again)', 'Reinstalling failed: %@ (if the signature has expired, sign and install again)'),+ 'dev.reinstallMissing': ('找不到已签名的 App:%@(请重新构建)', 'The signed app is not there: %@ (build again)', 'The signed app is not there: %@ (build again)'),+ 'dev.signedApp': ('已签名的 App', 'Signed app', 'Signed app'),+ 'dev.saveIPA': ('保存 IPA…', 'Save IPA…', 'Save IPA…'),+ 'dev.saveIPATitle': ('保存已签名的 IPA', 'Save the signed IPA', 'Save the signed IPA'),+ 'dev.saveStage': ('打包 IPA', 'Packing the IPA', 'Packing the IPA'),+ 'dev.savedIPA': ('已保存 IPA:%@', 'Saved the IPA: %@', 'Saved the IPA: %@'),+ 'dev.saveFailed': ('保存 IPA 失败:%@(请检查目标位置的可用空间和写入权限)', 'Saving the IPA failed: %@ (check free space and write permission at the destination)', 'Saving the IPA failed: %@ (check free space and write permission at the destination)'),+ 'dev.saveNeedsApp': ('没有可打包的已签名 App:%@(请重新构建)', 'No signed app to pack: %@ (build again)', 'No signed app to pack: %@ (build again)'),+ 'dev.expiry': ('签名到期:%@(剩 %d 天)', 'Signature expires: %@ (%d days left)', 'Signature expires: %@ (%d days left)'),+ 'dev.expiryToday': ('签名今天到期(%@)', 'Signature expires today (%@)', 'Signature expires today (%@)'),+ 'dev.expiryPast': ('签名已过期(%@,%d 天前)', 'Signature expired %@ (%d days ago)', 'Signature expired %@ (%d days ago)'),+ 'dev.expiryShort': ('签名剩 %d 天', '%d days of signature left', '%d days of signature left'),+ 'dev.expiryTodayShort': ('签名今天到期', 'signature expires today', 'signature expires today'),+ 'dev.expiryExpiredShort': ('签名已过期', 'signature expired', 'signature expired'),+ 'dev.expiryUnknown': ('签名到期:未知(仍可续签)', 'Signature expiry: unknown (re-signing is still offered)', 'Signature expiry: unknown (re-signing is still offered)'),+ 'dev.resign': ('续签', 'Re-sign', 'Re-sign'),+ 'dev.resignHelp': ('用缓存工程重新签名并安装:不重新编译游戏,App 数据(存档、游戏数据)保留', "Sign and install again from the cached project: no rebuild, and the app's data (saves, game data) is kept", "Sign and install again from the cached project: no rebuild, and the app's data (saves, game data) is kept"),+ 'dev.resignStage': ('续签并安装到 %@', 'Re-signing for %@', 'Re-signing for %@'),+ 'dev.resigned': ('已续签并安装到 %@', 'Re-signed and installed on %@', 'Re-signed and installed on %@'),+ 'dev.resignFailed': ('续签失败:%@(请在 Xcode → 设置 → 账户 → Manage Certificates 检查证书,或确认网络)', 'Re-signing failed: %@ (check the certificate in Xcode → Settings → Accounts → Manage Certificates, or the network)', 'Re-signing failed: %@ (check the certificate in Xcode → Settings → Accounts → Manage Certificates, or the network)'),+ 'dev.resignNoProject': ('找不到缓存的 Xcode 工程:%@(请重新构建一次)', 'The cached Xcode project is not there: %@ (build once more)', 'The cached Xcode project is not there: %@ (build once more)'),+ 'dev.resignNoTeam': ('续签需要签名团队:请选择签名团队后再试。', 'Re-signing needs a signing team: pick one first.', 'Re-signing needs a signing team: pick one first.'),'prog.eta': ('还剩 %@', '%@ left', '%@ kvar'),'activity.mac': ('正在构建 Mac 版', 'Mac build in progress', 'Mac-byggning pågår'),'activity.ios': ('正在构建 iPhone 版', 'iPhone build in progress', 'iPhone-byggning pågår'),@@ -452,7 +583,7 @@ TABLE: dict[str, tuple[str, str, str]] = {'dep.installTimeout': ('安装超时(30 分钟)——网络太慢或卡住了', 'Install timed out (30 minutes) — the network is slow or stuck', 'Installationen överskred tidsgränsen på 30 minuter. Nätverket kan vara långsamt eller ha fastnat.'),'dep.installAll': ('一键安装全部缺失项', 'Install all missing', 'Installera alla som saknas'),'diag.title': ('诊断信息', 'Diagnostics', 'Diagnostik'),- 'diag.note': ('用于问题报告:版本、工具和上次构建的日志,不含密钥。', 'For a bug report: versions, tools, the last build’s log. No keys.', 'För en felrapport: versioner, verktyg och loggen från senaste bygget. Inga nycklar.'),+ 'diag.note': ('用于问题报告:版本、工具、上次构建的日志和所选游戏的日志,不含密钥。', 'For a bug report: versions, tools, the last build’s log and the selected game’s log. No keys.', 'För en felrapport: versioner, verktyg och loggen från senaste bygget. Inga nycklar.'),'diag.copy': ('复制诊断信息', 'Copy diagnostics', 'Kopiera diagnostik'),'diag.copied': ('已复制', 'Copied', 'Kopierad'),'dep.recheck': ('重新检测', 'Check again', 'Kontrollera igen'),@@ -462,7 +593,7 @@ TABLE: dict[str, tuple[str, str, str]] = {'dep.xcode': ('Xcode + iOS SDK', 'Xcode + iOS SDK', 'Xcode + iOS SDK'),'dep.xcode.notSelected': ('Xcode 已安装,但 xcode-select 还指向 CommandLineTools——点「修复」会切换到 Xcode 并完成首次启动(会要管理员密码)。', 'Xcode is installed, but xcode-select still points at CommandLineTools — Fix switches to Xcode and finishes its first launch (asks for your admin password).', 'Xcode är installerat men xcode-select pekar fortfarande på CommandLineTools. Välj ”Åtgärda” för att byta till Xcode och slutföra första starten. Administratörslösenord krävs.'),'dep.xcode.fix': ('修复', 'Fix', 'Åtgärda'),- 'dep.xcode.hint': ('App Store 安装(Beta 版也行,用 xcode-select 指向它),约 12 GB', 'from the App Store (a beta works too — point xcode-select at it), about 12 GB', 'Installera från App Store. Betaversion går också bra om xcode-select pekar på den. Ungefär 12 GB.'),+ 'dep.xcode.hint': ('App Store 安装(Beta 版也行,用 xcode-select 指向它),约 12 GB。首次打开会提示装 iOS SDK——让它装完。不需要 iOS Simulator(约 8 GB),Xcode 如果自动下载请取消。', 'from the App Store (a beta works too — point xcode-select at it), about 12 GB', 'Installera från App Store. Betaversion går också bra om xcode-select pekar på den. Ungefär 12 GB.'),'dep.xcode.noSDK': ('Xcode 已装,但 iOS SDK 未下载(Xcode 15 起 iOS 平台是单独下载的)', 'Xcode is installed but the iOS SDK is not downloaded (a separate download since Xcode 15)', 'Xcode är installerat men iOS SDK är inte hämtat. Från Xcode 15 hämtas iOS-plattformen separat.'),'dep.metal': ('Metal Toolchain', 'Metal Toolchain', 'Metal-verktygskedja'),'dep.metal.hint': ('xcodebuild -downloadComponent MetalToolchain(约 840 MB)', 'xcodebuild -downloadComponent MetalToolchain (about 840 MB)', 'xcodebuild -downloadComponent MetalToolchain (ungefär 840 MB)'),@@ -527,6 +658,8 @@ TABLE: dict[str, tuple[str, str, str]] = {'install.step1': ('1\\t用 AltStore / Sideloadly 安装上面的 IPA', '1\\tInstall the IPA above with AltStore / Sideloadly', '1\\tInstallera IPA-filen ovan med AltStore/Sideloadly'),'install.step2': ('2\\t把上面的 romfs 文件夹整个拷到游戏 App 的 Documents 里(文件 App → 我的 iPhone → 游戏名)', "2\\tCopy the whole romfs folder above into the game app's Documents (Files → On My iPhone → game name)", '2\\tKopiera hela romfs-mappen ovan till spelappens Dokument (appen Filer → På min iPhone → spelets namn)'),'install.step3': ('3\\t启动游戏', '3\\tLaunch the game', '3\\tStarta spelet'),+ 'library.showLog': ('显示游戏日志', 'Show game log', 'Show game log'),+ 'library.showLog.none': ('这个游戏还没有日志,运行一次就会生成', 'No game log yet. Play the game once to create it', 'No game log yet. Play the game once to create it'),'install.reveal': ('在访达中显示', 'Reveal in Finder', 'Visa i Finder'),'msg.running': ('运行:%@', 'Running: %@', 'Kör: %@'),'msg.installingNsz': ('选中的是 NSZ / XCZ 压缩格式,正在给构建用的 Python 安装 nsz…', "The selected dump is NSZ / XCZ — installing nsz into the build's Python…", 'Det valda filformatet är komprimerat NSZ/XCZ. Installerar nsz i Python-miljön som används för bygget …'),@@ -535,6 +668,37 @@ TABLE: dict[str, tuple[str, str, str]] = {'msg.stopped': ('已停止', 'Stopped', 'Stoppad'),'msg.buildFailed': ('构建失败(退出码 %d),见下方日志', 'Build failed (exit code %d) — see the log below', 'Bygget misslyckades med slutkod %d. Se loggen nedan.'),'msg.buildFailedReason': ('构建失败,见下方日志。最后一行:%@', 'Build failed — see the log below. Last line: %@', 'Bygget misslyckades. Se loggen nedan. Sista raden: %@'),+ 'fail.section': ('构建为何停止', 'Why the build stopped', 'Why the build stopped'),+ 'fail.rosetta.what': ('构建脚本用的是在 Rosetta 下运行的 Intel 版 Python,它启动的工具也会按 Intel 代码运行。', 'The build script ran with an Intel Python under Rosetta, so the tools it starts would run as Intel code too.', 'The build script ran with an Intel Python under Rosetta, so the tools it starts would run as Intel code too.'),+ 'fail.rosetta.next': ('NS Port Builder 有自带的 Python 时会优先使用它。如果这次用的是别的,请删除 ~/Library/Application Support/NS Port Builder/venv 里的 Intel 虚拟环境,再点「重新检测」。', 'NS Port Builder uses its bundled Python when it has one. If this build used another, remove the Intel venv in ~/Library/Application Support/NS Port Builder/venv and press Check again.', 'NS Port Builder uses its bundled Python when it has one. If this build used another, remove the Intel venv in ~/Library/Application Support/NS Port Builder/venv and press Check again.'),+ 'fail.translator.what': ('着色器翻译器无法运行,它需要适合这台 Mac 架构的 .NET 10 运行时。', "The shader translator does not run. It needs the .NET 10 runtime for this Mac's architecture.", "The shader translator does not run. It needs the .NET 10 runtime for this Mac's architecture."),+ 'fail.translator.next': ('用下面的按钮重新安装 .NET,然后再构建。如果环境变量 DOTNET_ROOT 指向了别的运行时,请取消设置。', 'Reinstall .NET with the button below, then build again. If DOTNET_ROOT names another runtime, unset it.', 'Reinstall .NET with the button below, then build again. If DOTNET_ROOT names another runtime, unset it.'),+ 'fail.translator.button': ('重新安装 .NET', 'Reinstall .NET', 'Reinstall .NET'),+ 'fail.iosSDK.what': ('没有安装 iOS SDK,构建 iPhone 版本需要它。', 'The iOS SDK is not installed. An iPhone build needs it.', 'The iOS SDK is not installed. An iPhone build needs it.'),+ 'fail.iosSDK.next': ('打开 Xcode → 设置 → 组件,安装 iOS,或者点下面的按钮运行 xcodebuild -downloadPlatform iOS。', 'Open Xcode → Settings → Components and install iOS, or press the button to run xcodebuild -downloadPlatform iOS.', 'Open Xcode → Settings → Components and install iOS, or press the button to run xcodebuild -downloadPlatform iOS.'),+ 'fail.iosSDK.button': ('下载 iOS 平台', 'Download iOS platform', 'Download iOS platform'),+ 'fail.cltSelected.what': ('当前选中的是命令行工具而不是 Xcode,而命令行工具没有 iOS SDK。', 'The Command Line Tools are selected instead of Xcode, and they have no iOS SDK.', 'The Command Line Tools are selected instead of Xcode, and they have no iOS SDK.'),+ 'fail.cltSelected.next': ('用下面的按钮选择 Xcode(会要管理员密码),或者在终端运行 sudo xcode-select -s /Applications/Xcode.app,然后再构建。', 'Select Xcode with the button below (it asks for an administrator password), or run sudo xcode-select -s /Applications/Xcode.app in Terminal, then build again.', 'Select Xcode with the button below (it asks for an administrator password), or run sudo xcode-select -s /Applications/Xcode.app in Terminal, then build again.'),+ 'fail.cltSelected.button': ('选择 Xcode', 'Select Xcode', 'Select Xcode'),+ 'fail.otherMetal.what': ('这台 Mac 的 Metal 编译器不是着色器测试时用的那一个。', "This Mac's Metal compiler is not the one the shaders were tested with.", "This Mac's Metal compiler is not the one the shaders were tested with."),+ 'fail.otherMetal.next': ('这个游戏使用 NVN,需要 Xcode 27.1(macOS 26.6 或更新)。请安装它和它的 Metal 工具链,然后再构建。', 'This game uses NVN and needs Xcode 27.1 (macOS 26.6 or later). Install it and its Metal toolchain, then build again.', 'This game uses NVN and needs Xcode 27.1 (macOS 26.6 or later). Install it and its Metal toolchain, then build again.'),+ 'fail.otherMetal.risk': ('会用没有测试过的 Metal 编译器构建。画面可能出错,结果也没有人测试过,不受支持。这个选择只对这一次构建有效,不会保存。', 'This builds with a Metal compiler nobody tested the shaders with. The pictures can come out wrong, the result is untested and it is not supported. The choice applies to this one build and is not saved.', 'This builds with a Metal compiler nobody tested the shaders with. The pictures can come out wrong, the result is untested and it is not supported. The choice applies to this one build and is not saved.'),+ 'fail.shaderRegression.what': ('有些以前能翻译的着色器,在这个版本里翻译失败了。', 'Some shaders that translated before fail to translate with this version.', 'Some shaders that translated before fail to translate with this version.'),+ 'fail.shaderRegression.next': ('请带上构建日志里的列表去报告这个问题。「仍然构建」会把这些着色器留空,所以画面可能缺少一部分。', 'Please report it with the list in the build log. Building anyway leaves those shaders out, so parts of the picture may be missing.', 'Please report it with the list in the build log. Building anyway leaves those shaders out, so parts of the picture may be missing.'),+ 'fail.shaderRegression.risk': ('会在没有这些着色器的情况下打包。画面可能缺少一部分,结果也没有人测试过。这个选择只对这一次构建有效,不会保存。', 'This packs the app without those shaders. Parts of the picture may be missing and the result is untested. The choice applies to this one build and is not saved.', 'This packs the app without those shaders. Parts of the picture may be missing and the result is untested. The choice applies to this one build and is not saved.'),+ 'fail.damagedNSP.what': ('游戏文件已损坏,没有通过 NCA 的哈希校验,常见原因是复制不完整或下载中断。', 'The game file is damaged. It fails the hash check, often from an incomplete copy or a broken download.', 'The game file is damaged. It fails the hash check, often from an incomplete copy or a broken download.'),+ 'fail.damagedNSP.next': ('请重新导出或重新下载这个文件。「仍然构建」会按读到的样子写出损坏的文件,游戏可能因此出错。', 'Dump or download the file again. Building anyway writes the damaged files as they are, which may break the game.', 'Dump or download the file again. Building anyway writes the damaged files as they are, which may break the game.'),+ 'fail.damagedNSP.risk': ('会把损坏的文件按读到的样子写出。游戏可能崩溃或显示错误的数据,结果也没有人测试过。这个选择只对这一次构建有效,不会保存。', 'This writes the damaged files as they are. The game may crash or show wrong data, and the result is untested. The choice applies to this one build and is not saved.', 'This writes the damaged files as they are. The game may crash or show wrong data, and the result is untested. The choice applies to this one build and is not saved.'),+ 'fail.a32Program.what': ('这个版本是 32 位的,无法在 Apple 芯片上运行。', "This version is 32-bit and can't run on Apple silicon.", "This version is 32-bit and can't run on Apple silicon."),+ 'fail.a32Program.whatNamed': ('%@ 的这个版本是 32 位的,无法在 Apple 芯片上运行。', "This version of %@ is 32-bit and can't run on Apple silicon.", "This version of %@ is 32-bit and can't run on Apple silicon."),+ 'fail.a32Program.next': ('请选择游戏配置里列出的那个更新版本。', 'Pick the update the profile lists.', 'Pick the update the profile lists.'),+ 'fail.buildAnyway': ('仍然构建…', 'Build anyway…', 'Build anyway…'),+ 'fail.confirm.title': ('仍然构建?', 'Build anyway?', 'Build anyway?'),+ 'fail.confirm.go': ('仍然构建', 'Build anyway', 'Build anyway'),+ 'fail.confirm.cancel': ('取消', 'Cancel', 'Cancel'),+ 'fail.override.note': ('仍然构建:这一次构建加上 %@(已确认,不会保存)', 'Build anyway: this build adds %@ (confirmed, not saved)', 'Build anyway: this build adds %@ (confirmed, not saved)'),+ 'dep.metal.other': ('%@(测试用的是 %@)', '%@ (tested: %@)', '%@ (tested: %@)'),+ 'dep.fix.metalPin': ('这不是着色器测试时用的 Metal 编译器。使用 NVN 的游戏会在着色器步骤前停下。请安装 Xcode 27.1(macOS 26.6 或更新)和它的 Metal 工具链。', 'This is not the Metal compiler the shaders were tested with. Games that use NVN stop before the shader steps. Install Xcode 27.1 (macOS 26.6 or later) and its Metal toolchain.', 'This is not the Metal compiler the shaders were tested with. Games that use NVN stop before the shader steps. Install Xcode 27.1 (macOS 26.6 or later) and its Metal toolchain.'),'msg.exitCode': ('退出码 %d', 'exit code %d', 'slutkod %d'),'msg.stagingFailed': ('无法在暂存文件夹里建立链接(文件在不同磁盘?)', 'Could not create links in the staging folder (files on different volumes?)', 'Kunde inte skapa en länk i mellanlagringsmappen. Ligger filerna på olika diskar?'),'msg.stagedFromSharedFolder': ('文件夹里还有其他游戏:只把选中的这个游戏(%@)临时复制出去构建', 'The folder holds other games: building from a temporary copy of this one (%@)', 'Mappen innehåller andra spel. Bygger från en tillfällig kopia av det här (%@)'),diff --git a/frontend-qt/nspb_qt/model.py b/frontend-qt/nspb_qt/model.pyindex fd999500..209e6261 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 Q_ARG, QMetaObject, QObject, Qt, QThread, Signal, Slot+from . import build_failure as bffrom . import platform_util as pufrom .i18n import Langfrom .localization import t@@ -83,6 +84,8 @@ class Model(QObject):self.stages: list[Stage] = []self.running = Falseself.log_tail = ''+ self.failure: bf.Failure | None = None # the script's known early stop (build_failure.py), None for any other+ self.override = bf.OverrideState() # "Build anyway": one confirmed --allow-* for the next buildself._last_error = '' # the last real log line: the failure note names it (issue #52)self.game_dir = ''self.base_path = ''@@ -969,6 +972,8 @@ class Model(QObject):self.ipa_path = str(Path(self.out_dir, f'{tid_hex}.ipa'))args += ['-o', self.ipa_path]self.effective_work_dir = work_dir if has_work_dir else str(Path(input_dir, f'{tid_hex}_build'))+ flag = self.override.take() # for this build only: the next one asks again+ args = bf.arguments(args, flag)self.running = Trueself.runningChanged.emit(True)@@ -976,7 +981,11 @@ class Model(QObject):self.ipa_path = self.archive_path = self.mac_app_path = ''self.log_tail = ''self._last_error = ''+ self.failure = None+ self.override.cancel()self.stagesChanged.emit()+ if flag:+ self.log(self.t('fail.override.note', flag) + '\n')self.log(self.t('msg.running', py + ' ' + ' '.join(args)) + '\n')env = pu.child_env()@@ -1030,13 +1039,34 @@ class Model(QObject):# The last real line says more than the exit code: "Build failed (exit code 1)"# on its own sent a reporter looking for a log that was not on screen (#52)last = getattr(self, '_last_error', '')- self.finished.emit(False, self.t('msg.buildFailedReason', last) if last else self.t('msg.buildFailed'))+ note = self.t('msg.buildFailedReason', last) if last else self.t('msg.buildFailed')+ known = bf.classify(self.log_tail)+ if known.kind != bf.UNKNOWN: # a known early stop: the window explains it and offers the next step+ self.failure = known+ note = self.failure_what(known)+ self.finished.emit(False, note)if staging:shutil.rmtree(staging, ignore_errors=True)self._thread = threading.Thread(target=work, daemon=True)self._thread.start()+ def failure_what(self, f: 'bf.Failure') -> str:+ """The first sentence of a failure's hint (it names the game of a 32-bit program when the message does)."""+ if f.kind == bf.A32_PROGRAM and f.game:+ return self.t('fail.a32Program.whatNamed', f.game)+ return self.t(f.what_key)++ def fix_failure(self, f: 'bf.Failure') -> None:+ """The failure card's fix buttons run the dependency rows' own fixes (install_dep, as Settings does)."""+ if f.kind == bf.TRANSLATOR:+ row = next((d for d in self.deps if d.id == 'dotnet'), None)+ if row:+ self.install_dep(row)+ elif f.kind == bf.IOS_SDK and not pu.IS_WIN:+ self.install_dep(Dep('xcode', 'dep.xcode', 'dep.xcode.hint', DepState.MISSING,+ install=['/usr/bin/xcodebuild', '-downloadPlatform', 'iOS']))+def cancel_build(self) -> None:if self._proc and self._proc.poll() is None:self._proc.terminate()@@ -1047,6 +1077,7 @@ class Model(QObject):"""Feed one line of the build's output: stage lines move the stage list, everythingelse goes to the log (which is what the window shows)."""self.log(line + '\n')+ self.log_tail = (self.log_tail + line + '\n')[-12000:] # what the classifier reads on a failure# The last line that was not stage bookkeeping: a failed build's summary used to be the# bare exit code ("Build failed (exit code 1)"), which told the reporter nothing and sent# them looking for a log that a short window had below the fold (issue #52)diff --git a/frontend-qt/nspb_qt/ui.py b/frontend-qt/nspb_qt/ui.pyindex 759c482c..5ccceba2 100644--- a/frontend-qt/nspb_qt/ui.py+++ b/frontend-qt/nspb_qt/ui.py@@ -299,10 +299,73 @@ class MainWindow(QMainWindow):hint.setObjectName('note')hint.setWordWrap(True)outer.addLayout(row)+ self._build_failure_box(outer)outer.addWidget(hint)self._translatable.append((hint, 'msg.workdirHint'))self.centralWidget().layout().addWidget(wrap)+ def _build_failure_box(self, outer: QVBoxLayout) -> None:+ """After a known early stop of the script: what happened, the next step, and its button."""+ self.failure_box = QFrame()+ self.failure_box.setObjectName('card')+ box = QVBoxLayout(self.failure_box)+ box.setContentsMargins(12, 8, 12, 8)+ box.setSpacing(4)+ self.failure_what = QLabel('')+ self.failure_what.setWordWrap(True)+ self.failure_what.setStyleSheet(f'color: {ORANGE}; font-weight: 600;')+ self.failure_next = QLabel('')+ self.failure_next.setWordWrap(True)+ self.failure_next.setObjectName('note')+ buttons = QHBoxLayout()+ self.failure_fix_btn = QPushButton('')+ self.failure_fix_btn.clicked.connect(self._fix_failure)+ self.failure_anyway_btn = QPushButton(self.m.t('fail.buildAnyway'))+ self.failure_anyway_btn.clicked.connect(self._build_anyway)+ buttons.addWidget(self.failure_fix_btn)+ buttons.addWidget(self.failure_anyway_btn)+ buttons.addStretch(1)+ box.addWidget(self.failure_what)+ box.addWidget(self.failure_next)+ box.addLayout(buttons)+ self.failure_box.hide()+ outer.addWidget(self.failure_box)++ _FIX_BUTTONS = {'translator': 'fail.translator.button', 'iosSDK': 'fail.iosSDK.button'}++ def _show_failure(self) -> None:+ f = self.m.failure+ if f is None or self.m.running:+ self.failure_box.hide()+ return+ self.failure_what.setText(self.m.failure_what(f))+ self.failure_next.setText(self.m.t(f.next_key))+ fix = self._FIX_BUTTONS.get(f.kind)+ self.failure_fix_btn.setVisible(fix is not None)+ if fix:+ self.failure_fix_btn.setText(self.m.t(fix))+ self.failure_anyway_btn.setVisible(f.flag is not None)+ self.failure_anyway_btn.setText(self.m.t('fail.buildAnyway'))+ self.failure_box.show()++ def _fix_failure(self) -> None:+ if self.m.failure is not None:+ self.m.fix_failure(self.m.failure)++ def _build_anyway(self) -> None:+ """Asks first: the dialog states the risk. Nothing is armed until the player agrees."""+ if self.m.running or not self.m.override.request(self.m.failure):+ return+ from PySide6.QtWidgets import QMessageBox+ risk = self.m.t(f'fail.{self.m.failure.kind}.risk')+ yes = QMessageBox.question(self, self.m.t('fail.confirm.title'), risk,+ QMessageBox.Yes | QMessageBox.Cancel, QMessageBox.Cancel)+ if yes != QMessageBox.Yes:+ self.m.override.cancel()+ return+ if self.m.override.confirm():+ self._build_clicked()+@staticmethoddef _separator() -> QFrame:line = QFrame()@@ -320,6 +383,7 @@ class MainWindow(QMainWindow):# start-up language — the report's half-Chinese interfacefor w, key in self._translatable:w.setText(self.m.t(key))+ self._show_failure()full = (pu.short_path(self.m.repo_path) if self.m.repo_okelse (self.m.repo_path or self.m.t('repo.notFound')))self.repo_path_label.setText(full)@@ -532,6 +596,7 @@ class MainWindow(QMainWindow):self.footer.setStyleSheet(f'color: {RED};')self.footer.setText(msg)self._failed = not ok+ self._show_failure()if not ok:# The message points at the log, so put it in view rather than trusting the window to# be tall enough. ensureWidgetVisible also handles the scroll area's own margin.@@ -552,6 +617,7 @@ class MainWindow(QMainWindow):self.footer.setText('')self.footer.setStyleSheet('')self._failed = False+ self.failure_box.hide()self.m.start_build()def _choose_repo(self) -> None:diff --git a/frontend-qt/tests/test_build_failure_hints.py b/frontend-qt/tests/test_build_failure_hints.pynew file mode 100644index 00000000..d20d91a1--- /dev/null+++ b/frontend-qt/tests/test_build_failure_hints.py@@ -0,0 +1,202 @@+"""The script's early stops become hints (nspb_qt/build_failure.py, the SwiftUI app's BuildFailure.swift).++Pure Python, no Qt. frontend/Tests/Fixtures/build_failures.json holds the script's real message for every+pattern, shared with the Swift tests. A sync of scripts/ or dm/ that rewords a message fails here.++ python3 -m unittest frontend-qt/tests/test_build_failure_hints.py -v+"""+from __future__ import annotations++import json+import os+import re+import sys+import unittest+from pathlib import Path+from unittest import mock++ROOT = Path(__file__).resolve().parents[2]+sys.path.insert(0, str(ROOT / 'frontend-qt'))+os.environ.setdefault('QT_QPA_PLATFORM', 'offscreen')++from nspb_qt import build_failure as bf # noqa: E402+from nspb_qt.localization import TABLE # noqa: E402++FIXTURES = json.loads((ROOT / 'frontend/Tests/Fixtures/build_failures.json').read_text(encoding='utf-8'))+SWIFT = (ROOT / 'frontend/Sources/NSPortBuilder/BuildFailure.swift').read_text(encoding='utf-8')+++def fixture(pattern_id: str) -> dict:+ return next(f for f in FIXTURES if f['id'] == pattern_id)+++class Classifier(unittest.TestCase):+ def test_every_pattern_has_its_real_message_and_matches_it(self):+ for pid, kind, pattern in bf.TABLE:+ with self.subTest(pattern=pid):+ f = fixture(pid)+ self.assertEqual(f['kind'], kind)+ self.assertTrue(re.search(pattern, f['text']), f'{pid} no longer matches its message')+ self.assertEqual(bf.classify(f['text']).kind, kind)+ self.assertEqual({f['id'] for f in FIXTURES}, {p[0] for p in bf.TABLE}, 'a fixture without a pattern')++ def test_every_kind_is_reachable(self):+ self.assertEqual({k for _, k, _ in bf.TABLE}, set(bf.KINDS))++ def test_the_vendored_scripts_still_say_what_the_patterns_expect(self):+ """A sync that rewords a message must fail here, not turn a hint into the raw last line."""+ for f in FIXTURES:+ with self.subTest(pattern=f['id']):+ there = f['fragment'] in (ROOT / f['source']).read_text(encoding='utf-8')+ if f.get('pending_sync'):+ self.assertFalse(there, f"{f['id']} is in {f['source']} now: remove pending_sync ({f['pending_sync']}) from the fixture")+ else:+ self.assertTrue(there, f"{f['id']}: {f['source']} no longer contains {f['fragment']!r}: update the pattern and the fixture")++ def test_the_failure_is_found_above_the_last_line(self):+ log = ("[3/9] extract\n[RED] the NSP is damaged: 2 files fail the NCA's hash check (x)\n"+ "---- last lines of /w/extract.log ----\n[RED] nx_extract exit code 3 (full output: /w/extract.log)\n")+ self.assertEqual(bf.classify(log).kind, bf.DAMAGED_NSP)++ def test_unknown_output_keeps_todays_behaviour(self):+ for log in ('', 'something odd happened', '[RED] the RomFS image failed',+ '[RED] the NSP is damaged: 3 files written as read (--allow-damaged)'): # the note of a build that went on+ self.assertEqual(bf.classify(log), bf.Failure(bf.UNKNOWN), log)++ def test_the_game_of_a_32_bit_program_is_named_when_the_message_names_it(self):+ f = fixture('arm32.program')+ self.assertEqual(bf.classify(f['text']).game, f['game'])+ self.assertIsNone(bf.classify('[RED] ? (0100ABCD00000000) is a 32-bit ARM program (main.npdm)').game)+ self.assertIsNone(bf.classify('[RED] the shader translator does not run (x)').game)++ def test_the_table_is_the_swift_one(self):+ rows = re.findall(r'\("([\w.]+)", \.(\w+), "((?:[^"\\]|\\.)*)"\)', SWIFT)+ self.assertEqual(len(rows), len(bf.TABLE))+ for (sid, skind, spattern), (pid, kind, pattern) in zip(rows, bf.TABLE):+ self.assertEqual((sid, skind), (pid, kind))+ self.assertEqual(spattern.replace('\\\\', '\\'), pattern, pid)++ def test_the_swift_overrides_are_these(self):+ flags = dict(re.findall(r'case \.(\w+): return "(--allow-[\w-]+)"', SWIFT))+ self.assertEqual(flags, bf.OVERRIDE_FLAGS)+++class Override(unittest.TestCase):+ BASE = ['-m', 'x', '/in', '-k', '/k', '--progress', 'lines']++ def test_the_build_arguments_get_exactly_one_allow_flag(self):+ self.assertEqual(bf.arguments(self.BASE, None), self.BASE)+ for kind, flag in bf.OVERRIDE_FLAGS.items():+ args = bf.arguments(self.BASE, flag)+ self.assertEqual([a for a in args if a.startswith('--allow-')], [flag], kind)+ self.assertEqual(args[:-1], self.BASE)+ two = bf.arguments(self.BASE + ['--allow-damaged'], '--allow-other-metal')+ self.assertEqual([a for a in two if a.startswith('--allow-')], ['--allow-other-metal'])+ self.assertEqual(bf.arguments(self.BASE, '--platform'), self.BASE, 'not an override')++ def test_nothing_is_armed_until_the_confirmation(self):+ s = bf.OverrideState()+ self.assertTrue(s.request(bf.Failure(bf.OTHER_METAL)))+ self.assertIsNone(s.take())+ s.cancel()+ self.assertFalse(s.confirm())+ self.assertIsNone(s.take())++ def test_a_confirmed_override_serves_one_build_only(self):+ s = bf.OverrideState()+ s.request(bf.Failure(bf.DAMAGED_NSP))+ self.assertTrue(s.confirm())+ self.assertEqual(s.take(), '--allow-damaged')+ self.assertIsNone(s.take(), 'the next build runs without it')++ def test_a_stop_without_an_override_cannot_be_built_anyway(self):+ s = bf.OverrideState()+ for kind in (bf.ROSETTA, bf.TRANSLATOR, bf.IOS_SDK, bf.CLT_SELECTED, bf.A32_PROGRAM, bf.UNKNOWN):+ self.assertFalse(s.request(bf.Failure(kind)), kind)+ self.assertFalse(s.request(None))+ self.assertIsNone(s.confirming)+++class Strings(unittest.TestCase):+ def test_every_hint_is_in_both_languages_without_semicolons(self):+ keys = ['fail.section', 'fail.buildAnyway', 'fail.confirm.title', 'fail.confirm.go', 'fail.confirm.cancel',+ 'fail.override.note', 'fail.a32Program.whatNamed', 'fail.translator.button', 'fail.iosSDK.button',+ 'fail.cltSelected.button', 'dep.metal.other', 'dep.fix.metalPin']+ for kind in bf.KINDS:+ keys += [f'fail.{kind}.what', f'fail.{kind}.next']+ if kind in bf.OVERRIDE_FLAGS:+ keys.append(f'fail.{kind}.risk')+ for key in keys:+ with self.subTest(key=key):+ self.assertIn(key, TABLE)+ row = TABLE[key]+ zh, en = row[0], row[1] # the table may carry a third (Swedish) element+ self.assertTrue(zh and en)+ for text in (zh, en):+ self.assertNotIn(';', text)+ self.assertNotIn(';', text)+ self.assertNotEqual(zh, en)++ def test_the_risk_text_states_the_risk_and_that_it_is_one_build(self):+ for kind in bf.OVERRIDE_FLAGS:+ en = TABLE[f'fail.{kind}.risk'][1]+ self.assertIn('untested', en)+ self.assertIn('one build', en)++ def test_the_hints_say_what_the_task_asks(self):+ self.assertIn('Xcode 27.1 (macOS 26.6 or later)', TABLE['fail.otherMetal.next'][1])+ self.assertIn("32-bit and can't run on Apple silicon", TABLE['fail.a32Program.what'][1])+++try:+ from PySide6.QtWidgets import QApplication, QMessageBox+except ImportError: # the packaged app always has it; a bare python3 may not+ QApplication = None++[email protected](QApplication is None, 'PySide6 is not installed')+class Window(unittest.TestCase):+ @classmethod+ def setUpClass(cls):+ cls.app = QApplication.instance() or QApplication([])++ def _window(self, failure):+ from nspb_qt.model import Model+ from nspb_qt.ui import MainWindow+ m = Model()+ w = MainWindow(m)+ w.show()+ m.failure = failure+ w._show_failure()+ return m, w++ def test_a_known_stop_shows_its_hint_and_the_buttons_it_has(self):+ m, w = self._window(bf.Failure(bf.OTHER_METAL))+ self.assertFalse(w.failure_box.isHidden())+ self.assertFalse(w.failure_anyway_btn.isHidden())+ self.assertTrue(w.failure_fix_btn.isHidden())+ m, w = self._window(bf.Failure(bf.TRANSLATOR))+ self.assertFalse(w.failure_fix_btn.isHidden())+ self.assertTrue(w.failure_anyway_btn.isHidden())+ m, w = self._window(bf.Failure(bf.ROSETTA))+ self.assertTrue(w.failure_fix_btn.isHidden() and w.failure_anyway_btn.isHidden())+ m, w = self._window(None)+ self.assertTrue(w.failure_box.isHidden())++ def test_build_anyway_builds_only_after_the_player_agrees(self):+ m, w = self._window(bf.Failure(bf.DAMAGED_NSP))+ with mock.patch.object(w, '_build_clicked') as build, \+ mock.patch.object(QMessageBox, 'question', return_value=QMessageBox.Cancel):+ w._build_anyway()+ build.assert_not_called()+ self.assertIsNone(m.override.take())+ with mock.patch.object(w, '_build_clicked') as build, \+ mock.patch.object(QMessageBox, 'question', return_value=QMessageBox.Yes) as ask:+ w._build_anyway()+ build.assert_called_once()+ self.assertIn('untested', ask.call_args.args[2])+ self.assertEqual(m.override.take(), '--allow-damaged')+++if __name__ == '__main__':+ unittest.main()diff --git a/frontend/Sources/NSPortBuilder/BuildFailure.swift b/frontend/Sources/NSPortBuilder/BuildFailure.swiftnew file mode 100644index 00000000..6291b522--- /dev/null+++ b/frontend/Sources/NSPortBuilder/BuildFailure.swift@@ -0,0 +1,105 @@+import Foundation++/// The early stops of the NSP script that the launcher can turn into a next step. The script prints a+/// `[RED]` line and exits 1 for each (a `BuildError`), and the launcher used to show only the last line of+/// the log, cut to 200 characters. The classifier reads the whole log tail, because for a damaged NSP the+/// last line is only "nx_extract exit code 3" and the message is a few lines above it.+enum BuildFailureKind: String, CaseIterable {+ case rosetta, translator, iosSDK, cltSelected, otherMetal, shaderRegression, damagedNSP, a32Program, unknown++ /// The script's override for this stop, offered as "Build anyway". Only these three have one that the launcher+ /// may offer: the others cannot be built around (a 32-bit program, a missing SDK).+ var overrideFlag: String? {+ switch self {+ case .otherMetal: return "--allow-other-metal"+ case .shaderRegression: return "--allow-shader-regressions"+ case .damagedNSP: return "--allow-damaged"+ default: return nil+ }+ }++ /// L10n keys: what happened, and the next step.+ var whatKey: String { "fail.\(rawValue).what" }+ var nextKey: String { "fail.\(rawValue).next" }+}++struct BuildFailure: Equatable {+ var kind: BuildFailureKind+ var gameName: String? // a32Program: the game, when the message names it+}++enum BuildFailureClassifier {+ /// One row per message of the script. The pattern is a stable part of the text in scripts/build_ipa_from_nsp.py,+ /// dm/gfx/tools/own_compilers.py or dm/tools/nx_extract/Program.cs (regular expressions, searched in the log).+ /// Frontend/Tests/Fixtures/build_failures.json holds the real message for every row, and a test checks that each+ /// fragment is still in the vendored script, so a sync that rewords a message fails there instead of turning a+ /// hint into the raw last line. The Qt front end has the same table (nspb_qt/build_failure.py, compared by a test).+ static let table: [(id: String, kind: BuildFailureKind, pattern: String)] = [+ ("rosetta.intel", .rosetta, "is an Intel one running under Rosetta"),+ ("translator.run", .translator, "the shader translator does not run"),+ ("translator.start", .translator, "the shader translator does not start"),+ ("ios.sdk", .iosSDK, "the iOS SDK is not installed"),+ ("clt.selected", .cltSelected, "the selected developer folder is the Command Line Tools"),+ ("metal.other", .otherMetal, "Metal compiler is not the one the shaders were tested with"),+ ("shaders.regression", .shaderRegression, "a change to the translation chain broke them"),+ ("nsp.damaged", .damagedNSP, "files fail the NCA's hash check"),+ ("arm32.program", .a32Program, "is a 32-bit ARM program"),+ ]++ /// `unknown` when no row matches: the caller then keeps showing the last line of the log.+ static func classify(_ log: String) -> BuildFailure {+ for row in table where log.range(of: row.pattern, options: .regularExpression) != nil {+ return BuildFailure(kind: row.kind, gameName: row.kind == .a32Program ? gameName(in: log) : nil)+ }+ return BuildFailure(kind: .unknown, gameName: nil)+ }++ /// "<name> (<title ID>) is a 32-bit ARM program": the name is "?" when the extraction has none.+ static func gameName(in log: String) -> String? {+ guard let r = log.range(of: #"(?m)^(?:\[RED\] )?.+? \([0-9A-Fa-f]{16}\) is a 32-bit ARM program"#, options: .regularExpression) else { return nil }+ var line = String(log[r])+ if line.hasPrefix("[RED] ") { line.removeFirst(6) }+ guard let paren = line.range(of: " (", options: .backwards, range: nil, locale: nil) else { return nil }+ let name = String(line[..<paren.lowerBound]).trimmingCharacters(in: .whitespaces)+ return name.isEmpty || name == "?" ? nil : name+ }++ /// The build arguments with the one-off override added: exactly one `--allow-*`, or none.+ static func arguments(_ args: [String], adding flag: String?) -> [String] {+ let rest = args.filter { !$0.hasPrefix("--allow-") }+ guard let flag, flag.hasPrefix("--allow-") else { return rest }+ return rest + [flag]+ }+}++/// The Metal compiler the shaders were tested with (dm/gfx/tools/dmsh_chain.lock) against this Mac's. NVN games stop at the+/// start of the shader steps with another compiler (own_compilers.py --check-metal), so the dependency panel says so beforehand.+/// The comparison is the script's: the first line of `xcrun -sdk <sdk> metal --version`, and a compiler that is not there is+/// not a mismatch (its own row reports a missing one).+enum MetalPin {+ struct Mismatch: Equatable { var sdk: String; var now: String; var pinned: String }++ static let lockPath = "dm/gfx/tools/dmsh_chain.lock"++ /// `metal_macosx` / `metal_iphoneos` lines of the lock: tab separated, `#` for comments.+ static func pins(lock: String) -> [String: String] {+ var out: [String: String] = [:]+ for line in lock.split(separator: "\n", omittingEmptySubsequences: true) where !line.hasPrefix("#") {+ let parts = line.split(separator: "\t", maxSplits: 1, omittingEmptySubsequences: false)+ if parts.count == 2 { out[String(parts[0])] = String(parts[1]).trimmingCharacters(in: .whitespaces) }+ }+ return out+ }++ /// `now`: the compilers found, by SDK name (macosx, iphoneos), nil for one that did not answer.+ /// An iOS compiler is compared only when `iOS` (the build is for an iPhone).+ static func mismatches(lock: String, now: [String: String?], iOS: Bool) -> [Mismatch] {+ let pinned = pins(lock: lock)+ var out: [Mismatch] = []+ for sdk in iOS ? ["macosx", "iphoneos"] : ["macosx"] {+ guard let want = pinned["metal_" + sdk], let found = now[sdk] ?? nil, !found.isEmpty, found != want else { continue }+ out.append(Mismatch(sdk: sdk, now: found, pinned: want))+ }+ return out+ }+}diff --git a/frontend/Sources/NSPortBuilder/BuildFailureView.swift b/frontend/Sources/NSPortBuilder/BuildFailureView.swiftnew file mode 100644index 00000000..5830a513--- /dev/null+++ b/frontend/Sources/NSPortBuilder/BuildFailureView.swift@@ -0,0 +1,62 @@+import SwiftUI++/// Under the build button after a stop the script's early checks explain: what happened in plain words, the next step, and the+/// button that does it (a dependency's own install command, or "Build anyway" for the three stops that have an override).+struct BuildFailureCard: View {+ @ObservedObject var m: BuildModel++ var body: some View {+ if let f = m.failure {+ VStack(alignment: .leading, spacing: 10) {+ Text(m.t("fail.section")).font(.manrope(15, .semibold)).foregroundStyle(.secondary).padding(.leading, 2)+ VStack(alignment: .leading, spacing: 8) {+ HStack(alignment: .firstTextBaseline, spacing: 10) {+ Circle().fill(LauncherPalette.building).frame(width: 7, height: 7)+ Text(m.failureWhat(f)).font(.manrope(14, .semibold)).fixedSize(horizontal: false, vertical: true)+ }+ Text(m.t(f.kind.nextKey)).font(.manrope(13)).foregroundStyle(.secondary)+ .fixedSize(horizontal: false, vertical: true).padding(.leading, 17)+ buttons(f.kind).padding(.leading, 17).padding(.top, 2)+ }+ .padding(18)+ .frame(maxWidth: .infinity, alignment: .leading)+ .background(LauncherPalette.surface.opacity(0.75), in: RoundedRectangle(cornerRadius: 14))+ .overlay(RoundedRectangle(cornerRadius: 14).strokeBorder(Color.white.opacity(0.06)))+ }+ .alert(m.t("fail.confirm.title"), isPresented: Binding(get: { m.confirmingOverride != nil }, set: { if !$0 { m.cancelBuildAnyway() } })) {+ Button(m.t("fail.confirm.go")) { m.confirmBuildAnyway() }+ Button(m.t("fail.confirm.cancel"), role: .cancel) { m.cancelBuildAnyway() }+ } message: {+ Text(m.confirmingOverride.map { m.t("fail.\($0.rawValue).risk") } ?? "")+ }+ }+ }++ @ViewBuilder private func buttons(_ kind: BuildFailureKind) -> some View {+ HStack(spacing: 10) {+ switch kind {+ case .translator:+ fix(kind, "fail.translator.button")+ case .iosSDK:+ fix(kind, "fail.iosSDK.button")+ case .cltSelected:+ if BuildModel.installedXcode() != nil { fix(kind, "fail.cltSelected.button") }+ default: EmptyView()+ }+ if kind.overrideFlag != nil {+ Button(m.t("fail.buildAnyway")) { m.requestBuildAnyway() }.disabled(m.running)+ }+ }+ .buttonStyle(LauncherSecondaryButtonStyle())+ }++ private func fix(_ kind: BuildFailureKind, _ key: String) -> some View {+ Group {+ if m.fixBusy(kind) {+ HStack(spacing: 8) { ProgressView().controlSize(.small); Text(m.t("dep.installing")).font(.manrope(12)).foregroundStyle(LauncherPalette.building) }+ } else {+ Button(m.t(key)) { m.fixBuildFailure(kind) }.disabled(m.running)+ }+ }+ }+}diff --git a/frontend/Sources/NSPortBuilder/ContentView.swift b/frontend/Sources/NSPortBuilder/ContentView.swiftindex 2d74e7fa..0ac1cc25 100644--- a/frontend/Sources/NSPortBuilder/ContentView.swift+++ b/frontend/Sources/NSPortBuilder/ContentView.swift@@ -100,6 +100,13 @@ final class BuildModel: ObservableObject {@Published var logTail = ""@Published var done = false@Published var doneNote = ""+ /// What the NSP script stopped on, when it is one of the known early stops (BuildFailure.swift). nil for a build that+ /// succeeded, is running, or failed some other way (the note then shows the last line of the log, as it always did).+ @Published var failure: BuildFailure?+ /// "Build anyway" asked for this stop and waiting for the confirmation dialog.+ @Published var confirmingOverride: BuildFailureKind?+ /// The one-off `--allow-*` of a confirmed "Build anyway": taken by the next build and never stored.+ private(set) var armedOverride: BuildFailureKind?@Published var ipaPath = "" // captured from the script's "output IPA:" line@Published var macAppPath = "" // --platform mac-app: the .app this build produced/// 'ios' = an IPA for an iPhone; 'mac-app' = a double-clickable Mac app (upstream's@@ -1024,6 +1031,8 @@ final class BuildModel: ObservableObject {guard !running else { return }stopping = falserunning = true; done = false; doneNote = ""; stages = []; logTail = ""; lineBuf = ""; chainNoteShown = false+ failure = nil; confirmingOverride = nil+ let override = takeOverrideFlag() // for this build only: the next one asks againinstalledOn = ""; installedAppPath = ""; bundleID = ""guard repoOK else {fail(repoPath.isEmpty ? t("msg.repoInvalidEmpty") : String(format: t("msg.repoInvalid"), shortPath(repoPath)))@@ -1147,6 +1156,8 @@ final class BuildModel: ObservableObject {// The archive step packs whatever folder the build reported; without --work-dir that is the// script's default, which is the same workDir unless a separate output folder was chosen.effectiveWorkDir = hasWorkDir ? workDir : (inputDir as NSString).appendingPathComponent(tidHex + "_build")+ args = BuildFailureClassifier.arguments(args, adding: override)+ if let override { say(String(format: t("fail.override.note"), override)) }say(String(format: t("msg.running"), py) + " " + args.joined(separator: " "))lastBuildCommand = [py] + args@@ -1218,6 +1229,7 @@ final class BuildModel: ObservableObject {if let i = self.stages.lastIndex(where: { $0.state == .running }) {self.stages[i].state = .failedself.stages[i].detail = String(format: self.t("msg.exitCode"), status.terminationStatus)+ self.noteFailure()} else {// The last real line says more than the exit code alone, and the message// points at the log: "Build failed (exit code 1)" with nothing else sent a@@ -1226,6 +1238,7 @@ final class BuildModel: ObservableObject {if let last = Self.lastMeaningfulLine(self.logTail) {self.doneNote = String(format: self.t("msg.buildFailedReason"), last)}+ self.noteFailure()}self.cleanupStaging()}@@ -1247,6 +1260,62 @@ final class BuildModel: ObservableObject {doneNote = note}+ /// A failed build's log read for the script's known early stops: the card under the build button then says what+ /// happened and what to do. An unknown stop leaves the note (the last line of the log) as it is.+ func noteFailure() {+ let f = BuildFailureClassifier.classify(logTail)+ guard f.kind != .unknown else { failure = nil; return }+ failure = f+ doneNote = failureWhat(f)+ }++ /// The first sentence of a failure's hint (it names the game of a 32-bit program when the message does).+ func failureWhat(_ f: BuildFailure) -> String {+ if f.kind == .a32Program, let name = f.gameName { return String(format: t("fail.a32Program.whatNamed"), name) }+ return t(f.kind.whatKey)+ }++ /// "Build anyway": asks first. Nothing is armed until `confirmBuildAnyway`.+ func requestBuildAnyway() {+ guard !running, let kind = failure?.kind, kind.overrideFlag != nil else { return }+ confirmingOverride = kind+ }++ func cancelBuildAnyway() { confirmingOverride = nil }++ func confirmBuildAnyway() {+ guard let kind = confirmingOverride else { return }+ confirmingOverride = nil+ armedOverride = kind+ startBuild()+ }++ /// The flag the next build runs with, once: the arm is cleared here, so a later build never inherits it.+ func takeOverrideFlag() -> String? {+ defer { armedOverride = nil }+ return armedOverride?.overrideFlag+ }++ /// The card's fix buttons run the dependency rows' own commands (the same installDep as Settings).+ func fixBuildFailure(_ kind: BuildFailureKind) {+ switch kind {+ case .translator:+ if let d = deps.first(where: { $0.id == "dotnet" }) { installDep(d) }+ case .iosSDK:+ installDep(Dep(id: "xcode", name: "dep.xcode", hint: "dep.xcode.hint", present: false, installCmd: Self.iosPlatformCmd))+ case .cltSelected:+ if let xcode = Self.installedXcode() {+ installDep(Dep(id: "xcode", name: "dep.xcode", hint: "dep.xcode.hint", present: false, installCmd: Self.selectXcodeCmd(xcode)))+ }+ default: break+ }+ }++ /// Whether the card's fix button is already running its command.+ func fixBusy(_ kind: BuildFailureKind) -> Bool {+ deps.first { $0.id == (kind == .translator ? "dotnet" : "xcode") }?.installing ?? false+ }+/// (file count, bytes) of a RomFS tree — the reuse fingerprint's content part.nonisolated static func treeStats(_ dir: String) -> (count: Int, bytes: Int)? {let fm = FileManager.default@@ -2033,6 +2102,7 @@ final class BuildModel: ObservableObject {var lastError = "" // the tool's own first error line after a failed install (brew's, pip's)var fixHint = "" // an L10n key: what to type or click, chosen from that linevar actionLabel = "" // an L10n key for the button when the action is not a plain install ("Fix")+ var warning = false // present, but with a caveat the row's error and hint lines explain (the Metal compiler is not the tested one)let installCmd: [String] // run via bash; empty = manual (Xcode from the App Store)}@@ -2323,6 +2393,14 @@ final class BuildModel: ObservableObject {nonisolated static let metalToolchainCmd = ["/usr/bin/xcodebuild", "-downloadComponent", "MetalToolchain"]nonisolated static let iosPlatformCmd = ["/usr/bin/xcodebuild", "-downloadPlatform", "iOS"]+ /// One admin prompt runs both steps: switch the toolchain to this Xcode, then let it finish its first launch (license and+ /// components) - a fresh App Store download has neither. The Xcode row and the failure card run the same command.+ nonisolated static func selectXcodeCmd(_ xcode: String) -> [String] {+ let script = "xcode-select -s '" + xcode + "/Contents/Developer' && xcodebuild -runFirstLaunch"+ let apple = "do shell script \"" + script.replacingOccurrences(of: "\"", with: "\\\"") + "\" with administrator privileges"+ return ["/usr/bin/osascript", "-e", apple]+ }+/// Whether the xcode row asks for the iOS SDK. Always, as before, unless the guided setup stored a Mac-only choice/// and builds are for the Mac: upstream no longer needs the iOS SDK for a Mac build (c464cb24).nonisolated static func needsIOSPlatform(defaults: UserDefaults = .standard) -> Bool {@@ -2356,7 +2434,34 @@ final class BuildModel: ObservableObject {"NONINTERACTIVE=1 /bin/bash -c \"$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)\""])] + rows}- nonisolated static func detectDepsSync(needsIOS: Bool = BuildModel.needsIOSPlatform()) -> [Dep] {+ /// First line of a tool's output (the Metal compiler's version line), nil when it does not run or says nothing.+ nonisolated static func firstOutputLine(_ tool: String, _ args: [String]) -> String? {+ let p = Process()+ p.executableURL = URL(fileURLWithPath: tool)+ p.arguments = args+ let out = Pipe()+ p.standardOutput = out; p.standardError = Pipe(); p.standardInput = FileHandle.nullDevice+ do { try p.run() } catch { return nil }+ let data = out.fileHandleForReading.readDataToEndOfFile()+ p.waitUntilExit()+ guard p.terminationStatus == 0 else { return nil }+ return String(decoding: data, as: UTF8.self).split(separator: "\n", omittingEmptySubsequences: true).first.map(String.init)+ }++ /// The Metal toolchain row. A compiler that does not run is the missing-toolchain row with its install button. One that differs from the+ /// lock's pin is a warning and not a blocker: the row stays present, and its error and hint lines (the install failures' fields) say that+ /// NVN games will stop. Pure over its inputs, so tests give it version strings.+ nonisolated static func metalDep(runs: Bool, lock: String?, now: [String: String?], needsIOS: Bool) -> Dep {+ var dep = Dep(id: "metal", name: "dep.metal", hint: "dep.metal.hint", present: runs, installCmd: metalToolchainCmd)+ guard runs, let lock, let m = MetalPin.mismatches(lock: lock, now: now, iOS: needsIOS).first else { return dep }+ dep.warning = true+ dep.detail = "dep.metal.other:" + m.now + ":" + m.pinned+ dep.lastError = "metal_" + m.sdk + ": " + m.now+ dep.fixHint = "dep.fix.metalPin"+ return dep+ }++ nonisolated static func detectDepsSync(needsIOS: Bool = BuildModel.needsIOSPlatform(), repo: String = "") -> [Dep] {var out: [Dep] = []// Xcode.app alone is not enough: since Xcode 15 the iOS platform ships as a separate@@ -2376,20 +2481,17 @@ final class BuildModel: ObservableObject {out.append(Dep(id: "xcode", name: "dep.xcode", hint: "dep.xcode.hint", present: false,detail: "dep.xcode.noSDK", installCmd: iosPlatformCmd))case .commandLineToolsOnly(let xcode):- // One admin prompt runs both steps: switch the toolchain, then let Xcode finish its- // first launch (license and components) - a fresh App Store download has neither.- let script = "xcode-select -s '" + xcode + "/Contents/Developer' && xcodebuild -runFirstLaunch"- let apple = "do shell script \"" + script.replacingOccurrences(of: "\"", with: "\\\"") + "\" with administrator privileges"out.append(Dep(id: "xcode", name: "dep.xcode", hint: "dep.xcode.hint", present: false,detail: "dep.xcode.notSelected", actionLabel: "dep.xcode.fix",- installCmd: ["/usr/bin/osascript", "-e", apple]))+ installCmd: selectXcodeCmd(xcode)))case .notInstalled:out.append(Dep(id: "xcode", name: "dep.xcode", hint: "dep.xcode.hint", present: false, installCmd: []))}- let mt = runOK("/usr/bin/xcrun", ["-sdk", "macosx", "metal", "--version"])- out.append(Dep(id: "metal", name: "dep.metal", hint: "dep.metal.hint",- present: mt, installCmd: metalToolchainCmd))+ let macMetal = firstOutputLine("/usr/bin/xcrun", ["-sdk", "macosx", "metal", "--version"])+ let lock = repo.isEmpty ? nil : try? String(contentsOfFile: repo + "/" + MetalPin.lockPath, encoding: .utf8)+ let iosMetal = needsIOS && lock != nil ? firstOutputLine("/usr/bin/xcrun", ["-sdk", "iphoneos", "metal", "--version"]) : nil+ out.append(metalDep(runs: macMetal != nil, lock: lock, now: ["macosx": macMetal, "iphoneos": iosMetal], needsIOS: needsIOS))out += toolDeps(resources: BundledTools.resources,installed: { firstExisting(["/opt/homebrew/bin/\($0)", "/usr/local/bin/\($0)"]) },@@ -2422,7 +2524,7 @@ final class BuildModel: ObservableObject {func checkDeps() {depsChecked = falseDispatchQueue.global(qos: .userInitiated).async {- let d = Self.detectDepsSync()+ let d = Self.detectDepsSync(repo: self.repoPath)let (py, _) = Self.findPython()let (dn, _) = Self.findDotnet()DispatchQueue.main.async {@@ -2687,6 +2789,7 @@ struct BuilderView: View {if m.target != "mac-app" { install.disabled(m.running) }logPanelaction+ BuildFailureCard(m: m)outcomeprogress}@@ -3166,7 +3269,7 @@ struct BuilderView: View {ForEach(m.deps, id: \.id) { d individerVStack(alignment: .leading, spacing: 0) {- row(m.t(d.name), detail: m.shortPath(m.depDetail(d)), dot: d.present ? LauncherPalette.ready : LauncherPalette.building,+ row(m.t(d.name), detail: m.shortPath(m.depDetail(d)), dot: d.present && !d.warning ? LauncherPalette.ready : LauncherPalette.building,help: m.t(d.hint)) {if d.installing {ProgressView().controlSize(.small)diff --git a/frontend/Sources/NSPortBuilder/Localization.swift b/frontend/Sources/NSPortBuilder/Localization.swiftindex bfa70f4a..87720cb7 100644--- a/frontend/Sources/NSPortBuilder/Localization.swift+++ b/frontend/Sources/NSPortBuilder/Localization.swift@@ -789,6 +789,68 @@ enum L10n {"Build failed (exit code %d) — see the log below"),"msg.buildFailedReason": ("构建失败,见下方日志。最后一行:%@","Build failed — see the log below. Last line: %@"),+ "fail.section": ("构建为何停止",+ "Why the build stopped"),+ "fail.rosetta.what": ("构建脚本用的是在 Rosetta 下运行的 Intel 版 Python,它启动的工具也会按 Intel 代码运行。",+ "The build script ran with an Intel Python under Rosetta, so the tools it starts would run as Intel code too."),+ "fail.rosetta.next": ("NS Port Builder 有自带的 Python 时会优先使用它。如果这次用的是别的,请删除 ~/Library/Application Support/NS Port Builder/venv 里的 Intel 虚拟环境,再点「重新检测」。",+ "NS Port Builder uses its bundled Python when it has one. If this build used another, remove the Intel venv in ~/Library/Application Support/NS Port Builder/venv and press Check again."),+ "fail.translator.what": ("着色器翻译器无法运行,它需要适合这台 Mac 架构的 .NET 10 运行时。",+ "The shader translator does not run. It needs the .NET 10 runtime for this Mac's architecture."),+ "fail.translator.next": ("用下面的按钮重新安装 .NET,然后再构建。如果环境变量 DOTNET_ROOT 指向了别的运行时,请取消设置。",+ "Reinstall .NET with the button below, then build again. If DOTNET_ROOT names another runtime, unset it."),+ "fail.translator.button": ("重新安装 .NET",+ "Reinstall .NET"),+ "fail.iosSDK.what": ("没有安装 iOS SDK,构建 iPhone 版本需要它。",+ "The iOS SDK is not installed. An iPhone build needs it."),+ "fail.iosSDK.next": ("打开 Xcode → 设置 → 组件,安装 iOS,或者点下面的按钮运行 xcodebuild -downloadPlatform iOS。",+ "Open Xcode → Settings → Components and install iOS, or press the button to run xcodebuild -downloadPlatform iOS."),+ "fail.iosSDK.button": ("下载 iOS 平台",+ "Download iOS platform"),+ "fail.cltSelected.what": ("当前选中的是命令行工具而不是 Xcode,而命令行工具没有 iOS SDK。",+ "The Command Line Tools are selected instead of Xcode, and they have no iOS SDK."),+ "fail.cltSelected.next": ("用下面的按钮选择 Xcode(会要管理员密码),或者在终端运行 sudo xcode-select -s /Applications/Xcode.app,然后再构建。",+ "Select Xcode with the button below (it asks for an administrator password), or run sudo xcode-select -s /Applications/Xcode.app in Terminal, then build again."),+ "fail.cltSelected.button": ("选择 Xcode",+ "Select Xcode"),+ "fail.otherMetal.what": ("这台 Mac 的 Metal 编译器不是着色器测试时用的那一个。",+ "This Mac's Metal compiler is not the one the shaders were tested with."),+ "fail.otherMetal.next": ("这个游戏使用 NVN,需要 Xcode 27.1(macOS 26.6 或更新)。请安装它和它的 Metal 工具链,然后再构建。",+ "This game uses NVN and needs Xcode 27.1 (macOS 26.6 or later). Install it and its Metal toolchain, then build again."),+ "fail.otherMetal.risk": ("会用没有测试过的 Metal 编译器构建。画面可能出错,结果也没有人测试过,不受支持。这个选择只对这一次构建有效,不会保存。",+ "This builds with a Metal compiler nobody tested the shaders with. The pictures can come out wrong, the result is untested and it is not supported. The choice applies to this one build and is not saved."),+ "fail.shaderRegression.what": ("有些以前能翻译的着色器,在这个版本里翻译失败了。",+ "Some shaders that translated before fail to translate with this version."),+ "fail.shaderRegression.next": ("请带上构建日志里的列表去报告这个问题。「仍然构建」会把这些着色器留空,所以画面可能缺少一部分。",+ "Please report it with the list in the build log. Building anyway leaves those shaders out, so parts of the picture may be missing."),+ "fail.shaderRegression.risk": ("会在没有这些着色器的情况下打包。画面可能缺少一部分,结果也没有人测试过。这个选择只对这一次构建有效,不会保存。",+ "This packs the app without those shaders. Parts of the picture may be missing and the result is untested. The choice applies to this one build and is not saved."),+ "fail.damagedNSP.what": ("游戏文件已损坏,没有通过 NCA 的哈希校验,常见原因是复制不完整或下载中断。",+ "The game file is damaged. It fails the hash check, often from an incomplete copy or a broken download."),+ "fail.damagedNSP.next": ("请重新导出或重新下载这个文件。「仍然构建」会按读到的样子写出损坏的文件,游戏可能因此出错。",+ "Dump or download the file again. Building anyway writes the damaged files as they are, which may break the game."),+ "fail.damagedNSP.risk": ("会把损坏的文件按读到的样子写出。游戏可能崩溃或显示错误的数据,结果也没有人测试过。这个选择只对这一次构建有效,不会保存。",+ "This writes the damaged files as they are. The game may crash or show wrong data, and the result is untested. The choice applies to this one build and is not saved."),+ "fail.a32Program.what": ("这个版本是 32 位的,无法在 Apple 芯片上运行。",+ "This version is 32-bit and can't run on Apple silicon."),+ "fail.a32Program.whatNamed": ("%@ 的这个版本是 32 位的,无法在 Apple 芯片上运行。",+ "This version of %@ is 32-bit and can't run on Apple silicon."),+ "fail.a32Program.next": ("请选择游戏配置里列出的那个更新版本。",+ "Pick the update the profile lists."),+ "fail.buildAnyway": ("仍然构建…",+ "Build anyway…"),+ "fail.confirm.title": ("仍然构建?",+ "Build anyway?"),+ "fail.confirm.go": ("仍然构建",+ "Build anyway"),+ "fail.confirm.cancel": ("取消",+ "Cancel"),+ "fail.override.note": ("仍然构建:这一次构建加上 %@(已确认,不会保存)",+ "Build anyway: this build adds %@ (confirmed, not saved)"),+ "dep.metal.other": ("%@(测试用的是 %@)",+ "%@ (tested: %@)"),+ "dep.fix.metalPin": ("这不是着色器测试时用的 Metal 编译器。使用 NVN 的游戏会在着色器步骤前停下。请安装 Xcode 27.1(macOS 26.6 或更新)和它的 Metal 工具链。",+ "This is not the Metal compiler the shaders were tested with. Games that use NVN stop before the shader steps. Install Xcode 27.1 (macOS 26.6 or later) and its Metal toolchain."),"msg.exitCode": ("退出码 %d", "exit code %d"),"msg.stagingFailed": ("无法在暂存文件夹里建立链接(文件在不同磁盘?)","Could not create links in the staging folder (files on different volumes?)"),diff --git a/frontend/Tests/Fixtures/build_failures.json b/frontend/Tests/Fixtures/build_failures.jsonnew file mode 100644index 00000000..c0966742--- /dev/null+++ b/frontend/Tests/Fixtures/build_failures.json@@ -0,0 +1,66 @@+[+ {+ "id": "rosetta.intel",+ "kind": "rosetta",+ "source": "scripts/build_ipa_from_nsp.py",+ "fragment": "is an Intel one running under Rosetta",+ "text": "[RED] this Python (/usr/local/bin/python3) is an Intel one running under Rosetta, and the tools it starts would run as Intel code too: run the script with an arm64 Python (/usr/bin/python3, or Homebrew's in /opt/homebrew)"+ },+ {+ "id": "translator.run",+ "kind": "translator",+ "source": "scripts/build_ipa_from_nsp.py",+ "fragment": "the shader translator does not run (",+ "text": "[RED] the shader translator does not run (You must install .NET to run this application.): it needs the .NET 10 runtime for this Mac's architecture (brew install --cask dotnet-sdk); unset DOTNET_ROOT if it names another one"+ },+ {+ "id": "translator.start",+ "kind": "translator",+ "source": "scripts/build_ipa_from_nsp.py",+ "fragment": "the shader translator does not start (",+ "text": "[RED] the shader translator does not start ([Errno 8] Exec format error: '/r/dm/gfx/tools/dmsh_xlate_bin'): /r/dm/gfx/tools/dmsh_xlate_bin"+ },+ {+ "id": "ios.sdk",+ "kind": "iosSDK",+ "source": "scripts/build_ipa_from_nsp.py",+ "fragment": "the iOS SDK is not installed",+ "text": "[RED] the iOS SDK is not installed: install the iOS platform in Xcode → Settings → Components, or with xcodebuild -downloadPlatform iOS"+ },+ {+ "id": "clt.selected",+ "kind": "cltSelected",+ "source": "scripts/build_ipa_from_nsp.py",+ "fragment": "the selected developer folder is the Command Line Tools",+ "text": "[RED] the selected developer folder is the Command Line Tools (/Library/Developer/CommandLineTools), which have no iOS SDK: select Xcode with sudo xcode-select -s /Applications/Xcode.app"+ },+ {+ "id": "metal.other",+ "kind": "otherMetal",+ "source": "dm/gfx/tools/own_compilers.py",+ "fragment": "Metal compiler is not the one the shaders were tested with",+ "text": "[RED] this Mac's Metal compiler is not the one the shaders were tested with (dm/gfx/tools/dmsh_chain.lock): metal_macosx Apple metal version 32023.883 (metalfe-32023.883.5) (tested: Apple metal version 32023.921 (metalfe-32023.921.6)). Untested compilers are unsupported (GitHub issue #242). Install Xcode 27.1 (macOS 26.6 or later) and its Metal toolchain (xcodebuild -downloadComponent MetalToolchain), or set ALLOW_OTHER_METAL = True (--allow-other-metal) to build with this one anyway"+ },+ {+ "id": "shaders.regression",+ "kind": "shaderRegression",+ "source": "scripts/build_ipa_from_nsp.py",+ "fragment": "a change to the translation chain broke them",+ "text": "[RED] 3 shaders that translated in b-1a2b3c fail in b-4d5e6f: a change to the translation chain broke them (list: /w/logs/shader_regressions.log). Please report it at https://github.com/seedds/nxnative/issues with that list; ALLOW_SHADER_REGRESSIONS = True (--allow-shader-regressions) packs the app without those shaders"+ },+ {+ "id": "nsp.damaged",+ "kind": "damagedNSP",+ "source": "dm/tools/nx_extract/Program.cs",+ "fragment": "files fail the NCA's hash check",+ "text": "[RED] hash check failed: ExeFS/main\n[RED] the NSP is damaged: 1 files fail the NCA's hash check (an incomplete copy or a broken download); copy or download it again, or pass --allow-damaged to write them as read\n[RED] nx_extract exit code 3 (full output: /w/logs/extract.log)"+ },+ {+ "id": "arm32.program",+ "kind": "a32Program",+ "source": "scripts/build_ipa_from_nsp.py",+ "fragment": "is a 32-bit ARM program",+ "game": "Some Game",+ "text": "[RED] Some Game (0100ABCD00000000) is a 32-bit ARM program (main.npdm: the 64-bit instruction flag is clear): Apple silicon cannot run 32-bit ARM code, and this repository runs a game's own AArch64 code, so it cannot be ported"+ }+]\ No newline at end of filediff --git a/frontend/Tests/NSPortBuilderTests/BuildFailureTests.swift b/frontend/Tests/NSPortBuilderTests/BuildFailureTests.swiftnew file mode 100644index 00000000..1a696c74--- /dev/null+++ b/frontend/Tests/NSPortBuilderTests/BuildFailureTests.swift@@ -0,0 +1,288 @@+import SwiftUI+import XCTest+@testable import NSPortBuilder++/// The script's early stops, turned into hints. The fixture holds the real message of every pattern, copied from the script+/// (Tests/Fixtures/build_failures.json, shared with the Qt front end's test).+final class BuildFailureTests: XCTestCase {+ struct Fixture: Decodable {+ let id: String, kind: String, source: String, fragment: String, text: String+ let game: String?+ }++ static let root = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent()+ .deletingLastPathComponent().deletingLastPathComponent() // the repository root++ func fixtures() throws -> [Fixture] {+ let url = Self.root.appendingPathComponent("frontend/Tests/Fixtures/build_failures.json")+ return try JSONDecoder().decode([Fixture].self, from: Data(contentsOf: url))+ }++ func testEveryPatternHasItsRealMessageAndMatchesIt() throws {+ let fx = try fixtures()+ for row in BuildFailureClassifier.table {+ let f = try XCTUnwrap(fx.first { $0.id == row.id }, "no fixture for pattern \(row.id)")+ XCTAssertEqual(f.kind, row.kind.rawValue, row.id)+ XCTAssertNotNil(f.text.range(of: row.pattern, options: .regularExpression), "\(row.id) no longer matches its message")+ XCTAssertEqual(BuildFailureClassifier.classify(f.text).kind, row.kind, row.id)+ }+ XCTAssertEqual(Set(fx.map(\.id)), Set(BuildFailureClassifier.table.map(\.id)), "a fixture without a pattern")+ }++ func testEveryKindIsReachable() {+ let kinds = Set(BuildFailureClassifier.table.map(\.kind))+ for k in BuildFailureKind.allCases where k != .unknown { XCTAssertTrue(kinds.contains(k), "\(k)") }+ }++ /// A sync of scripts/ or dm/ that rewords a message must fail here, not turn a hint into the raw last line.+ func testTheVendoredScriptsStillSayWhatThePatternsExpect() throws {+ for f in try fixtures() {+ let source = try String(contentsOf: Self.root.appendingPathComponent(f.source), encoding: .utf8)+ let there = source.contains(f.fragment)+ XCTAssertTrue(there, "\(f.id): \(f.source) no longer contains \"\(f.fragment)\": update the pattern and the fixture")+ }+ }++ func testTheFailureIsFoundAboveTheLastLine() {+ let log = "[3/9] extract\n[RED] the NSP is damaged: 2 files fail the NCA's hash check (x)\n---- last lines of /w/extract.log ----\n[RED] nx_extract exit code 3 (full output: /w/extract.log)\n"+ XCTAssertEqual(BuildFailureClassifier.classify(log).kind, .damagedNSP)+ }++ func testUnknownOutputKeepsTodaysBehaviour() {+ for log in ["", "something odd happened", "[RED] the RomFS image failed",+ "[RED] the NSP is damaged: 3 files written as read (--allow-damaged)"] { // the success note of a build that went on+ XCTAssertEqual(BuildFailureClassifier.classify(log), BuildFailure(kind: .unknown, gameName: nil), log)+ }+ }++ func testTheGameOfA32BitProgramIsNamedWhenTheMessageNamesIt() throws {+ let f = try XCTUnwrap(fixtures().first { $0.id == "arm32.program" })+ XCTAssertEqual(BuildFailureClassifier.classify(f.text).gameName, f.game)+ XCTAssertNil(BuildFailureClassifier.classify("[RED] ? (0100ABCD00000000) is a 32-bit ARM program (main.npdm)").gameName)+ XCTAssertNil(BuildFailureClassifier.classify("[RED] the shader translator does not run (x)").gameName)+ }++ // ---- hints++ func testOnlyThreeStopsOfferBuildAnyway() {+ let flags = Dictionary(uniqueKeysWithValues: BuildFailureKind.allCases.compactMap { k in k.overrideFlag.map { (k, $0) } })+ XCTAssertEqual(flags, [.otherMetal: "--allow-other-metal", .shaderRegression: "--allow-shader-regressions", .damagedNSP: "--allow-damaged"])+ }++ func testEveryHintIsInBothLanguagesWithoutSemicolons() {+ var keys = ["fail.section", "fail.buildAnyway", "fail.confirm.title", "fail.confirm.go", "fail.confirm.cancel", "fail.override.note",+ "fail.a32Program.whatNamed", "fail.translator.button", "fail.iosSDK.button", "fail.cltSelected.button",+ "dep.metal.other", "dep.fix.metalPin"]+ for k in BuildFailureKind.allCases where k != .unknown {+ keys += [k.whatKey, k.nextKey]+ if k.overrideFlag != nil { keys.append("fail.\(k.rawValue).risk") }+ }+ for key in keys {+ let row = L10n.table[key]+ XCTAssertNotNil(row, key)+ for text in [row?.zh ?? "", row?.en ?? ""] {+ XCTAssertFalse(text.isEmpty, key)+ XCTAssertFalse(text.contains(";") || text.contains("\u{FF1B}"), "\(key) has a semicolon")+ }+ XCTAssertNotEqual(row?.zh, row?.en, "\(key) has the English text twice")+ }+ }++ func testTheRiskTextStatesTheRiskAndThatItIsOneBuild() {+ for k in [BuildFailureKind.otherMetal, .shaderRegression, .damagedNSP] {+ let en = L10n.table["fail.\(k.rawValue).risk"]?.en ?? ""+ XCTAssertTrue(en.contains("untested"), "\(k)")+ XCTAssertTrue(en.contains("one build"), "\(k)")+ }+ }++ func testTheOtherMetalHintNamesXcode27() {+ XCTAssertTrue(L10n.table["fail.otherMetal.next"]!.en.contains("Xcode 27.1 (macOS 26.6 or later)"))+ XCTAssertTrue(L10n.table["fail.a32Program.what"]!.en.contains("32-bit and can't run on Apple silicon"))+ }++ // ---- the flag of "Build anyway"++ func testTheBuildArgumentsGetExactlyOneAllowFlag() {+ let base = ["/r/scripts/build_ipa_from_nsp.py", "/in", "-k", "/k", "--progress", "json"]+ XCTAssertEqual(BuildFailureClassifier.arguments(base, adding: nil), base)+ for k in [BuildFailureKind.otherMetal, .shaderRegression, .damagedNSP] {+ let args = BuildFailureClassifier.arguments(base, adding: k.overrideFlag)+ XCTAssertEqual(args.filter { $0.hasPrefix("--allow-") }, [k.overrideFlag!])+ XCTAssertEqual(Array(args.dropLast()), base)+ }+ XCTAssertEqual(BuildFailureClassifier.arguments(base + ["--allow-damaged"], adding: "--allow-other-metal").filter { $0.hasPrefix("--allow-") }, ["--allow-other-metal"])+ XCTAssertEqual(BuildFailureClassifier.arguments(base, adding: "--platform").count, base.count, "not an override")+ }++ func testNothingIsArmedUntilTheConfirmation() {+ let m = BuildModel()+ m.failure = BuildFailure(kind: .otherMetal, gameName: nil)+ m.requestBuildAnyway()+ XCTAssertEqual(m.confirmingOverride, .otherMetal)+ XCTAssertNil(m.armedOverride)+ XCTAssertNil(m.takeOverrideFlag())+ m.cancelBuildAnyway()+ XCTAssertNil(m.confirmingOverride)+ XCTAssertNil(m.armedOverride)+ }++ func testAConfirmedOverrideServesOneBuildOnly() {+ let m = BuildModel()+ m.failure = BuildFailure(kind: .damagedNSP, gameName: nil)+ m.requestBuildAnyway()+ m.confirmBuildAnyway() // starts a build: with no repository it stops at once, after taking the flag+ XCTAssertNil(m.armedOverride, "the build took it")+ XCTAssertNil(m.confirmingOverride)+ XCTAssertNil(m.takeOverrideFlag(), "the next build runs without it")+ XCTAssertNil(m.failure, "a new build clears the old stop")+ }++ func testAStopWithoutAnOverrideCannotBeBuiltAnyway() {+ let m = BuildModel()+ for k in [BuildFailureKind.rosetta, .translator, .iosSDK, .cltSelected, .a32Program] {+ m.failure = BuildFailure(kind: k, gameName: nil)+ m.requestBuildAnyway()+ XCTAssertNil(m.confirmingOverride, "\(k)")+ }+ }++ func testAFailedBuildShowsTheHintInsteadOfTheLastLine() {+ let m = BuildModel()+ m.logTail = "[RED] the iOS SDK is not installed: install the iOS platform in Xcode\n"+ m.noteFailure()+ XCTAssertEqual(m.failure?.kind, .iosSDK)+ XCTAssertEqual(m.doneNote, m.t(BuildFailureKind.iosSDK.whatKey))+ m.logTail = "[RED] something else\n"; m.doneNote = "last line"+ m.noteFailure()+ XCTAssertNil(m.failure)+ XCTAssertEqual(m.doneNote, "last line", "unknown output keeps the note")+ }++ // ---- the Metal compiler row++ static let lock = "# fingerprints\ndmsh_xlate.dll\tdbc483247a4cb22d\nmetal_macosx\tApple metal version 32023.921 (metalfe-32023.921.6)\nmetal_iphoneos\tApple metal version 32023.921 (metalfe-32023.921.6)\n"+ static let pinned = "Apple metal version 32023.921 (metalfe-32023.921.6)"+ static let other = "Apple metal version 32023.883 (metalfe-32023.883.5)"++ func testThePinIsReadFromTheLock() {+ XCTAssertEqual(MetalPin.pins(lock: Self.lock)["metal_macosx"], Self.pinned)+ XCTAssertEqual(MetalPin.pins(lock: Self.lock)["metal_iphoneos"], Self.pinned)+ XCTAssertNil(MetalPin.pins(lock: Self.lock)["# fingerprints"])+ }++ func testTheRepositorysOwnLockHasTheTwoPins() throws {+ let lock = try String(contentsOf: Self.root.appendingPathComponent(MetalPin.lockPath), encoding: .utf8)+ XCTAssertNotNil(MetalPin.pins(lock: lock)["metal_macosx"])+ XCTAssertNotNil(MetalPin.pins(lock: lock)["metal_iphoneos"])+ }++ func testTheTestedCompilerIsNoWarning() {+ let dep = BuildModel.metalDep(runs: true, lock: Self.lock, now: ["macosx": Self.pinned, "iphoneos": Self.pinned], needsIOS: true)+ XCTAssertTrue(dep.present)+ XCTAssertFalse(dep.warning)+ XCTAssertTrue(dep.lastError.isEmpty)+ }++ func testAnotherCompilerIsAWarningAndNotABlocker() {+ let dep = BuildModel.metalDep(runs: true, lock: Self.lock, now: ["macosx": Self.other, "iphoneos": nil], needsIOS: false)+ XCTAssertTrue(dep.present, "a warning never blocks")+ XCTAssertTrue(dep.warning)+ XCTAssertEqual(dep.fixHint, "dep.fix.metalPin")+ XCTAssertEqual(dep.lastError, "metal_macosx: " + Self.other)+ XCTAssertEqual(dep.detail, "dep.metal.other:" + Self.other + ":" + Self.pinned)+ }++ func testTheIPhoneCompilerCountsOnlyForAnIPhoneBuild() {+ let now: [String: String?] = ["macosx": Self.pinned, "iphoneos": Self.other]+ XCTAssertFalse(BuildModel.metalDep(runs: true, lock: Self.lock, now: now, needsIOS: false).warning)+ let ios = BuildModel.metalDep(runs: true, lock: Self.lock, now: now, needsIOS: true)+ XCTAssertTrue(ios.warning)+ XCTAssertTrue(ios.lastError.hasPrefix("metal_iphoneos:"))+ }++ func testAMissingCompilerKeepsTheInstallRow() {+ let dep = BuildModel.metalDep(runs: false, lock: Self.lock, now: ["macosx": nil, "iphoneos": nil], needsIOS: true)+ XCTAssertFalse(dep.present)+ XCTAssertFalse(dep.warning)+ XCTAssertEqual(dep.installCmd, BuildModel.metalToolchainCmd)+ }++ func testWithoutALockThereIsNothingToCompare() {+ XCTAssertFalse(BuildModel.metalDep(runs: true, lock: nil, now: ["macosx": Self.other], needsIOS: true).warning)+ XCTAssertTrue(MetalPin.mismatches(lock: "", now: ["macosx": Self.other], iOS: true).isEmpty)+ }++ func testTheMetalRowsDetailReadsInTheLauncher() {+ let m = BuildModel()+ let dep = BuildModel.metalDep(runs: true, lock: Self.lock, now: ["macosx": Self.other], needsIOS: false)+ XCTAssertTrue(m.depDetail(dep).contains(Self.other), m.depDetail(dep))+ XCTAssertTrue(m.depDetail(dep).contains(Self.pinned), m.depDetail(dep))+ }++ /// Opt-in native rendering for pull request screenshots (NX_LAUNCHER_CAPTURE_DIR), the way LibraryTests renders the launcher.+ @MainActor func testRenderBuildFailureStatesForScreenshots() throws {+ guard let directory = ProcessInfo.processInfo.environment["NX_LAUNCHER_CAPTURE_DIR"] else { throw XCTSkip("Set NX_LAUNCHER_CAPTURE_DIR to capture native views") }+ let output = URL(fileURLWithPath: directory)+ try FileManager.default.createDirectory(at: output, withIntermediateDirectories: true)+ let app = NSApplication.shared+ app.setActivationPolicy(.accessory)+ func capture(_ name: String, width: CGFloat, height: CGFloat, _ view: some View) throws {+ let host = NSHostingView(rootView: view.preferredColorScheme(.dark).frame(width: width, height: height))+ let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: width, height: height), styleMask: [.titled], backing: .buffered, defer: false)+ window.contentView = host+ window.appearance = NSAppearance(named: .darkAqua)+ window.orderFront(nil)+ RunLoop.main.run(until: Date().addingTimeInterval(0.4))+ host.layoutSubtreeIfNeeded()+ let rep = try XCTUnwrap(host.bitmapImageRepForCachingDisplay(in: host.bounds))+ host.cacheDisplay(in: host.bounds, to: rep)+ try XCTUnwrap(rep.representation(using: .png, properties: [:])).write(to: output.appendingPathComponent(name + ".png"))+ window.orderOut(nil)+ }+ for (name, kind, lang) in [("hint-other-metal", BuildFailureKind.otherMetal, Lang.en), ("hint-ios-sdk", .iosSDK, .en), ("hint-damaged-nsp", .damagedNSP, .en),+ ("hint-other-metal-zh", .otherMetal, .zh)] {+ let m = BuildModel()+ m.lang = lang+ m.failure = BuildFailure(kind: kind, gameName: nil)+ m.doneNote = m.failureWhat(m.failure!)+ try capture(name, width: 760, height: 250, ZStack(alignment: .top) {+ LauncherPalette.background+ BuildFailureCard(m: m).padding(24)+ })+ }+ let m = BuildModel()+ m.lang = .en+ m.depsChecked = true+ m.deps = [BuildModel.Dep(id: "xcode", name: "dep.xcode", hint: "dep.xcode.hint", present: true, installCmd: []),+ BuildModel.metalDep(runs: true, lock: Self.lock, now: ["macosx": Self.other, "iphoneos": Self.other], needsIOS: true)]+ try capture("deps-metal-warning", width: 760, height: 260, ZStack(alignment: .top) {+ LauncherPalette.background+ MetalRowPreview(m: m).padding(24)+ })+ }+}++/// The dependency panel's rows as the Settings card draws them, for the screenshot (the card itself is private to BuilderView).+private struct MetalRowPreview: View {+ @ObservedObject var m: BuildModel+ var body: some View {+ VStack(alignment: .leading, spacing: 0) {+ ForEach(m.deps, id: \.id) { d in+ HStack(alignment: .top, spacing: 12) {+ Circle().fill(d.present && !d.warning ? LauncherPalette.ready : LauncherPalette.building).frame(width: 7, height: 7).padding(.top, 6)+ VStack(alignment: .leading, spacing: 3) {+ Text(m.t(d.name)).font(.manrope(14, .semibold))+ Text(m.depDetail(d)).font(.manrope(12.5)).foregroundStyle(.secondary)+ if !d.lastError.isEmpty {+ Text(d.lastError).font(.mono(11)).foregroundStyle(LauncherPalette.building)+ Text(m.t(d.fixHint)).font(.manrope(11.5)).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)+ }+ }+ Spacer()+ }.padding(.vertical, 10).padding(.horizontal, 18)+ }+ }+ .background(LauncherPalette.surface.opacity(0.75), in: RoundedRectangle(cornerRadius: 14))+ }+}