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
Console mode: players assigned automatically, precise statuses, real versions, calmer scrolling, wide hint bar
v0lumehia906bbb76cec
diff --git a/frontend/Sources/NSPortBuilder/ConsoleControllersView.swift b/frontend/Sources/NSPortBuilder/ConsoleControllersView.swiftindex 3f0d3bb1..8bc789f7 100644--- a/frontend/Sources/NSPortBuilder/ConsoleControllersView.swift+++ b/frontend/Sources/NSPortBuilder/ConsoleControllersView.swift@@ -196,7 +196,10 @@ struct DesktopControllerChips: View {struct ConsoleToastView: View {let toast: ConsoleToastvar body: some View {- Label(toast.message, systemImage: "gamecontroller")+ HStack(spacing: 10) {+ Label(toast.message, systemImage: "gamecontroller")+ if let glyph = toast.glyph { ConsoleGlyphView(glyph: glyph, size: 20) }+ }.font(.manrope(17, .semibold)).padding(.horizontal, 22).padding(.vertical, 15).background(LauncherPalette.surface, in: Capsule()).overlay(Capsule().strokeBorder(.white.opacity(0.15)))diff --git a/frontend/Sources/NSPortBuilder/ConsoleState.swift b/frontend/Sources/NSPortBuilder/ConsoleState.swiftindex 5e9ff270..e430c320 100644--- a/frontend/Sources/NSPortBuilder/ConsoleState.swift+++ b/frontend/Sources/NSPortBuilder/ConsoleState.swift@@ -5,11 +5,13 @@ import Combine/// controller names and a clock value; none of these types inspects a library or a controller device.struct ConsoleGame: Identifiable {enum Status: Equatable {- case ready, needsBuild, needsData, broken(String)+ case ready, needsBuild, needsData, iphoneOnly, broken(String)var labelKey: String {switch self {case .ready: return "console.ready"- case .needsBuild, .needsData: return "console.setup"+ case .needsBuild: return "console.notBuilt"+ case .needsData: return "console.needsDataBadge"+ case .iphoneOnly: return "console.iphoneOnly"case .broken: return "console.unavailable"}}@@ -18,6 +20,7 @@ struct ConsoleGame: Identifiable {case .ready: return nilcase .needsBuild: return "console.needsBuild"case .needsData: return "console.needsData"+ case .iphoneOnly: return "console.iphoneOnlyNote"case .broken: return "console.broken"}}@@ -70,6 +73,8 @@ struct ConsoleController: Identifiable, Equatable {struct ConsoleToast: Equatable, Identifiable {var id = UUID()+ /// A button glyph shown after the message (the controller in use), for a toast that names a button.+ var glyph: ConsoleGlyphs.Glyph? = nil/// Already localized by the driver, using console connection/identification keys.var message: String}diff --git a/frontend/Sources/NSPortBuilder/ConsoleView.swift b/frontend/Sources/NSPortBuilder/ConsoleView.swiftindex df681f48..919ab4eb 100644--- a/frontend/Sources/NSPortBuilder/ConsoleView.swift+++ b/frontend/Sources/NSPortBuilder/ConsoleView.swift@@ -139,8 +139,8 @@ enum ConsoleInput {.tracking(-1.6).lineLimit(2).fixedSize(horizontal: false, vertical: true).accessibilityAddTraits(.isHeader)HStack(spacing: 12) {- Text(String(format: t("console.version"), game.version)).monospacedDigit().lineLimit(1)- .foregroundStyle(.white.opacity(0.6)).frame(width: compact ? 116 : 150, alignment: .leading) // fixed, so the badges stay put+ if !game.version.isEmpty { Text(String(format: t("console.version"), game.version)).monospacedDigit().lineLimit(1)+ .foregroundStyle(.white.opacity(0.6)).frame(width: compact ? 116 : 150, alignment: .leading) } // fixed, so the badges stay putForEach(game.platforms, id: \.self) { platform inText(t(platform.labelKey)).font(.manrope(compact ? 13 : 17, .semibold)).padding(.horizontal, 12).padding(.vertical, 5)@@ -151,7 +151,7 @@ enum ConsoleInput {}.id(game.id).transition(.opacity)}- .animation(.easeInOut(duration: 0.15), value: game.id)+ .animation(.easeInOut(duration: 0.12), value: game.id).padding(.horizontal, inset).frame(height: compact ? 175 : 100 + 2.4 * min(64, size.width / 24), alignment: .bottomLeading)}@@ -214,34 +214,47 @@ enum ConsoleInput {.onPreferenceChange(ConsoleTileFramesKey.self) { tileFrames = $0 }.padding(.horizontal, inset - 8) // the scroll area is the page margin, so tiles clip there and the title lines up with the first tile.onChange(of: state.focusedGame?.id) { id in- // a new focus replaces the running scroll, it does not queue- if let id { withAnimation(.easeInOut(duration: reduceMotion ? 0 : 0.25)) { proxy.scrollTo("console.game." + id, anchor: .center) } }+ // The ring moves across the visible tiles. The row scrolls only when the focused tile would leave the visible area, by+ // the least that brings it inside, and a new focus replaces the running scroll (held repeats do not queue).+ guard let id else { return }+ let tile = "console.game." + id+ guard let frame = tileFrames[id] else { proxy.scrollTo(tile, anchor: .center); return }+ let rowWidth = size.width - 2 * (inset - 8)+ let anchor: UnitPoint? = frame.minX < 8 ? .leading : (frame.maxX > rowWidth - 8 ? .trailing : nil)+ if let anchor { withAnimation(.easeOut(duration: reduceMotion ? 0 : 0.2)) { proxy.scrollTo(tile, anchor: anchor) } }}.onAppear { if let id = state.focusedGame?.id { proxy.scrollTo("console.game." + id, anchor: .center) } }}}private func hintBar(compact: Bool) -> some View {- // Equal-width slots between the page margins, every item the same pill and centered in its slot (two by two when compact).- let columns = Array(repeating: GridItem(.flexible(), spacing: compact ? 12 : 20), count: compact ? 2 : 4)- return VStack(spacing: 20) {- Rectangle().fill(.white.opacity(0.10)).frame(height: 1)- LazyVGrid(columns: columns, spacing: compact ? 12 : 16) {+ let items = {+ Group {hint(.activate, "console.play", "console.play", primary: true, compact: compact) { if let id = state.focusedGame?.id { driver.play(id) } }hint(.options, "console.options", "console.options", compact: compact) { if let id = state.focusedGame?.id { driver.openOptions(id) } }hint(.controllers, "console.controllers", "console.controllers", compact: compact) { driver.openControllers() }hint(.back, "console.desktop", "console.desktop", compact: compact) { driver.exitToDesktop() }}}+ return VStack(spacing: 20) {+ Rectangle().fill(.white.opacity(0.10)).frame(height: 1)+ if compact {+ // equal pills, two by two+ LazyVGrid(columns: Array(repeating: GridItem(.flexible(), spacing: 12), count: 2), spacing: 12) { items() }+ } else {+ // inline glyph and label, the group centered as a whole with even spacing, the active one a cream pill+ HStack(spacing: 44) { items() }.frame(maxWidth: .infinity)+ }+ }}private func hint(_ role: ConsoleGlyphs.Role, _ key: String, _ id: String, primary: Bool = false, compact: Bool, action: @escaping () -> Void) -> some View {Button(action: action) {HStack(alignment: .center, spacing: 10) { ConsoleGlyphView(glyph: glyphs.glyph(for: role), size: compact ? 20 : 24); Text(t(key)).lineLimit(1).minimumScaleFactor(0.8) }.font(.manrope(compact ? 15 : 20, .semibold))- .padding(.horizontal, 12).frame(maxWidth: .infinity, minHeight: 48)+ .padding(.horizontal, compact ? 12 : (primary ? 20 : 8)).frame(maxWidth: compact ? .infinity : nil, minHeight: 48).foregroundStyle(primary ? LauncherPalette.background : .white.opacity(0.8))- .background(primary ? LauncherPalette.cream : .white.opacity(0.07), in: Capsule())+ .background(primary ? LauncherPalette.cream : (compact ? .white.opacity(0.07) : .clear), in: Capsule()).contentShape(Capsule())}.buttonStyle(.plain).padTarget(id, scope: "console", radius: 28, activate: action)@@ -396,7 +409,7 @@ enum ConsoleInput {switch sheet {case .controllers: return "console.controllers"case .options: return "console.options"- case .explanation: return "console.setup"+ case .explanation: return "console.explanationTitle"}}private func resetFocus() {diff --git a/frontend/Sources/NSPortBuilder/LiveConsoleDriver.swift b/frontend/Sources/NSPortBuilder/LiveConsoleDriver.swiftindex 471adcb2..3a36acd5 100644--- a/frontend/Sources/NSPortBuilder/LiveConsoleDriver.swift+++ b/frontend/Sources/NSPortBuilder/LiveConsoleDriver.swift@@ -115,6 +115,7 @@ struct ConsolePadSnapshot: Equatable {static func status(of game: LibraryGame, brokenMessage: String) -> ConsoleGame.Status {if game.isReady { return .ready }+ if game.hasIOSBuild || game.onDevice { return .iphoneOnly } // built for iPhone: this Mac cannot play it until it is built for Macif !game.appPath.isEmpty { return .broken(brokenMessage) } // an app is recorded but is not a complete game appreturn game.inputs.values.contains { !$0.isEmpty } ? .needsBuild : .needsData}@@ -136,12 +137,43 @@ struct ConsolePadSnapshot: Equatable {status: Self.status(of: game, brokenMessage: t("console.broken")), settings: settings, values: values)}- /// The app's version as its Info.plist states it; empty for a game that has no app yet.+ private var versions: [String: String] = [:]++ /// The version of the build the library knows: the Mac app's Info.plist (pack_app.py writes CFBundleShortVersionString), else the+ /// iPhone app's, else the one inside the IPA. Empty only when none of them states one.private func version(of game: LibraryGame) -> String {- let plist = URL(fileURLWithPath: game.appPath).appendingPathComponent("Contents/Info.plist")- guard let data = try? Data(contentsOf: plist),- let info = try? PropertyListSerialization.propertyList(from: data, format: nil) as? [String: Any] else { return "" }- return info["CFBundleShortVersionString"] as? String ?? ""+ for path in [game.appPath, game.iosAppPath, game.ipaPath] where !path.isEmpty {+ if let cached = versions[path] { if !cached.isEmpty { return cached }; continue }+ let found = Self.version(at: path)+ versions[path] = found+ if !found.isEmpty { return found }+ }+ return ""+ }++ /// The display version in a build: a .app (Contents/Info.plist), an iOS .app (Info.plist) or an IPA (Payload/*.app/Info.plist).+ static func version(at path: String) -> String {+ let url = URL(fileURLWithPath: path)+ if url.pathExtension.lowercased() == "ipa" {+ let process = Process(), pipe = Pipe()+ process.executableURL = URL(fileURLWithPath: "/usr/bin/unzip")+ process.arguments = ["-p", path, "Payload/*.app/Info.plist"]+ process.standardOutput = pipe; process.standardError = FileHandle.nullDevice+ guard (try? process.run()) != nil else { return "" }+ let data = pipe.fileHandleForReading.readDataToEndOfFile()+ process.waitUntilExit()+ return version(plist: data)+ }+ for relative in ["Contents/Info.plist", "Info.plist"] {+ if let data = try? Data(contentsOf: url.appendingPathComponent(relative)) { let v = version(plist: data); if !v.isEmpty { return v } }+ }+ return ""+ }++ static func version(plist data: Data) -> String {+ guard let info = try? PropertyListSerialization.propertyList(from: data, format: nil) as? [String: Any] else { return "" }+ let v = (info["CFBundleShortVersionString"] as? String) ?? (info["CFBundleVersion"] as? String) ?? ""+ return v.trimmingCharacters(in: .whitespaces)}/// Covers through the launcher's own lookup, decoded once per image path.@@ -257,14 +289,26 @@ struct ConsolePadSnapshot: Equatable {/// macOS offers apps no way to drop a Bluetooth controller, so this says where to do it instead.func disconnect(controllerID: String) { showToast(t("console.disconnectHint")) }+ /// Controllers that have no player take the next free one, in the order they are listed, as a console does. A fifth has none.+ static func autoAssigned(_ pads: [ConsolePadSnapshot]) -> [ConsolePadSnapshot] {+ var used = Set(pads.compactMap(\.playerIndex))+ return pads.map { pad in+ guard pad.playerIndex == nil, let free = (1...4).first(where: { !used.contains($0) }) else { return pad }+ used.insert(free)+ var assigned = pad; assigned.playerIndex = free+ return assigned+ }+ }+func padsChanged(connected: Bool, note: Notification) {refreshControllers(announce: false)guard let pad = note.object as? GCController else { return }let name = pad.vendorName ?? pad.productCategory- let player = state.padMerge ? 1 : state.controllers.first { $0.name == name }?.player- if connected {- showToast(player.map { String(format: t("console.connected"), name, $0) } ?? String(format: t("console.connectedUnassigned"), name))- } else { showToast(String(format: t("console.disconnected"), name)) }+ guard connected else { showToast(String(format: t("console.disconnected"), name)); return }+ let id = String(UInt(bitPattern: ObjectIdentifier(pad).hashValue), radix: 16)+ if let player = state.padMerge ? 1 : state.controllers.first(where: { $0.id == id })?.player {+ showToast(String(format: t("console.connected"), name, player))+ } else { showToast(t("console.noFreePlayer"), glyph: ConsoleGlyphs.current().glyph(for: .controllers)) }}func refreshControllers(announce: Bool) {@@ -282,7 +326,11 @@ struct ConsolePadSnapshot: Equatable {charging: c.battery.map { $0.batteryState == .charging } ?? false)}}- state.controllers = snapshots.map(\.controller)+ let assigned = Self.autoAssigned(snapshots)+ for (before, after) in zip(snapshots, assigned) where before.playerIndex != after.playerIndex {+ devices[after.id]?.playerIndex = GCControllerPlayerIndex(rawValue: (after.playerIndex ?? 1) - 1) ?? .indexUnset+ }+ state.controllers = assigned.map(\.controller)}// MARK: Navigation@@ -292,9 +340,9 @@ struct ConsolePadSnapshot: Equatable {func exitToDesktop() { state.exitToDesktop() }func returnFromGame() { state.returnFromGame() }- private func showToast(_ message: String) {+ private func showToast(_ message: String, glyph: ConsoleGlyphs.Glyph? = nil) {toastTask?.cancel()- state.toast = ConsoleToast(message: message)+ state.toast = ConsoleToast(glyph: glyph, message: message)toastTask = Task { [weak self] intry? await Task.sleep(nanoseconds: 3_000_000_000)guard !Task.isCancelled else { return }diff --git a/frontend/Sources/NSPortBuilder/Localization.swift b/frontend/Sources/NSPortBuilder/Localization.swiftindex f9e5df64..3384aa7a 100644--- a/frontend/Sources/NSPortBuilder/Localization.swift+++ b/frontend/Sources/NSPortBuilder/Localization.swift@@ -154,6 +154,13 @@ enum L10n {"console.promptSettingNote": ("\u{6bcf}\u{6b21}\u{542f}\u{52a8}\u{6700}\u{591a}\u{63d0}\u{793a}\u{4e00}\u{6b21}\u{3002}", "At most once each time the launcher starts."),"console.menuLeave": ("\u{9000}\u{51fa}\u{4e3b}\u{673a}\u{6a21}\u{5f0f}", "Leave Console Mode"),"console.promptNever": ("\u{4e0d}\u{518d}\u{63d0}\u{793a}", "Don\u{2019}t ask again"),+ "console.notBuilt": ("\u{5c1a}\u{672a}\u{6784}\u{5efa}", "Not built yet"),+ "console.needsDataBadge": ("\u{9700}\u{8981}\u{6e38}\u{620f}\u{6570}\u{636e}", "Needs game data"),+ "console.iphoneOnly": ("\u{4ec5} iPhone \u{7248}", "iPhone only"),+ "console.iphoneOnlyNote": ("\u{8fd9}\u{6b3e}\u{6e38}\u{620f}\u{53ea}\u{6784}\u{5efa}\u{4e86} iPhone \u{7248}\u{3002}\u{8bf7}\u{5728}\u{684c}\u{9762}\u{6a21}\u{5f0f}\u{7684}\u{201c}\u{6784}\u{5efa}\u{201d}\u{9875}\u{9762}\u{6784}\u{5efa} Mac \u{7248}\u{ff0c}\u{4e4b}\u{540e}\u{5c31}\u{80fd}\u{5728}\u{8fd9}\u{91cc}\u{6e38}\u{73a9}\u{3002}", "This game is built for iPhone only. Build it for Mac on the Builds page in desktop mode, then play it here."),+ "console.explanationTitle": ("\u{6682}\u{65f6}\u{65e0}\u{6cd5}\u{6e38}\u{73a9}", "Not ready to play"),+ "console.connectedNextPlayer": ("%@ \u{5df2}\u{8fde}\u{63a5}\u{ff0c}\u{73a9}\u{5bb6} %d", "%@ connected, player %d"),+ "console.noFreePlayer": ("\u{56db}\u{4f4d}\u{73a9}\u{5bb6}\u{90fd}\u{5df2}\u{5360}\u{7528}\u{3002}\u{8bf7}\u{6253}\u{5f00}\u{624b}\u{67c4}\u{9875}\u{9762}\u{8c03}\u{6574}\u{3002}", "All four players are taken. Open Controllers to change them."),"console.mergeEach": ("\u{6bcf}\u{4e2a}\u{624b}\u{67c4}\u{5bf9}\u{5e94}\u{4e00}\u{4f4d}\u{73a9}\u{5bb6}", "Each controller is its own player"),"console.mockPress": ("\u{6a21}\u{62df}\u{6309}\u{4e0b}\u{6309}\u{94ae}", "Simulate a button press"),"console.connectedUnassigned": ("%@ \u{5df2}\u{8fde}\u{63a5}", "%@ connected"),diff --git a/frontend/Sources/NSPortBuilder/MockConsoleDriver.swift b/frontend/Sources/NSPortBuilder/MockConsoleDriver.swiftindex 32a80abc..9a9514fe 100644--- a/frontend/Sources/NSPortBuilder/MockConsoleDriver.swift+++ b/frontend/Sources/NSPortBuilder/MockConsoleDriver.swift@@ -33,7 +33,7 @@ import SwiftUIartwork: artworkRepo.flatMap { repo inGameLibrary.artwork(for: LibraryGame(titleID: String(format: "%016X", index), name: title), repo: repo, banners: noBanners)}.map { Image(nsImage: $0) }, // nil: the view draws a placeholder cover from the title- status: index == 3 ? .needsBuild : index == 5 ? .needsData : index == 7 ? .broken(t("console.demoBroken")) : .ready,+ status: index == 3 ? .needsBuild : index == 5 ? .needsData : index == 7 ? .broken(t("console.demoBroken")) : index == 9 ? .iphoneOnly : .ready,settings: settings)}var snapshot = ConsoleState(games: scenario == .empty ? [] : scenario == .few ? Array(games.prefix(2)) : games,diff --git a/frontend/Tests/NSPortBuilderTests/ConsoleLiveTests.swift b/frontend/Tests/NSPortBuilderTests/ConsoleLiveTests.swiftindex b8f128ee..50771fd4 100644--- a/frontend/Tests/NSPortBuilderTests/ConsoleLiveTests.swift+++ b/frontend/Tests/NSPortBuilderTests/ConsoleLiveTests.swift@@ -173,4 +173,42 @@ import SwiftUIXCTAssertFalse(BatteryIcon.isLow(0.21))XCTAssertFalse(BatteryIcon.isLow(nil))}++ func testPlayersAreAssignedAutomaticallyInOrder() {+ func pad(_ id: String, _ player: Int?) -> ConsolePadSnapshot { ConsolePadSnapshot(id: id, name: id, category: nil, playerIndex: player) }+ let result = LiveConsoleDriver.autoAssigned([pad("a", nil), pad("b", 1), pad("c", nil), pad("d", nil)])+ XCTAssertEqual(result.map(\.playerIndex), [2, 1, 3, 4], "the next free players, never one already taken")+ let full = LiveConsoleDriver.autoAssigned([pad("a", 1), pad("b", 2), pad("c", 3), pad("d", 4), pad("e", nil)])+ XCTAssertNil(full.last?.playerIndex, "a fifth controller has no free player")+ XCTAssertEqual(LiveConsoleDriver.autoAssigned([pad("a", 3)]).map(\.playerIndex), [3], "an assigned one keeps its player")+ }++ func testDriverListsFakeControllersWithPlayers() throws {+ let pads = [ConsolePadSnapshot(id: "a", name: "Pad", category: "Xbox One", playerIndex: nil)]+ let (driver, _, _) = try makeDriver(pads: pads)+ XCTAssertEqual(driver.state.controllers.first?.player, 1, "never shown as unassigned")+ }++ func testIPhoneOnlyAndNotBuiltStatuses() throws {+ var ios = LibraryGame(titleID: titleID, name: "A")+ ios.iosAppPath = temporary.path // any folder with an Info.plist counts as an iOS app+ try Data([0]).write(to: temporary.appendingPathComponent("Info.plist"))+ XCTAssertEqual(LiveConsoleDriver.status(of: ios, brokenMessage: "x"), .iphoneOnly)+ XCTAssertEqual(LiveConsoleDriver.platforms(of: ios), [.iphone])+ XCTAssertEqual(LiveConsoleDriver.status(of: LibraryGame(titleID: titleID, name: "B"), brokenMessage: "x"), .needsData)+ XCTAssertEqual(ConsoleGame.Status.iphoneOnly.labelKey, "console.iphoneOnly")+ XCTAssertEqual(ConsoleGame.Status.needsBuild.labelKey, "console.notBuilt")+ XCTAssertEqual(ConsoleGame.Status.needsData.labelKey, "console.needsDataBadge")+ }++ func testVersionFromMacAppIOSAppAndPlist() throws {+ XCTAssertEqual(LiveConsoleDriver.version(plist: try PropertyListSerialization.data(fromPropertyList: ["CFBundleShortVersionString": "1.2.3"], format: .xml, options: 0)), "1.2.3")+ XCTAssertEqual(LiveConsoleDriver.version(plist: try PropertyListSerialization.data(fromPropertyList: ["CFBundleVersion": "7"], format: .xml, options: 0)), "7")+ XCTAssertEqual(LiveConsoleDriver.version(plist: Data([0])), "")+ let ios = temporary.appendingPathComponent("ios.app")+ try FileManager.default.createDirectory(at: ios, withIntermediateDirectories: true)+ try PropertyListSerialization.data(fromPropertyList: ["CFBundleShortVersionString": "2.0.1"], format: .xml, options: 0).write(to: ios.appendingPathComponent("Info.plist"))+ XCTAssertEqual(LiveConsoleDriver.version(at: ios.path), "2.0.1")+ XCTAssertEqual(LiveConsoleDriver.version(at: temporary.appendingPathComponent("none.app").path), "")+ }}diff --git a/frontend/Tests/NSPortBuilderTests/ConsoleTests.swift b/frontend/Tests/NSPortBuilderTests/ConsoleTests.swiftindex 708dc59b..d0f9165d 100644--- a/frontend/Tests/NSPortBuilderTests/ConsoleTests.swift+++ b/frontend/Tests/NSPortBuilderTests/ConsoleTests.swift@@ -26,7 +26,7 @@ final class ConsoleTests: XCTestCase {}@MainActor func testPlayExplainsEachUnavailableStatus() {- for (id, key) in [("demo.3", "console.needsBuild"), ("demo.5", "console.needsData"), ("demo.7", "console.broken")] {+ for (id, key) in [("demo.3", "console.needsBuild"), ("demo.5", "console.needsData"), ("demo.7", "console.broken"), ("demo.9", "console.iphoneOnlyNote")] {let driver = MockConsoleDriver(animated: false)driver.focus(id)driver.play(id)@@ -182,7 +182,7 @@ final class ConsoleTests: XCTestCase {XCTAssertNotEqual(L10n.string(key, lang), key)}}- for status in [ConsoleGame.Status.ready, .needsBuild, .needsData, .broken("")] {+ for status in [ConsoleGame.Status.ready, .needsBuild, .needsData, .iphoneOnly, .broken("")] {XCTAssertNotNil(L10n.table[status.labelKey])if let key = status.explanationKey { XCTAssertNotNil(L10n.table[key]) }}