Skip to content

Play your own Switch games on iPhone/iPad — one-click macOS app, no terminal. | 把 Switch 游戏装进 iPhone:图形界面一键构建,不用命令行。Bring your own game.

A failed build says what failed, and shows the log it points at (issue #52)

LNPANDYdc65dbab08ed
diff --git a/frontend-qt/nspb_qt/localization.py b/frontend-qt/nspb_qt/localization.py
index 7ca373ee..0f6bcb09 100644
--- a/frontend-qt/nspb_qt/localization.py
+++ b/frontend-qt/nspb_qt/localization.py
@@ -280,6 +280,7 @@ TABLE: dict[str, tuple[str, str]] = {
'msg.nszFailed': ('nsz 安装失败(构建用的 Python:%@)——网络不通?或手动执行 pip install nsz', 'Could not install nsz (build Python: %@) — network trouble? Or run pip install nsz by hand'),
'msg.stopped': ('已停止', 'Stopped'),
'msg.buildFailed': ('构建失败(退出码 %d),见下方日志', 'Build failed (exit code %d) — see the log below'),
+ 'msg.buildFailedReason': ('构建失败,见下方日志。最后一行:%@', 'Build failed — see the log below. Last line: %@'),
'msg.exitCode': ('退出码 %d', 'exit code %d'),
'msg.stagingFailed': ('无法在暂存文件夹里建立链接(文件在不同磁盘?)', 'Could not create links in the staging folder (files on different volumes?)'),
'msg.launchFailed': ('无法启动构建脚本:%@', 'Could not start the build script: %@'),
@@ -293,6 +294,48 @@ TABLE: dict[str, tuple[str, str]] = {
'prog.archiveDone': ('游戏数据就绪:%@/romfs.img', 'game data ready: %@/romfs.img'),
'prog.archiveReused': ('复用上次的镜像(%d 个文件未变)', 'reused the previous image (%d files unchanged)'),
'msg.archiveReused': ('归档未变,复用 %@', 'archive unchanged, reusing %@'),
+ 'section.controls': ('操作', 'Controls'),
+ 'controls.settingsHint': ('适用于所有在 Mac 上运行的游戏。', 'Used by every game you play on this Mac.'),
+ 'controls.row': ('键盘与手柄', 'Keyboard and controller'),
+ 'controls.defaultLayout': ('默认布局', 'Default layout'),
+ 'controls.changes': ('已更改 %d 项', '%d changes'),
+ 'controls.customize': ('自定义…', 'Customize…'),
+ 'controls.title': ('操作', 'Controls'),
+ 'controls.note': ('每个游戏都使用这里的按键和手柄按钮。', 'The keys and controller buttons every game uses.'),
+ 'controls.sticks': ('键盘:摇杆和方向键', 'Keyboard: sticks and D-pad'),
+ 'controls.keyButtons': ('键盘:按钮', 'Keyboard: buttons'),
+ 'controls.pad': ('手柄:每个按钮发送的按键', 'Controller: what each button sends'),
+ 'controls.padNote': ('按钮按位置命名:右侧为 A,下方为 B,上方为 X,左侧为 Y。', 'Buttons are named by position: A on the right, B at the bottom, X at the top, Y on the left.'),
+ 'controls.applied': ('下次在这里按下“开始游戏”时生效。较早的构建会忽略这些设置。', 'Applied the next time you press Play here. Older builds ignore it.'),
+ 'controls.reset': ('恢复默认', 'Reset to defaults'),
+ 'controls.clear': ('不使用按键', 'No key'),
+ 'controls.press': ('请按一个键…', 'Press a key…'),
+ 'controls.none': ('无', 'None'),
+ 'controls.fn.LUp': ('左摇杆 上', 'Left stick up'),
+ 'controls.fn.LDown': ('左摇杆 下', 'Left stick down'),
+ 'controls.fn.LLeft': ('左摇杆 左', 'Left stick left'),
+ 'controls.fn.LRight': ('左摇杆 右', 'Left stick right'),
+ 'controls.fn.RUp': ('右摇杆 上', 'Right stick up'),
+ 'controls.fn.RDown': ('右摇杆 下', 'Right stick down'),
+ 'controls.fn.RLeft': ('右摇杆 左', 'Right stick left'),
+ 'controls.fn.RRight': ('右摇杆 右', 'Right stick right'),
+ 'controls.fn.Up': ('方向键 上', 'D-pad up'),
+ 'controls.fn.Down': ('方向键 下', 'D-pad down'),
+ 'controls.fn.Left': ('方向键 左', 'D-pad left'),
+ 'controls.fn.Right': ('方向键 右', 'D-pad right'),
+ 'controls.fn.A': ('A', 'A'),
+ 'controls.fn.B': ('B', 'B'),
+ 'controls.fn.X': ('X', 'X'),
+ 'controls.fn.Y': ('Y', 'Y'),
+ 'controls.fn.L': ('L', 'L'),
+ 'controls.fn.R': ('R', 'R'),
+ 'controls.fn.ZL': ('ZL', 'ZL'),
+ 'controls.fn.ZR': ('ZR', 'ZR'),
+ 'controls.fn.Plus': ('+', '+'),
+ 'controls.fn.Minus': ('−', '−'),
+ 'controls.fn.LS': ('按下左摇杆', 'Left stick press'),
+ 'controls.fn.RS': ('按下右摇杆', 'Right stick press'),
+ 'controls.fn.Shake': ('摇动手柄', 'Shake'),
'msg.archiveLog': ('归档:%@ → %@', 'Archive: %@ → %@'),
}
diff --git a/frontend-qt/nspb_qt/model.py b/frontend-qt/nspb_qt/model.py
index 1a5f6245..6aea490a 100644
--- a/frontend-qt/nspb_qt/model.py
+++ b/frontend-qt/nspb_qt/model.py
@@ -81,6 +81,7 @@ class Model(QObject):
self.stages: list[Stage] = []
self.running = False
self.log_tail = ''
+ self._last_error = '' # the last real log line: the failure note names it (issue #52)
self.game_dir = ''
self.base_path = ''
self.update_path = ''
@@ -972,6 +973,7 @@ class Model(QObject):
self.stages = []
self.ipa_path = self.archive_path = self.mac_app_path = ''
self.log_tail = ''
+ self._last_error = ''
self.stagesChanged.emit()
self.log(self.t('msg.running', py + ' ' + ' '.join(args)) + '\n')
@@ -1023,7 +1025,10 @@ class Model(QObject):
if self.stages:
self.stages[-1].state = 'failed'
self.stagesChanged.emit()
- self.finished.emit(False, self.t('msg.buildFailed'))
+ # 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'))
if staging:
shutil.rmtree(staging, ignore_errors=True)
@@ -1040,6 +1045,11 @@ class Model(QObject):
"""Feed one line of the build's output: stage lines move the stage list, everything
else goes to the log (which is what the window shows)."""
self.log(line + '\n')
+ # 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)
+ if line.strip() and not (line.startswith('[') and ']' in line and line.find(']') + 1 < len(line)):
+ self._last_error = line.strip()[:200]
if line.startswith('output IPA:'):
self.ipa_path = line.split(':', 1)[1].strip()
low = line.lower()
diff --git a/frontend-qt/nspb_qt/ui.py b/frontend-qt/nspb_qt/ui.py
index a00d684e..64bf7ad6 100644
--- a/frontend-qt/nspb_qt/ui.py
+++ b/frontend-qt/nspb_qt/ui.py
@@ -46,6 +46,9 @@ class MainWindow(QMainWindow):
scroll = QScrollArea()
scroll.setWidgetResizable(True)
scroll.setFrameShape(QFrame.NoFrame)
+ # kept so a failed build can scroll the log into view: the message says "see the log
+ # below", and on a window shorter than about 600 px the log sits below the fold (issue #52)
+ self.scroll = scroll
body = QWidget()
body.setObjectName('body')
self.body = QVBoxLayout(body)
@@ -477,6 +480,9 @@ class MainWindow(QMainWindow):
# updated it — the footer was English after the toggle.
if running:
self.footer.setText('')
+ elif getattr(self, '_failed', False):
+ pass # a failure message stays until the next build: it was being replaced by
+ # the input reminder on the refresh that follows the failure (issue #52)
elif not self.m.base_path:
self.footer.setText(self.m.t('status.needInputs'))
elif not self.m.repo_ok:
@@ -510,6 +516,12 @@ class MainWindow(QMainWindow):
msg = note or self.m.t('msg.buildFailed')
self.footer.setStyleSheet(f'color: {RED};')
self.footer.setText(msg)
+ self._failed = not ok
+ 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.
+ self.scroll.ensureWidgetVisible(self.log, 0, 0)
+ self.log.setFocus(Qt.OtherFocusReason)
self._refresh_running()
# ---------------------------------------------------------------- actions
@@ -524,6 +536,7 @@ class MainWindow(QMainWindow):
else:
self.footer.setText('')
self.footer.setStyleSheet('')
+ self._failed = False
self.m.start_build()
def _choose_repo(self) -> None:
diff --git a/frontend-qt/tests/test_build_failure.py b/frontend-qt/tests/test_build_failure.py
new file mode 100644
index 00000000..9369f23f
--- /dev/null
+++ b/frontend-qt/tests/test_build_failure.py
@@ -0,0 +1,100 @@
+"""Issue #52: a failed build says which line failed, and the log it points at is in view.
+
+The reporter saw "Build failed (exit code 1) — see the log below" with no log below it. Two
+separate things were wrong, and both are tested here because either alone still leaves the
+report unusable:
+
+* the message carried only the exit code, so the window said nothing about the cause;
+* the log sits at the bottom of a scroll area, below the fold on any window shorter than about
+ 600 px, and the failure did not scroll it into view;
+* and the input reminder overwrote the failure note on the refresh that follows it.
+
+Needs PySide6 and runs offscreen; skipped when PySide6 is absent.
+
+ QT_QPA_PLATFORM=offscreen python3 -m unittest frontend-qt/tests/test_build_failure.py -v
+"""
+from __future__ import annotations
+
+import os
+import sys
+import unittest
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parents[2]
+sys.path.insert(0, str(ROOT / 'frontend-qt'))
+os.environ.setdefault('QT_QPA_PLATFORM', 'offscreen')
+
+try:
+ from PySide6.QtWidgets import QApplication, QScrollArea
+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 BuildFailure(unittest.TestCase):
+ @classmethod
+ def setUpClass(cls):
+ cls.app = QApplication.instance() or QApplication([])
+
+ def _window(self, height: int):
+ from nspb_qt.model import Model
+ from nspb_qt.ui import MainWindow
+ m = Model()
+ w = MainWindow(m)
+ w.resize(900, height)
+ w.show()
+ for _ in range(3):
+ self.app.processEvents()
+ return m, w
+
+ def test_the_log_is_below_the_fold_on_a_short_window(self):
+ """The precondition for the bug: at this height the log is not on screen."""
+ m, w = self._window(460)
+ scroll = w.findChild(QScrollArea)
+ top = w.log.mapTo(scroll.widget(), w.log.rect().topLeft()).y()
+ self.assertGreaterEqual(top, scroll.viewport().height())
+ w.close()
+
+ def test_a_failure_scrolls_the_log_into_view(self):
+ m, w = self._window(460)
+ scroll = w.findChild(QScrollArea)
+ for line in ('extract: RomFS not found', 'Traceback (most recent call last):',
+ 'RuntimeError: no prod.keys in the game folder'):
+ m._on_line(line)
+ w._on_finished(False, m.t('msg.buildFailedReason', m._last_error))
+ self.app.processEvents()
+ self.assertGreater(scroll.verticalScrollBar().value(), 0)
+ w.close()
+
+ def test_the_failure_note_names_the_last_real_line(self):
+ m, w = self._window(700)
+ for line in ('[1/7] extract', '[2/7] build shaders', 'RuntimeError: no prod.keys in the game folder'):
+ m._on_line(line)
+ self.assertEqual(m._last_error, 'RuntimeError: no prod.keys in the game folder',
+ 'stage bookkeeping must not win over the last real line')
+ w._on_finished(False, m.t('msg.buildFailedReason', m._last_error))
+ self.assertIn('no prod.keys', w.footer.text())
+ self.assertIn('see the log below', w.footer.text())
+ w.close()
+
+ def test_the_input_reminder_does_not_erase_the_failure(self):
+ """The refresh after a failure used to replace the note with "Still need the base game"."""
+ m, w = self._window(700)
+ m._on_line('RuntimeError: no prod.keys in the game folder')
+ w._on_finished(False, m.t('msg.buildFailedReason', m._last_error))
+ w._refresh_running()
+ self.assertIn('no prod.keys', w.footer.text())
+ w.close()
+
+ def test_starting_the_next_build_clears_it(self):
+ m, w = self._window(700)
+ m._on_line('RuntimeError: no prod.keys')
+ w._on_finished(False, m.t('msg.buildFailedReason', m._last_error))
+ w._build_clicked() # no inputs: start_build returns on its own check
+ w._refresh_running()
+ self.assertNotIn('no prod.keys', w.footer.text())
+ w.close()
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/frontend/Sources/NSPortBuilder/ContentView.swift b/frontend/Sources/NSPortBuilder/ContentView.swift
index 31241a6c..0e7679cd 100644
--- a/frontend/Sources/NSPortBuilder/ContentView.swift
+++ b/frontend/Sources/NSPortBuilder/ContentView.swift
@@ -762,7 +762,15 @@ final class BuildModel: ObservableObject {
if let i = self.stages.lastIndex(where: { $0.state == .running }) {
self.stages[i].state = .failed
self.stages[i].detail = String(format: self.t("msg.exitCode"), status.terminationStatus)
- } else { self.doneNote = String(format: self.t("msg.buildFailed"), status.terminationStatus) }
+ } 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
+ // reporter looking for a log that a short window had below the fold (#52)
+ self.doneNote = String(format: self.t("msg.buildFailed"), status.terminationStatus)
+ if let last = Self.lastMeaningfulLine(self.logTail) {
+ self.doneNote = String(format: self.t("msg.buildFailedReason"), last)
+ }
+ }
self.cleanupStaging()
}
}
@@ -830,6 +838,17 @@ final class BuildModel: ObservableObject {
// MARK: Output parsing
+ /// The last line of the log that says something: not blank, not a progress event. Used for the
+ /// failure note, where the exit code on its own is not actionable (issue #52).
+ static func lastMeaningfulLine(_ log: String) -> String? {
+ for line in log.split(separator: "\n", omittingEmptySubsequences: true).reversed() {
+ let s = line.trimmingCharacters(in: .whitespaces)
+ if s.isEmpty || s.hasPrefix("{") { continue } // a --progress json event
+ return String(s.prefix(200))
+ }
+ return nil
+ }
+
private func say(_ s: String) { append(s + "\n") }
private func append(_ s: String) {
logTail += s
diff --git a/frontend/Sources/NSPortBuilder/Localization.swift b/frontend/Sources/NSPortBuilder/Localization.swift
index 45d826e3..751c7a56 100644
--- a/frontend/Sources/NSPortBuilder/Localization.swift
+++ b/frontend/Sources/NSPortBuilder/Localization.swift
@@ -379,6 +379,8 @@ enum L10n {
"msg.stopped": ("已停止", "Stopped"),
"msg.buildFailed": ("构建失败(退出码 %d),见下方日志",
"Build failed (exit code %d) — see the log below"),
+ "msg.buildFailedReason": ("构建失败,见下方日志。最后一行:%@",
+ "Build failed — see the log below. Last line: %@"),
"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/NSPortBuilderTests/LibraryTests.swift b/frontend/Tests/NSPortBuilderTests/LibraryTests.swift
index bc7bfddc..ac2b1090 100644
--- a/frontend/Tests/NSPortBuilderTests/LibraryTests.swift
+++ b/frontend/Tests/NSPortBuilderTests/LibraryTests.swift
@@ -612,3 +612,17 @@ final class LibraryTests: XCTestCase {
model.running = false
}
}
+
+ /// Issue #52: the failure note names the last real line, not just the exit code.
+ func testLastMeaningfulLineSkipsProgressEventsAndBlankLines() {
+ let log = """
+ [1/7] extract
+ {"event":"progress","frac":0.4}
+
+ RuntimeError: no prod.keys in the game folder
+
+ """
+ XCTAssertEqual(BuildModel.lastMeaningfulLine(log), "RuntimeError: no prod.keys in the game folder")
+ XCTAssertNil(BuildModel.lastMeaningfulLine("\n\n"))
+ XCTAssertNil(BuildModel.lastMeaningfulLine("{\"event\":\"stage_end\"}\n"))
+ }