Skip to content

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

A double-click on the top bar does the title bar's action, and a game without a Mac app offers Build

v0lumehi5e5f00d5efad
diff --git a/frontend/Sources/NSPortBuilder/LauncherStyles.swift b/frontend/Sources/NSPortBuilder/LauncherStyles.swift
index e674880b..eb31ffbf 100644
--- a/frontend/Sources/NSPortBuilder/LauncherStyles.swift
+++ b/frontend/Sources/NSPortBuilder/LauncherStyles.swift
@@ -16,6 +16,52 @@ struct LauncherWindowChrome: NSViewRepresentable {
func updateNSView(_ nsView: NSView, context: Context) {}
}
+/// What a double-click on the title bar does, as System Settings → Desktop & Dock sets it.
+enum TitlebarAction: Equatable {
+ case zoom, minimize, none
+
+ /// `AppleActionOnDoubleClick` ("Maximize", "Fill", "Minimize", "None") wins; the older `AppleMiniaturizeOnDoubleClick` bool is read only
+ /// without it; with neither, macOS's default (zoom).
+ static func resolve(actionSetting: String?, miniaturizeFlag: Bool?) -> TitlebarAction {
+ if let value = actionSetting?.trimmingCharacters(in: .whitespaces).lowercased(), !value.isEmpty {
+ switch value {
+ case "minimize": return .minimize
+ case "none", "do nothing", "nothing": return .none
+ default: return .zoom // Maximize, Fill, or a value a later macOS adds
+ }
+ }
+ return miniaturizeFlag == true ? .minimize : .zoom
+ }
+
+ static var current: TitlebarAction {
+ let d = UserDefaults.standard // the global domain is searched too
+ return resolve(actionSetting: d.string(forKey: "AppleActionOnDoubleClick"),
+ miniaturizeFlag: d.object(forKey: "AppleMiniaturizeOnDoubleClick") as? Bool)
+ }
+
+ func perform(on window: NSWindow?) {
+ switch self {
+ case .zoom: window?.zoom(nil) // fills the screen, traffic lights kept; a second one restores
+ case .minimize: window?.miniaturize(nil)
+ case .none: break
+ }
+ }
+}
+
+/// Sits behind the top bar. Controls above it keep their clicks; on an empty part a double-click does the title bar's action
+/// and a single press drags the window (the view takes the mouse-down, so it starts the drag itself).
+struct TitlebarDoubleClick: NSViewRepresentable {
+ final class DragView: NSView {
+ override var mouseDownCanMoveWindow: Bool { false }
+ override func mouseDown(with event: NSEvent) {
+ if event.clickCount == 2 { TitlebarAction.current.perform(on: window) }
+ else { window?.performDrag(with: event) }
+ }
+ }
+ func makeNSView(context: Context) -> NSView { DragView() }
+ func updateNSView(_ nsView: NSView, context: Context) {}
+}
+
struct LauncherSecondaryButtonStyle: ButtonStyle {
/// Text and border in this colour (the build bar's Stop); plain white otherwise.
var accent: Color? = nil
diff --git a/frontend/Sources/NSPortBuilder/LauncherView.swift b/frontend/Sources/NSPortBuilder/LauncherView.swift
index 13c31abd..9a035615 100644
--- a/frontend/Sources/NSPortBuilder/LauncherView.swift
+++ b/frontend/Sources/NSPortBuilder/LauncherView.swift
@@ -221,6 +221,7 @@ struct ContentView: View {
}
.padding(.leading, 90).padding(.trailing, 24)
.frame(height: 64)
+ .background(TitlebarDoubleClick()) // an empty part of the bar acts as the title bar does
}
/// The magnifier opens into a search field in the bar itself; Esc, or leaving it empty, closes it again.
@@ -349,10 +350,10 @@ struct ContentView: View {
.tracking(-1.6).lineLimit(2).shadow(color: .black.opacity(0.25), radius: 12)
HStack(spacing: 18) {
Button { primaryAction(game) } label: {
- Label(game.isReady ? m.t("library.play")
- : (game.onDevice ? String(format: m.t("dev.open"), m.deviceName(game.installedDevice))
- : m.t(game.hasIOSBuild ? "library.showIOS" : "library.newBuild")),
- systemImage: game.isReady ? "play.fill" : (game.hasIOSBuild ? "iphone" : "hammer.fill"))
+ Label(game.primary == .play ? m.t("library.play")
+ : (game.primary == .openOnDevice ? String(format: m.t("dev.open"), m.deviceName(game.installedDevice))
+ : m.t("library.newBuild")),
+ systemImage: game.primary == .play ? "play.fill" : (game.primary == .openOnDevice ? "iphone" : "hammer.fill"))
.font(.manrope(18, .bold))
.foregroundStyle(.black).padding(.horizontal, 30).padding(.vertical, 14)
.frame(minWidth: 164)
@@ -636,7 +637,7 @@ struct ContentView: View {
actions: ManageActions(
rebuild: { configureBuild(game) }, options: { optionsFor = game.id }, saves: { savesFor = game.id },
changeArtwork: { chooseArtwork(game) }, resetArtwork: { library.setArtwork("", for: game.id) },
- reveal: { NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: game.appPath)]) },
+ reveal: { if let path = game.revealTarget { NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: path)]) } },
freeSpace: { freeSpaceFor = game.id }, remove: { removing = game }))
}
@@ -659,10 +660,6 @@ struct ContentView: View {
}
return
}
- if !game.isReady && game.hasIOSBuild {
- NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: game.ipaPath)])
- return
- }
guard game.isReady else { configureBuild(game); return }
do {
_ = try MacGameBundle.read(URL(fileURLWithPath: game.appPath))
diff --git a/frontend/Sources/NSPortBuilder/Library.swift b/frontend/Sources/NSPortBuilder/Library.swift
index 81868798..2891fd2c 100644
--- a/frontend/Sources/NSPortBuilder/Library.swift
+++ b/frontend/Sources/NSPortBuilder/Library.swift
@@ -28,9 +28,20 @@ struct LibraryGame: Codable, Identifiable, Equatable {
/// Signed and installed on a paired device (installedDevice is its UDID): Play starts it there.
var onDevice: Bool { !installedDevice.isEmpty && FileManager.default.fileExists(atPath: iosAppPath + "/Info.plist") }
- var hasIOSBuild: Bool {
- (!ipaPath.isEmpty && FileManager.default.fileExists(atPath: ipaPath)) ||
- (!iosAppPath.isEmpty && FileManager.default.fileExists(atPath: iosAppPath + "/Info.plist"))
+ var hasIOSBuild: Bool { hasIPA || hasIOSApp }
+ var hasIPA: Bool { !ipaPath.isEmpty && FileManager.default.fileExists(atPath: ipaPath) }
+ var hasIOSApp: Bool { !iosAppPath.isEmpty && FileManager.default.fileExists(atPath: iosAppPath + "/Info.plist") }
+
+ /// What the hero's primary button does: play the Mac app, open the installed iPhone app, else build (an IPA alone is not a reason to show anything else).
+ enum Primary: Equatable { case play, openOnDevice, build }
+ var primary: Primary { isReady ? .play : (onDevice ? .openOnDevice : .build) }
+
+ /// What "Reveal in Finder" shows: the Mac app if it exists, else the IPA, else the iOS app; nil when none does (the item is hidden).
+ var revealTarget: String? {
+ if isReady { return appPath }
+ if hasIPA { return ipaPath }
+ if hasIOSApp { return iosAppPath }
+ return nil
}
}
@@ -246,9 +257,26 @@ final class GameLibrary: ObservableObject {
}
catch { self.error = error.localizedDescription }
}
+ pruneMissingPaths()
selectedID = games.first?.id
}
+ /// Forgets a remembered Mac app, IPA or iOS app that is gone from disk, so nothing points at it. Saves only when something changed;
+ /// run on load and after a scan, never from a view.
+ func pruneMissingPaths() {
+ let fm = FileManager.default
+ var changed = false
+ for index in games.indices {
+ let game = games[index]
+ if !game.appPath.isEmpty && !fm.fileExists(atPath: game.appPath) { games[index].appPath = ""; changed = true }
+ if !game.ipaPath.isEmpty && !fm.fileExists(atPath: game.ipaPath) { games[index].ipaPath = ""; changed = true }
+ if !game.iosAppPath.isEmpty && !fm.fileExists(atPath: game.iosAppPath + "/Info.plist") {
+ games[index].iosAppPath = ""; games[index].installedDevice = ""; changed = true
+ }
+ }
+ if changed { save() }
+ }
+
var selected: LibraryGame? { games.first { $0.id == selectedID } }
func save() {
@@ -359,6 +387,7 @@ final class GameLibrary: ObservableObject {
if let existing = self.games.first(where: { $0.titleID == info.titleID }), existing.isReady { continue }
_ = try? self.addApp(url)
}
+ self.pruneMissingPaths()
self.selectedID = previousSelection ?? self.games.first?.id
self.scanning = false
}
diff --git a/frontend/Sources/NSPortBuilder/Localization.swift b/frontend/Sources/NSPortBuilder/Localization.swift
index 80c7f76b..c3f1862d 100644
--- a/frontend/Sources/NSPortBuilder/Localization.swift
+++ b/frontend/Sources/NSPortBuilder/Localization.swift
@@ -42,7 +42,6 @@ enum L10n {
/// key: (Chinese, English)
static let table: [String: (zh: String, en: String)] = [
"library.readyIOS": ("\u{53ef}\u{7528}\u{4e8e} iPhone", "Ready for iPhone"),
- "library.showIOS": ("\u{663e}\u{793a} iPhone \u{6784}\u{5efa}", "Show iPhone build"),
"library.stopping": ("\u{6b63}\u{5728}\u{505c}\u{6b62}…", "Stopping…"),
"build.setup": ("\u{5b8c}\u{6210}\u{8bbe}\u{7f6e}", "Finish setup"),
"library.chooseFolder": ("\u{6e38}\u{620f}\u{6587}\u{4ef6}\u{5939}\u{2026}", "Change folder…"),
diff --git a/frontend/Sources/NSPortBuilder/ManageMenu.swift b/frontend/Sources/NSPortBuilder/ManageMenu.swift
index 1f4378b9..3f676407 100644
--- a/frontend/Sources/NSPortBuilder/ManageMenu.swift
+++ b/frontend/Sources/NSPortBuilder/ManageMenu.swift
@@ -33,7 +33,7 @@ struct ManageItem: Identifiable {
items.append(.init(id: "saves", symbol: "tray.and.arrow.down", title: t("saves.menu"), run: a.saves))
items.append(.init(id: "artwork", symbol: "photo", title: t("library.changeArtwork"), run: a.changeArtwork))
if !game.artworkPath.isEmpty { items.append(.init(id: "resetArtwork", symbol: "arrow.uturn.backward", title: t("library.resetArtwork"), run: a.resetArtwork)) }
- if !game.appPath.isEmpty { items.append(.init(id: "reveal", symbol: "folder", title: t("install.reveal"), run: a.reveal)) }
+ if game.revealTarget != nil { items.append(.init(id: "reveal", symbol: "folder", title: t("install.reveal"), run: a.reveal)) }
if hasBuildFolder { items.append(.init(id: "freeSpace", symbol: "externaldrive", title: t("free.menu"), run: a.freeSpace)) }
items.append(.init(id: "remove", symbol: "trash", title: t("library.remove"), enabled: game.id != activeBuildID,
destructive: true, separatorBefore: true, run: a.remove))
diff --git a/frontend/Tests/NSPortBuilderTests/LibraryTests.swift b/frontend/Tests/NSPortBuilderTests/LibraryTests.swift
index ef283823..622b8e57 100644
--- a/frontend/Tests/NSPortBuilderTests/LibraryTests.swift
+++ b/frontend/Tests/NSPortBuilderTests/LibraryTests.swift
@@ -705,8 +705,8 @@ final class LibraryTests: XCTestCase {
model.slots[0].paths = []
library.selectedID = library.games.first?.id
func capture(_ name: String, width: CGFloat = 1440, height: CGFloat = 1024, page: LauncherPage = .library, activeID: UUID? = nil, empty: Bool = false,
- search: String? = nil, older: Set<UUID> = [], manageOpen: Bool = false, padRing: Bool = false) throws {
- let store = empty ? GameLibrary(file: temporary.appendingPathComponent("empty.json")) : library
+ search: String? = nil, older: Set<UUID> = [], manageOpen: Bool = false, padRing: Bool = false, only: GameLibrary? = nil) throws {
+ let store = only ?? (empty ? GameLibrary(file: temporary.appendingPathComponent("empty.json")) : library)
let view = ContentView(model: model, library: store, initialPage: page, activeBuildID: activeID, performStartupChecks: false, search: search,
olderTools: older, manageOpen: manageOpen, padRing: padRing)
let host = NSHostingView(rootView: view)
@@ -774,6 +774,15 @@ final class LibraryTests: XCTestCase {
model.slots[0].paths = []
try capture("library-older-tools", older: [library.games[0].id, library.games[1].id])
try capture("library-older-tools-small", width: 900, height: 680, older: [library.games[0].id, library.games[1].id])
+ do { // a game with an IPA but no Mac app: Build is the primary button, Reveal in Finder shows the IPA
+ let ipa = temporary.appendingPathComponent("Metroid Dread.ipa")
+ try Data([0]).write(to: ipa)
+ let ipaOnly = LibraryGame(titleID: "010093801237C000", name: "Metroid Dread", ipaPath: ipa.path)
+ let file = temporary.appendingPathComponent("ipa-only.json")
+ try JSONEncoder().encode([ipaOnly]).write(to: file)
+ try capture("library-ipa-only", only: GameLibrary(file: file))
+ try capture("manage-menu-ipa-only", manageOpen: true, only: GameLibrary(file: file))
+ }
// An iPhone build with a paired device and a team (example values)
let previousTarget = model.target
model.target = "ios"
diff --git a/frontend/Tests/NSPortBuilderTests/PrimaryActionTests.swift b/frontend/Tests/NSPortBuilderTests/PrimaryActionTests.swift
new file mode 100644
index 00000000..d28e4ce1
--- /dev/null
+++ b/frontend/Tests/NSPortBuilderTests/PrimaryActionTests.swift
@@ -0,0 +1,109 @@
+import XCTest
+@testable import NSPortBuilder
+
+final class PrimaryActionTests: XCTestCase {
+ private var temporary: URL!
+ private let titleID = "0100535012974000"
+
+ override func setUpWithError() throws {
+ temporary = FileManager.default.temporaryDirectory.appendingPathComponent("nxnative-primary-" + UUID().uuidString)
+ try FileManager.default.createDirectory(at: temporary, withIntermediateDirectories: true)
+ }
+ override func tearDownWithError() throws { try FileManager.default.removeItem(at: temporary) }
+
+ private func makeApp(_ name: String = "Hades") throws -> URL {
+ let app = temporary.appendingPathComponent(name + ".app")
+ let executables = app.appendingPathComponent("Contents/MacOS")
+ try FileManager.default.createDirectory(at: executables, withIntermediateDirectories: true)
+ for exe in ["nxnative", "dmhost"] {
+ try FileManager.default.createSymbolicLink(at: executables.appendingPathComponent(exe), withDestinationURL: URL(fileURLWithPath: "/usr/bin/true"))
+ }
+ let info: [String: Any] = ["DMTitleID": titleID, "CFBundleDisplayName": name, "CFBundleExecutable": "nxnative", "CFBundleIdentifier": "org.nxnative.primarytests"]
+ try PropertyListSerialization.data(fromPropertyList: info, format: .xml, options: 0).write(to: app.appendingPathComponent("Contents/Info.plist"))
+ return app
+ }
+ private func makeIPA() throws -> URL {
+ let ipa = temporary.appendingPathComponent("Hades.ipa")
+ try Data([0]).write(to: ipa)
+ return ipa
+ }
+ private func makeIOSApp() throws -> URL {
+ let app = temporary.appendingPathComponent("ios/Hades.app")
+ try FileManager.default.createDirectory(at: app, withIntermediateDirectories: true)
+ try Data([0]).write(to: app.appendingPathComponent("Info.plist"))
+ return app
+ }
+
+ func testPrimaryForEachState() throws {
+ let app = try makeApp(), ipa = try makeIPA(), ios = try makeIOSApp()
+ XCTAssertEqual(LibraryGame(titleID: titleID, name: "H", appPath: app.path, ipaPath: ipa.path).primary, .play)
+ var device = LibraryGame(titleID: titleID, name: "H", ipaPath: ipa.path, iosAppPath: ios.path)
+ device.installedDevice = "UDID"
+ XCTAssertEqual(device.primary, .openOnDevice)
+ XCTAssertEqual(LibraryGame(titleID: titleID, name: "H", ipaPath: ipa.path).primary, .build, "an IPA alone builds, it does not offer to show the IPA")
+ XCTAssertEqual(LibraryGame(titleID: titleID, name: "H").primary, .build)
+ XCTAssertEqual(LibraryGame(titleID: titleID, name: "H", appPath: temporary.appendingPathComponent("gone.app").path).primary, .build, "a deleted Mac app")
+ }
+
+ func testRevealTargetPrefersWhatExists() throws {
+ let app = try makeApp(), ipa = try makeIPA(), ios = try makeIOSApp()
+ let gone = temporary.appendingPathComponent("gone").path
+ XCTAssertEqual(LibraryGame(titleID: titleID, name: "H", appPath: app.path, ipaPath: ipa.path, iosAppPath: ios.path).revealTarget, app.path)
+ XCTAssertEqual(LibraryGame(titleID: titleID, name: "H", appPath: gone, ipaPath: ipa.path, iosAppPath: ios.path).revealTarget, ipa.path)
+ XCTAssertEqual(LibraryGame(titleID: titleID, name: "H", appPath: gone, ipaPath: gone, iosAppPath: ios.path).revealTarget, ios.path)
+ XCTAssertNil(LibraryGame(titleID: titleID, name: "H", appPath: gone, ipaPath: gone, iosAppPath: gone).revealTarget)
+ XCTAssertNil(LibraryGame(titleID: titleID, name: "H").revealTarget)
+ }
+
+ func testManageMenuShowsRevealOnlyWithATarget() throws {
+ let ipa = try makeIPA()
+ func ids(_ game: LibraryGame) -> [String] {
+ ManageItem.list(game: game, labels: { $0 }, running: false, olderTools: false, activeBuildID: nil, hasBuildFolder: false, actions: ManageActions()).map(\.id)
+ }
+ XCTAssertTrue(ids(LibraryGame(titleID: titleID, name: "H", ipaPath: ipa.path)).contains("reveal"))
+ XCTAssertFalse(ids(LibraryGame(titleID: titleID, name: "H", appPath: temporary.appendingPathComponent("gone.app").path)).contains("reveal"))
+ }
+
+ func testStalePathsAreClearedOnLoad() throws {
+ let app = try makeApp(), ipa = try makeIPA()
+ let gone = temporary.appendingPathComponent("gone").path
+ let kept = LibraryGame(titleID: titleID, name: "Kept", appPath: app.path, ipaPath: ipa.path)
+ var stale = LibraryGame(titleID: "0100000000010000", name: "Stale", appPath: gone + ".app", ipaPath: gone + ".ipa", iosAppPath: gone + "/Hades.app")
+ stale.installedDevice = "UDID"
+ let file = temporary.appendingPathComponent("library.json")
+ try JSONEncoder().encode([kept, stale]).write(to: file)
+ let library = GameLibrary(file: file)
+ let a = try XCTUnwrap(library.games.first { $0.name == "Kept" }), b = try XCTUnwrap(library.games.first { $0.name == "Stale" })
+ XCTAssertEqual(a.appPath, app.path)
+ XCTAssertEqual(a.ipaPath, ipa.path)
+ XCTAssertEqual([b.appPath, b.ipaPath, b.iosAppPath, b.installedDevice], ["", "", "", ""])
+ // saved: a fresh load sees the cleared entry too, and the entries are kept
+ let again = GameLibrary(file: file)
+ XCTAssertEqual(again.games.first { $0.name == "Stale" }?.appPath, "")
+ XCTAssertEqual(again.games.count, 2)
+ }
+
+ func testPruneAfterAppIsDeletedWhileRunning() throws {
+ let app = try makeApp()
+ let library = GameLibrary(file: temporary.appendingPathComponent("library.json"))
+ _ = try library.addApp(app)
+ XCTAssertEqual(library.games[0].primary, .play)
+ try FileManager.default.removeItem(at: app)
+ library.pruneMissingPaths()
+ XCTAssertEqual(library.games[0].appPath, "")
+ XCTAssertEqual(library.games[0].primary, .build)
+ }
+
+ func testTitlebarActionFollowsTheSetting() {
+ XCTAssertEqual(TitlebarAction.resolve(actionSetting: "Maximize", miniaturizeFlag: nil), .zoom)
+ XCTAssertEqual(TitlebarAction.resolve(actionSetting: "Fill", miniaturizeFlag: nil), .zoom)
+ XCTAssertEqual(TitlebarAction.resolve(actionSetting: "Minimize", miniaturizeFlag: nil), .minimize)
+ XCTAssertEqual(TitlebarAction.resolve(actionSetting: "None", miniaturizeFlag: nil), .none)
+ XCTAssertEqual(TitlebarAction.resolve(actionSetting: "Do Nothing", miniaturizeFlag: nil), .none)
+ XCTAssertEqual(TitlebarAction.resolve(actionSetting: nil, miniaturizeFlag: nil), .zoom, "macOS's default")
+ XCTAssertEqual(TitlebarAction.resolve(actionSetting: "", miniaturizeFlag: nil), .zoom)
+ XCTAssertEqual(TitlebarAction.resolve(actionSetting: nil, miniaturizeFlag: true), .minimize, "the older setting, when the new one is absent")
+ XCTAssertEqual(TitlebarAction.resolve(actionSetting: nil, miniaturizeFlag: false), .zoom)
+ XCTAssertEqual(TitlebarAction.resolve(actionSetting: "Maximize", miniaturizeFlag: true), .zoom, "the new setting wins")
+ }
+}