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
Launcher: a notification when a build finishes or fails (issue #64)
v0lumehi5d10ac9fe348
diff --git a/frontend/README.md b/frontend/README.mdindex 8fc1ad06..838b7069 100644--- a/frontend/README.md+++ b/frontend/README.md@@ -32,6 +32,13 @@ A completed Mac build appears in the collection automatically and can be startedwith **Play**. An iPhone build, by default, offers its unsigned IPA and thesideloading and RomFS-copy instructions.+When a build finishes or fails while the app is in the background, a notification+names the game and the target; clicking it shows the game in the library, or the+Builds page with the log for a failed build. macOS asks for permission when the+first build starts, and **Settings → App** turns it off. Notifications need the+app bundle: started with `swift run` the launcher has no bundle identifier, and+there are none.+## Install on an iPhone or iPadWith Xcode, a development certificate (sign in to Xcode with your Apple ID underdiff --git a/frontend/Sources/NSPortBuilder/BuildNotifications.swift b/frontend/Sources/NSPortBuilder/BuildNotifications.swiftnew file mode 100644index 00000000..e41e0aae--- /dev/null+++ b/frontend/Sources/NSPortBuilder/BuildNotifications.swift@@ -0,0 +1,121 @@+import AppKit+import Combine+import UserNotifications++// A notification when a build finishes or fails (issue #64): a build takes long enough that people switch+// to something else, and the only sign it was done was the window they had left. Only while the app is not+// frontmost (a build someone is watching needs no notification), and only when Settings leaves it on.+// Clicking it brings the app forward on the game in the library (finished) or the Builds page with the+// log open (failed).+//+// UNUserNotificationCenter needs an app bundle: an unbundled `swift run` has no bundle identifier and+// UNUserNotificationCenter.current() raises an exception there. So without a bundle identifier there are+// no notifications at all (and Settings says so); they work in the packaged NX2Apple.app.++/// The decisions and the text, kept apart from the notification center so they can be tested.+enum BuildNotice {+ enum Outcome: Equatable {+ case finished+ case failed(reason: String)+ case stopped+ }++ static let defaultsKey = "notifyBuilds"++ /// On unless switched off in Settings.+ static var enabled: Bool { UserDefaults.standard.object(forKey: defaultsKey) as? Bool ?? true }++ static var hasBundleID: Bool { Bundle.main.bundleIdentifier != nil }++ /// A stopped build was stopped by someone at the app; a build in front of someone needs no notification.+ static func shouldNotify(_ outcome: Outcome, enabled: Bool, appActive: Bool, hasBundleID: Bool) -> Bool {+ outcome != .stopped && enabled && !appActive && hasBundleID+ }++ /// Title and body: the game, the target, and for a failure the reason (the build's own last word).+ static func text(_ outcome: Outcome, game: String, target: String, device: String?, _ t: (String) -> String) -> (title: String, body: String) {+ let place = target == "mac-app" ? t("notify.forMac")+ : device.map { String(format: t("notify.installedOn"), $0) } ?? t("notify.forIOS")+ switch outcome {+ case .finished, .stopped: return (String(format: t("notify.doneTitle"), game), place)+ case .failed(let reason):+ return (String(format: t("notify.failedTitle"), game), reason.isEmpty ? place : place + "\n" + reason)+ }+ }++ /// What a failed build said last: its message, else the step that failed with its detail.+ static func failureReason(note: String, stages: [Stage]) -> String {+ if !note.isEmpty { return note }+ guard let s = stages.last(where: { $0.state == .failed }) else { return "" }+ return s.detail.isEmpty ? s.name : s.name + " · " + s.detail+ }+}++/// Watches the build model, posts the notification and turns a click on it into where the app should show.+final class BuildNotifier: NSObject, ObservableObject, UNUserNotificationCenterDelegate {+ static let shared = BuildNotifier()++ struct Route: Equatable {+ var page: LauncherPage+ var game: UUID?+ }++ /// Where a clicked notification asks the window to go (ContentView takes it and clears it).+ @Published var route: Route?+ /// The Builds page opens its log when this is set (BuilderView clears it).+ @Published var showLog = false++ private var watching: AnyCancellable?++ /// Follows the model's builds: asks for permission when one starts, notifies when it ends. Only from the real+ /// app's window (not previews or tests), and only with a bundle identifier (see the top of this file).+ func watch(_ m: BuildModel, library: GameLibrary) {+ guard watching == nil, BuildNotice.hasBundleID else { return }+ UNUserNotificationCenter.current().delegate = self+ watching = m.$running.removeDuplicates().dropFirst().sink { [weak self, weak m, weak library] running in+ guard let self, let m, let library else { return }+ if running {+ // The first build is when someone has a reason to say yes; the system asks only once.+ if BuildNotice.enabled { UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound]) { _, _ in } }+ return+ }+ // Published before the change lands: Stop is still visible now, the outcome only once the handler that+ // ended the build has finished (it sets done and its note after running).+ let stopped = m.stopping+ DispatchQueue.main.async {+ let outcome: BuildNotice.Outcome = stopped ? .stopped+ : m.done ? .finished : .failed(reason: BuildNotice.failureReason(note: m.doneNote, stages: m.stages))+ guard BuildNotice.shouldNotify(outcome, enabled: BuildNotice.enabled, appActive: NSApp.isActive, hasBundleID: true) else { return }+ self.post(outcome, m: m, library: library)+ }+ }+ }++ private func post(_ outcome: BuildNotice.Outcome, m: BuildModel, library: GameLibrary) {+ let titleID = BuildModel.titleID(m.basePath).map { String(format: "%016llX", $0) } ?? ""+ let game = library.games.first { $0.titleID == titleID }+ let name = game?.name ?? GameLibrary.title(for: m.basePath, repo: m.repoPath, titleID: titleID)+ let text = BuildNotice.text(outcome, game: name, target: m.target, device: m.installedOn.isEmpty ? nil : m.deviceName(m.installedOn), m.t)+ let content = UNMutableNotificationContent()+ content.title = text.title+ content.body = text.body+ content.sound = .default+ content.userInfo = ["page": outcome == .finished ? LauncherPage.library.rawValue : LauncherPage.builds.rawValue,+ "game": game?.id.uuidString ?? ""]+ UNUserNotificationCenter.current().add(UNNotificationRequest(identifier: "build-" + UUID().uuidString, content: content, trigger: nil))+ }++ func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse,+ withCompletionHandler completionHandler: @escaping () -> Void) {+ let info = response.notification.request.content.userInfo+ let page = LauncherPage(rawValue: info["page"] as? String ?? "") ?? .library+ let game = (info["game"] as? String).flatMap(UUID.init(uuidString:))+ DispatchQueue.main.async {+ NSApp.activate(ignoringOtherApps: true)+ NSApp.windows.first { $0.canBecomeMain }?.makeKeyAndOrderFront(nil)+ if page == .builds { self.showLog = true }+ self.route = Route(page: page, game: game)+ completionHandler()+ }+ }+}diff --git a/frontend/Sources/NSPortBuilder/ContentView.swift b/frontend/Sources/NSPortBuilder/ContentView.swiftindex 48fa702e..db4ec476 100644--- a/frontend/Sources/NSPortBuilder/ContentView.swift+++ b/frontend/Sources/NSPortBuilder/ContentView.swift@@ -1934,6 +1934,7 @@ struct BuilderView: View {var onChooseLibraryFolder: () -> Void = {}var onOpenControls: () -> Void = {}var controlChanges = 0+ @AppStorage(BuildNotice.defaultsKey) private var notifyBuilds = true // BuildNotifications.swift@State private var extrasOpen = false@State private var logOpen = false@EnvironmentObject private var padFocus: PadFocus@@ -2261,6 +2262,9 @@ struct BuilderView: View {disclosure(m.t("build.log"), isOpen: logOpen) { logOpen.toggle() }if logOpen { logView.padding(.horizontal, 14).padding(.bottom, 14) }}+ .onReceive(BuildNotifier.shared.$showLog) { show in // a clicked notification of a failed build+ if show { logOpen = true; DispatchQueue.main.async { BuildNotifier.shared.showLog = false } }+ }}private var logView: some View {@@ -2368,6 +2372,12 @@ struct BuilderView: View {.padTarget("set.language", scope: "main", activate: { cycleLanguage(1) }, adjust: { cycleLanguage($0) })}divider+ // Build notifications (BuildNotifications.swift): none without an app bundle, e.g. under swift run+ row(m.t("settings.notify"), detail: m.t(BuildNotice.hasBundleID ? "settings.notifyNote" : "settings.notifyUnbundled")) {+ Toggle("", isOn: $notifyBuilds).toggleStyle(LauncherSwitchStyle()).labelsHidden().disabled(!BuildNotice.hasBundleID)+ .padTarget("set.notify", scope: "main") { notifyBuilds.toggle() }+ }+ dividerrow("NX2Apple", detail: String(format: m.t("app.version"), BuildModel.appVersion),dot: m.appStaged != nil ? LauncherPalette.ready : nil) {if m.appBusy { ProgressView().controlSize(.small) }diff --git a/frontend/Sources/NSPortBuilder/LauncherView.swift b/frontend/Sources/NSPortBuilder/LauncherView.swiftindex 3fcd6c63..4ea1c9bf 100644--- a/frontend/Sources/NSPortBuilder/LauncherView.swift+++ b/frontend/Sources/NSPortBuilder/LauncherView.swift@@ -87,8 +87,15 @@ struct ContentView: View {m.checkDeps()if m.repoOK && m.repoIsGit { m.checkRepoUpdates(silent: true) }m.checkAppUpdate(silent: true)+ BuildNotifier.shared.watch(m, library: library) // BuildNotifications.swift}}+ .onReceive(BuildNotifier.shared.$route) { route in // a clicked build notification+ guard let route else { return }+ page = route.page+ if let id = route.game { library.selectedID = id }+ DispatchQueue.main.async { BuildNotifier.shared.route = nil }+ }.onChange(of: library.games) { _ inrefreshArtwork()if performStartupChecks { fetchArtwork() }diff --git a/frontend/Sources/NSPortBuilder/Localization.swift b/frontend/Sources/NSPortBuilder/Localization.swiftindex f4323d17..88faf9d3 100644--- a/frontend/Sources/NSPortBuilder/Localization.swift+++ b/frontend/Sources/NSPortBuilder/Localization.swift@@ -268,6 +268,14 @@ enum L10n {// ---- dependencies ----// ---- Qt front end (frontend-qt): keys the SwiftUI app does not use yet ----"build.start": ("开始构建", "Start build"),+ "notify.doneTitle": ("%@ 构建完成", "%@ is built"),+ "notify.failedTitle": ("%@ 构建失败", "%@ couldn’t be built"),+ "notify.forMac": ("用于这台 Mac,已在游戏库中", "For this Mac, in your library"),+ "notify.forIOS": ("用于 iPhone / iPad", "For iPhone / iPad"),+ "notify.installedOn": ("已安装到 %@", "Installed on %@"),+ "settings.notify": ("构建完成时通知", "Notify when a build ends"),+ "settings.notifyNote": ("仅在 NX2Apple 不在前台时,构建完成或失败都会通知", "When a build finishes or fails while NX2Apple is in the background"),+ "settings.notifyUnbundled": ("需要 NX2Apple.app:用 swift run 启动时没有通知", "Needs NX2Apple.app: no notifications when started with swift run"),"build.cancel": ("取消构建", "Cancel build"),"msg.macAppDone": ("Mac App 已生成,可在访达里双击运行", "Mac app ready — double-click it in the Finder"),"msg.macAppMissing": ("构建结束但没有找到 .app(仓库里缺 dm/mac/pack_app.py?)",diff --git a/frontend/Tests/NSPortBuilderTests/BuildNotificationsTests.swift b/frontend/Tests/NSPortBuilderTests/BuildNotificationsTests.swiftnew file mode 100644index 00000000..7e5a9dd5--- /dev/null+++ b/frontend/Tests/NSPortBuilderTests/BuildNotificationsTests.swift@@ -0,0 +1,76 @@+import XCTest+import SwiftUI+@testable import NSPortBuilder++/// When a build notification is posted and what it says (issue #64). Nothing here touches the notification center.+final class BuildNotificationsTests: XCTestCase {+ private func en(_ key: String) -> String { L10n.string(key, .en) }++ func testOnlyAFinishedOrFailedBuildInTheBackgroundIsNotified() {+ let failed = BuildNotice.Outcome.failed(reason: "Build failed (exit code 1)")+ XCTAssertTrue(BuildNotice.shouldNotify(.finished, enabled: true, appActive: false, hasBundleID: true))+ XCTAssertTrue(BuildNotice.shouldNotify(failed, enabled: true, appActive: false, hasBundleID: true))+ XCTAssertFalse(BuildNotice.shouldNotify(.finished, enabled: true, appActive: true, hasBundleID: true), "a build someone is watching")+ XCTAssertFalse(BuildNotice.shouldNotify(.stopped, enabled: true, appActive: false, hasBundleID: true), "Stop was pressed at the app")+ XCTAssertFalse(BuildNotice.shouldNotify(failed, enabled: false, appActive: false, hasBundleID: true), "switched off in Settings")+ XCTAssertFalse(BuildNotice.shouldNotify(.finished, enabled: true, appActive: false, hasBundleID: false), "swift run: no bundle, no notification center")+ }++ func testNotificationsAreOnUntilSwitchedOff() {+ let saved = UserDefaults.standard.object(forKey: BuildNotice.defaultsKey)+ defer { UserDefaults.standard.set(saved, forKey: BuildNotice.defaultsKey) }+ UserDefaults.standard.removeObject(forKey: BuildNotice.defaultsKey)+ XCTAssertTrue(BuildNotice.enabled)+ UserDefaults.standard.set(false, forKey: BuildNotice.defaultsKey)+ XCTAssertFalse(BuildNotice.enabled)+ }++ func testTheTextNamesTheGameAndTheTarget() {+ let mac = BuildNotice.text(.finished, game: "Metroid Dread", target: "mac-app", device: nil, en)+ XCTAssertEqual(mac.title, "Metroid Dread is built")+ XCTAssertEqual(mac.body, "For this Mac, in your library")+ XCTAssertEqual(BuildNotice.text(.finished, game: "Hades", target: "ios", device: nil, en).body, "For iPhone / iPad")+ XCTAssertEqual(BuildNotice.text(.finished, game: "Hades", target: "ios", device: "Jo’s iPhone", en).body, "Installed on Jo’s iPhone")+ let failed = BuildNotice.text(.failed(reason: "Extract · exit code 3"), game: "Hades", target: "ios", device: nil, en)+ XCTAssertEqual(failed.title, "Hades couldn’t be built")+ XCTAssertEqual(failed.body, "For iPhone / iPad\nExtract · exit code 3")+ let zh = BuildNotice.text(.failed(reason: ""), game: "Hades", target: "mac-app", device: nil) { L10n.string($0, .zh) }+ XCTAssertTrue(zh.title.contains("Hades") && !zh.title.contains("notify.") && !zh.body.contains("notify."), zh.title)+ }++ func testTheFailureReasonIsTheBuildsOwnLastWord() {+ var stage = Stage(id: 3, name: "Extract")+ stage.state = .failed+ stage.detail = "exit code 3"+ XCTAssertEqual(BuildNotice.failureReason(note: "", stages: [Stage(id: 1, name: "Survey", state: .done), stage]), "Extract · exit code 3")+ XCTAssertEqual(BuildNotice.failureReason(note: "Build failed: no Program NCA", stages: [stage]), "Build failed: no Program NCA")+ XCTAssertEqual(BuildNotice.failureReason(note: "", stages: []), "")+ }++ // MARK: Visual QA (matched by --filter testRenderLauncherForVisualQA)++ @MainActor func testRenderLauncherForVisualQANotificationSetting() 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)+ NSApplication.shared.setActivationPolicy(.accessory)+ let temporary = FileManager.default.temporaryDirectory.appendingPathComponent("nxnative-notify-" + UUID().uuidString)+ try FileManager.default.createDirectory(at: temporary, withIntermediateDirectories: true)+ defer { try? FileManager.default.removeItem(at: temporary) }+ let model = BuildModel()+ model.lang = .en+ model.depsChecked = true+ model.deps = [BuildModel.Dep(id: "test", name: "Xcode", hint: "", present: true, installCmd: [])]+ let library = GameLibrary(file: temporary.appendingPathComponent("preview.json"))+ let host = NSHostingView(rootView: ContentView(model: model, library: library, initialPage: .settings, performStartupChecks: false))+ let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 1440, height: 1500), styleMask: [.titled, .closable, .resizable], backing: .buffered, defer: false)+ window.contentView = host+ window.orderFront(nil)+ RunLoop.main.run(until: Date().addingTimeInterval(0.5))+ 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("settings-notify.png"))+ window.orderOut(nil)+ }+}