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
The Manage button opens a dropdown in the launcher's own style that a controller can use, and Y opens it instead of Saves
v0lumehi3050306e34ae
diff --git a/frontend/Sources/NSPortBuilder/LauncherView.swift b/frontend/Sources/NSPortBuilder/LauncherView.swiftindex 20286b83..0654e89d 100644--- a/frontend/Sources/NSPortBuilder/LauncherView.swift+++ b/frontend/Sources/NSPortBuilder/LauncherView.swift@@ -37,6 +37,7 @@ struct ContentView: View {@State private var freeSpaceFor: UUID? // the game whose Free space sheet is open@State private var controlsOpen = false@State private var savesFor: UUID? // the game whose Saves sheet is open (SaveTransfer.swift)+ @State private var manageOpenFor: UUID? // the game whose Manage menu is open (ManageMenu.swift)@StateObject private var controls = ControlLayout()@StateObject private var gamepad = LauncherGamepad()@StateObject private var padFocus = PadFocus()@@ -44,10 +45,13 @@ struct ContentView: View {@StateObject private var toolsAge: ToolsAge@State private var buildCommit = "" // the checkout's commit when the running build started (ToolsAge)private var performStartupChecks: Bool+ private let qaManage: (open: Bool, ring: Bool) // visual QA: the Manage menu open at launch, with the controller's focus ring or without@Environment(\.scenePhase) private var scenePhaseinit(model: BuildModel? = nil, library: GameLibrary? = nil, initialPage: LauncherPage = .library,- activeBuildID: UUID? = nil, performStartupChecks: Bool = true, search: String? = nil, olderTools: Set<UUID> = []) {+ activeBuildID: UUID? = nil, performStartupChecks: Bool = true, search: String? = nil, olderTools: Set<UUID> = [],+ manageOpen: Bool = false, padRing: Bool = false) {+ qaManage = (manageOpen, padRing)if let search { _search = State(initialValue: search); _searching = State(initialValue: true) } // visual QA: the bar with its field open_toolsAge = StateObject(wrappedValue: ToolsAge(older: olderTools)) // visual QA: games marked without a checkout to compare_m = StateObject(wrappedValue: model ?? BuildModel())@@ -77,6 +81,14 @@ struct ContentView: View {}.padScope("main", padFocus).environmentObject(padFocus)+ .manageMenuOverlay(items: manageOpenFor.flatMap { id in library.games.first { $0.id == id } }.map(manageItems),+ label: m.t("library.manage"), pad: padFocus) { manageOpenFor = nil }+ .onChange(of: manageOpenFor) { id in+ padFocus.scope = id != nil ? "manage" : currentPadScope+ if id != nil, padFocus.visible { // opened by the controller: its focus lands on the first usable row+ DispatchQueue.main.async { padFocus.show(default: ManagePad.firstFocus(manageItems(for: library.selected))) }+ }+ }.background(LauncherPalette.background).background(LauncherWindowChrome()).ignoresSafeArea(.container, edges: .top)@@ -86,6 +98,10 @@ struct ContentView: View {.frame(minWidth: 900, idealWidth: 1280, minHeight: 680, idealHeight: 900).onAppear {gamepad.perform = padAction+ if qaManage.open {+ if qaManage.ring { padFocus.show(default: nil) }+ manageOpenFor = library.selected?.id+ }refreshArtwork()if performStartupChecks { library.discover(); fetchArtwork(); m.refreshDevices(); checkTools() }if performStartupChecks {@@ -152,12 +168,12 @@ struct ContentView: View {.sheet(isPresented: Binding(get: { freeSpaceFor != nil }, set: { if !$0 { freeSpaceFor = nil } })) {if let game = library.games.first(where: { $0.id == freeSpaceFor }) { FreeSpaceView(m: m, game: game).environmentObject(padFocus) }}- .onChange(of: freeSpaceFor) { id in padFocus.scope = id != nil ? "free" : "main" }+ .onChange(of: freeSpaceFor) { id in padFocus.scope = id != nil ? "free" : currentPadScope }.sheet(isPresented: $m.showUpdateSheet) { UpdateSheet(m: m) }.sheet(isPresented: Binding(get: { savesFor != nil }, set: { if !$0 { savesFor = nil } })) {if let id = savesFor { SavesView(m: m, library: library, gameID: id).environmentObject(padFocus) }}- .onChange(of: savesFor) { id in padFocus.scope = id != nil ? "saves" : "main" }+ .onChange(of: savesFor) { id in padFocus.scope = id != nil ? "saves" : currentPadScope }.onChange(of: optionsFor) { id in padFocus.scope = id != nil ? "launch" : (controlsOpen ? "controls" : "main") }.onChange(of: controlsOpen) { open in padFocus.scope = open ? "controls" : (optionsFor != nil ? "launch" : "main") }.onChange(of: page) { _ in padFocus.focused = nil }@@ -354,29 +370,10 @@ struct ContentView: View {.buttonStyle(.plain).help(m.t("launch.title")).accessibilityLabel(m.t("launch.title")).padTarget("hero.options", scope: "main", radius: 24) { optionsFor = game.id }}- Menu {- Button(m.t(toolsAge.older.contains(game.id) ? "library.rebuild" : "library.buildAgain")) { configureBuild(game) }.disabled(m.running || game.inputs["base", default: []].isEmpty)- if game.isReady { Button(m.t("launch.title")) { optionsFor = game.id } }- Button(m.t("saves.menu")) { savesFor = game.id }- Button(m.t("library.changeArtwork")) { chooseArtwork(game) }- if !game.artworkPath.isEmpty {- Button(m.t("library.resetArtwork")) { library.setArtwork("", for: game.id) }- }- if !game.appPath.isEmpty {- Button(m.t("install.reveal")) {- NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: game.appPath)])- }- }- if BuildFolder.location(for: game) != nil { Button(m.t("free.menu")) { freeSpaceFor = game.id } }- Divider()- Button(m.t("library.remove"), role: .destructive) { removing = game }.disabled(game.id == activeBuildID)- } label: {- HStack(spacing: 9) {- Image(systemName: "ellipsis.circle").font(.system(size: 27, weight: .ultraLight))- Text(m.t("library.manage")).font(.manrope(13))- }- }- .menuStyle(.borderlessButton).fixedSize().foregroundStyle(.white)+ Button { manageOpenFor = manageOpenFor == nil ? game.id : nil } label: { ManageButtonLabel(title: m.t("library.manage")) }+ .buttonStyle(.plain).accessibilityLabel(m.t("library.manage"))+ .anchorPreference(key: ManageAnchorKey.self, value: .bounds) { $0 }+ .padTarget("hero.manage", scope: "main", radius: 12) { manageOpenFor = game.id }}}.padding(.horizontal, 34).padding(.bottom, 34)@@ -533,7 +530,7 @@ struct ContentView: View {// The buttons a controller has here, named as the game names them (A on the right)HStack(spacing: 18) {padHint("A", m.t("pad.play")); padHint("X", m.t("pad.options")); padHint("B", m.t("pad.back"))- padHint("Y", m.t("pad.saves"))+ padHint("Y", m.t("pad.manage"))Image(systemName: "gamecontroller").foregroundStyle(.secondary)}}@@ -583,6 +580,16 @@ struct ContentView: View {/// game's launch options, L and R switch the pages.private func padAction(_ action: LauncherGamepad.Action) {let sheetOpen = optionsFor != nil || controlsOpen || savesFor != nil || freeSpaceFor != nil+ switch ManagePad.route(action, menuOpen: manageOpenFor != nil, sheetOpen: sheetOpen, hasGame: library.selected != nil && page == .library) {+ case .close: manageOpenFor = nil; return+ case .swallow: return+ case .open:+ guard let game = library.selected else { return }+ padFocus.show(default: nil) // the ring shows: the menu's own focus follows once it is drawn+ manageOpenFor = game.id+ return+ case .pass: break+ }if action == .b, savesFor != nil { savesFor = nil; return }// The Free space sheet: B closes it, the D-pad and A work in it, X, L and R do nothing behind itif freeSpaceFor != nil && [.b, .x, .l, .r].contains(action) { if action == .b { freeSpaceFor = nil }; return }@@ -593,7 +600,8 @@ struct ContentView: View {}if removing != nil { return } // the remove dialog is AppKit's; it takes the mouse or the keyboardif !padFocus.visible {- padFocus.show(default: !sheetOpen && page == .library ? library.selectedID.map { "card." + $0.uuidString } : nil)+ padFocus.show(default: manageOpenFor != nil ? ManagePad.firstFocus(manageItems(for: library.selected))+ : !sheetOpen && page == .library ? library.selectedID.map { "card." + $0.uuidString } : nil)if [.up, .down, .left, .right].contains(action) { return } // the first press only shows where the focus is}switch action {@@ -608,13 +616,31 @@ struct ContentView: View {guard !sheetOpen, let at = LauncherPage.allCases.firstIndex(of: page) else { return }let pages = LauncherPage.allCasespage = pages[(at + (action == .l ? pages.count - 1 : 1)) % pages.count]- case .y: // the selected game's saves: the Manage menu is AppKit's, which a controller cannot open- if !sheetOpen, let game = library.selected { savesFor = game.id }+ case .y: // the Manage menu: ManagePad.route opened it above+ returncase .b:return}}+ /// The Manage menu's rows for a game, wired to the launcher's sheets and actions (ManageItem.list).+ private func manageItems(_ game: LibraryGame) -> [ManageItem] {+ ManageItem.list(game: game, labels: m.t, running: m.running, olderTools: toolsAge.older.contains(game.id), activeBuildID: activeBuildID,+ hasBuildFolder: BuildFolder.location(for: game) != nil,+ 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)]) },+ freeSpace: { freeSpaceFor = game.id }, remove: { removing = game }))+ }++ private func manageItems(for game: LibraryGame?) -> [ManageItem] { game.map(manageItems) ?? [] }++ /// The scope a controller acts in when no menu is open: the innermost sheet, else the window.+ private var currentPadScope: String {+ savesFor != nil ? "saves" : freeSpaceFor != nil ? "free" : optionsFor != nil ? "launch" : controlsOpen ? "controls" : "main"+ }+/// The space the collection row keeps around its cards for the focus ring (PadFocus draws it 4 pt outside a target).static let ringRoom: CGFloat = 6diff --git a/frontend/Sources/NSPortBuilder/Localization.swift b/frontend/Sources/NSPortBuilder/Localization.swiftindex 0764d70c..c9565583 100644--- a/frontend/Sources/NSPortBuilder/Localization.swift+++ b/frontend/Sources/NSPortBuilder/Localization.swift@@ -94,7 +94,7 @@ enum L10n {"saves.noMacSave": ("这台 Mac 上还没有这个游戏的存档。", "This Mac has no save for this game yet."),"saves.noDeviceSave": ("%@ 上还没有这个游戏的存档。", "%@ has no save for this game yet."),"saves.failed": ("复制失败:%@", "Copying failed: %@"),- "pad.saves": ("存档", "Saves"),+ "pad.manage": ("管理", "Manage"),"dev.signStage": ("\u{4e3a} %@ \u{7b7e}\u{540d}", "Sign for %@"),"dev.installStage": ("\u{5b89}\u{88c5}\u{5230} %@", "Install on %@"),"dev.copyStage": ("复制游戏文件到 %@", "Copy the game files to %@"),diff --git a/frontend/Sources/NSPortBuilder/ManageMenu.swift b/frontend/Sources/NSPortBuilder/ManageMenu.swiftnew file mode 100644index 00000000..1f4378b9--- /dev/null+++ b/frontend/Sources/NSPortBuilder/ManageMenu.swift@@ -0,0 +1,203 @@+import SwiftUI++/// What the Manage menu of a game's hero does. One closure per item, so the menu (ManageItem.list) and its tests never+/// reach into the launcher's state.+struct ManageActions {+ var rebuild: () -> Void = {}+ var options: () -> Void = {}+ var saves: () -> Void = {}+ var changeArtwork: () -> Void = {}+ var resetArtwork: () -> Void = {}+ var reveal: () -> Void = {}+ var freeSpace: () -> Void = {}+ var remove: () -> Void = {}+}++/// One row of the Manage menu.+struct ManageItem: Identifiable {+ let id: String+ let symbol: String+ let title: String+ var enabled = true+ var destructive = false+ var separatorBefore = false+ let run: () -> Void++ /// The menu's rows, in order, built in one place: a new item is one line here. The rules are the ones the system menu had:+ /// Build again is off while a build runs or with no recorded inputs, Remove while this game is the one building.+ static func list(game: LibraryGame, labels t: (String) -> String, running: Bool, olderTools: Bool, activeBuildID: UUID?,+ hasBuildFolder: Bool, actions a: ManageActions) -> [ManageItem] {+ var items = [ManageItem(id: "rebuild", symbol: "arrow.clockwise", title: t(olderTools ? "library.rebuild" : "library.buildAgain"),+ enabled: !running && !game.inputs["base", default: []].isEmpty, run: a.rebuild)]+ if game.isReady { items.append(.init(id: "options", symbol: "slider.horizontal.3", title: t("launch.title"), run: a.options)) }+ 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 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))+ return items+ }++ /// The pad-focus id of the row.+ var padID: String { "manage." + id }+}++/// What a controller's button does around the Manage menu; the rest of the launcher's routing stays in ContentView.padAction.+enum ManagePad {+ enum Route: Equatable {+ case open // Y: open the selected game's menu+ case close // B: close it+ case swallow // X, Y, L and R while it is open: nothing happens behind it+ case pass // the D-pad and A (PadFocus moves or activates in the menu's scope), or any button with the menu closed+ }++ static func route(_ action: LauncherGamepad.Action, menuOpen: Bool, sheetOpen: Bool, hasGame: Bool) -> Route {+ if menuOpen {+ switch action {+ case .b: return .close+ case .x, .y, .l, .r: return .swallow+ case .up, .down, .left, .right, .a: return .pass+ }+ }+ return action == .y && !sheetOpen && hasGame ? .open : .pass+ }++ /// The row a controller lands on when the menu opens: the first one that can be used.+ static func firstFocus(_ items: [ManageItem]) -> String? { items.first { $0.enabled }?.padID }+}++/// The hero's Manage button reports its frame here so the menu opens against it, outside the hero's clipping.+struct ManageAnchorKey: PreferenceKey {+ static var defaultValue: Anchor<CGRect>?+ static func reduce(value: inout Anchor<CGRect>?, nextValue: () -> Anchor<CGRect>?) { value = value ?? nextValue() }+}++extension View {+ /// Draws the Manage menu over the window when `items` is non-nil, above the button that reported ManageAnchorKey (below it+ /// when there is no room above), with a click anywhere else closing it.+ func manageMenuOverlay(items: [ManageItem]?, label: String, pad: PadFocus, close: @escaping () -> Void) -> some View {+ overlayPreferenceValue(ManageAnchorKey.self) { anchor in+ GeometryReader { g in+ if let items, let anchor {+ let button = g[anchor]+ let height = ManageMenuPanel.height(items)+ let above = button.minY - 8 - height >= ManageMenuPanel.topInset // not over the top bar+ ZStack(alignment: .topLeading) {+ Color.black.opacity(0.001).contentShape(Rectangle()).onTapGesture(perform: close)+ .accessibilityHidden(true)+ ManageMenuPanel(items: items, label: label, close: close).environmentObject(pad)+ .offset(x: min(max(button.minX, 8), max(8, g.size.width - ManageMenuPanel.width - 8)),+ y: above ? button.minY - 8 - height : min(button.maxY + 8, max(8, g.size.height - height - 8)))+ }+ }+ }+ }+ }+}++/// The Manage button's look: the icon and the word, as the system menu's label had them.+struct ManageButtonLabel: View {+ let title: String+ var body: some View {+ HStack(spacing: 9) {+ Image(systemName: "ellipsis.circle").font(.system(size: 27, weight: .ultraLight))+ Text(title).font(.manrope(13))+ }+ .foregroundStyle(.white).contentShape(Rectangle())+ }+}++/// The dropdown: the app's dark surface with its border and radius, a symbol and a label per row, Remove in red under a+/// divider. Arrow keys move, Return activates, Esc closes (a local key monitor while it is open: the hero's Play button+/// owns Return otherwise); a controller moves by PadFocus in the "manage" scope.+struct ManageMenuPanel: View {+ static let width: CGFloat = 250+ static let rowHeight: CGFloat = 36+ static let topInset: CGFloat = 74 // the top bar (65 pt) and a gap+ static func height(_ items: [ManageItem]) -> CGFloat {+ CGFloat(items.count) * rowHeight + CGFloat(items.filter(\.separatorBefore).count) * 9 + 12+ }++ let items: [ManageItem]+ let label: String+ let close: () -> Void+ @State private var highlighted: Int?+ @State private var monitor: Any?+ @EnvironmentObject private var pad: PadFocus++ var body: some View {+ VStack(alignment: .leading, spacing: 0) {+ ForEach(Array(items.enumerated()), id: \.element.id) { index, item in+ if item.separatorBefore { Divider().opacity(0.4).padding(.vertical, 4).padding(.horizontal, 6) }+ row(item, index: index)+ }+ }+ .padding(6)+ .frame(width: Self.width)+ .background(LauncherPalette.surface, in: RoundedRectangle(cornerRadius: 12))+ .overlay(RoundedRectangle(cornerRadius: 12).strokeBorder(Color.white.opacity(0.10)))+ .shadow(color: .black.opacity(0.5), radius: 18, y: 6)+ .padScope("manage", pad)+ .accessibilityElement(children: .contain)+ .accessibilityLabel(label)+ .onAppear(perform: startKeys)+ .onDisappear(perform: stopKeys)+ }++ private func row(_ item: ManageItem, index: Int) -> some View {+ let tint = item.destructive ? Color(red: 1, green: 0.42, blue: 0.40) : Color.white.opacity(0.92)+ return Button { activate(item) } label: {+ HStack(spacing: 11) {+ Image(systemName: item.symbol).font(.system(size: 13, weight: .medium)).frame(width: 18)+ Text(item.title).font(.manrope(13, .medium)).lineLimit(1)+ Spacer(minLength: 0)+ }+ .foregroundStyle(tint).opacity(item.enabled ? 1 : 0.4)+ .padding(.horizontal, 10).frame(height: Self.rowHeight)+ .background(highlighted == index && item.enabled ? Color.white.opacity(0.08) : .clear, in: RoundedRectangle(cornerRadius: 8))+ .contentShape(RoundedRectangle(cornerRadius: 8))+ }+ .buttonStyle(.plain)+ .disabled(!item.enabled)+ .onHover { inside in if inside && item.enabled { highlighted = index } else if !inside && highlighted == index { highlighted = nil } }+ .accessibilityLabel(item.title)+ .padTarget(item.padID, scope: "manage", radius: 8) { activate(item) }+ }++ private func activate(_ item: ManageItem) {+ guard item.enabled else { return }+ close()+ item.run()+ }++ private func step(_ delta: Int) {+ let usable = items.indices.filter { items[$0].enabled }+ guard !usable.isEmpty else { return }+ if let current = highlighted, let at = usable.firstIndex(of: current) {+ highlighted = usable[(at + delta + usable.count) % usable.count]+ } else {+ highlighted = delta > 0 ? usable.first : usable.last+ }+ }++ private func startKeys() {+ stopKeys()+ monitor = NSEvent.addLocalMonitorForEvents(matching: .keyDown) { event in+ switch event.keyCode {+ case 125: step(1)+ case 126: step(-1)+ case 36, 76: if let i = highlighted, items.indices.contains(i) { activate(items[i]) }+ case 53: close()+ default: return event+ }+ return nil+ }+ }++ private func stopKeys() {+ if let monitor { NSEvent.removeMonitor(monitor) }+ monitor = nil+ }+}diff --git a/frontend/Tests/NSPortBuilderTests/LibraryTests.swift b/frontend/Tests/NSPortBuilderTests/LibraryTests.swiftindex aa256301..01605f04 100644--- a/frontend/Tests/NSPortBuilderTests/LibraryTests.swift+++ b/frontend/Tests/NSPortBuilderTests/LibraryTests.swift@@ -653,10 +653,10 @@ final class LibraryTests: XCTestCase {model.slots[0].paths = []library.selectedID = library.games.first?.idfunc capture(_ name: String, width: CGFloat = 1440, height: CGFloat = 1024, page: LauncherPage = .library, activeID: UUID? = nil, empty: Bool = false,- search: String? = nil, older: Set<UUID> = []) throws {+ search: String? = nil, older: Set<UUID> = [], manageOpen: Bool = false, padRing: Bool = false) throws {let store = empty ? GameLibrary(file: temporary.appendingPathComponent("empty.json")) : librarylet view = ContentView(model: model, library: store, initialPage: page, activeBuildID: activeID, performStartupChecks: false, search: search,- olderTools: older)+ olderTools: older, manageOpen: manageOpen, padRing: padRing)let host = NSHostingView(rootView: view)let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: width, height: height),styleMask: [.titled, .closable, .resizable], backing: .buffered, defer: false)@@ -673,6 +673,9 @@ final class LibraryTests: XCTestCase {try capture("library")try capture("library-search", search: "zel")try capture("library-small", width: 900, height: 680)+ try capture("manage-menu", manageOpen: true) // the Manage menu open, mouse look+ try capture("manage-menu-pad", manageOpen: true, padRing: true) // opened by the controller: the ring on the first row+ try capture("manage-menu-small", width: 900, height: 680, manageOpen: true, padRing: true)try capture("library-fullscreen", width: 2000, height: 1125) // the cards at their widest: the row must fit under the herotry capture("empty", empty: true)try capture("build", page: .builds)diff --git a/frontend/Tests/NSPortBuilderTests/ManageMenuTests.swift b/frontend/Tests/NSPortBuilderTests/ManageMenuTests.swiftnew file mode 100644index 00000000..defef5be--- /dev/null+++ b/frontend/Tests/NSPortBuilderTests/ManageMenuTests.swift@@ -0,0 +1,128 @@+import XCTest+@testable import NSPortBuilder++/// The Manage menu: its rows and when they can be used, what a controller's buttons do around it, and that its rows run+/// the actions the system menu ran.+final class ManageMenuTests: XCTestCase {+ private var temporary: URL!++ override func setUpWithError() throws {+ temporary = FileManager.default.temporaryDirectory.appendingPathComponent("nxnative-manage-" + UUID().uuidString)+ try FileManager.default.createDirectory(at: temporary, withIntermediateDirectories: true)+ }++ override func tearDownWithError() throws { try FileManager.default.removeItem(at: temporary) }++ private let titleID = "0100535012974000"++ private func readyGame() throws -> LibraryGame {+ let app = temporary.appendingPathComponent("Hades.app")+ let executables = app.appendingPathComponent("Contents/MacOS")+ try FileManager.default.createDirectory(at: executables, withIntermediateDirectories: true)+ for name in ["nxnative", "dmhost"] {+ try FileManager.default.createSymbolicLink(at: executables.appendingPathComponent(name), withDestinationURL: URL(fileURLWithPath: "/usr/bin/true"))+ }+ let info: [String: Any] = ["DMTitleID": titleID, "CFBundleDisplayName": "Hades", "CFBundleExecutable": "nxnative"]+ try PropertyListSerialization.data(fromPropertyList: info, format: .xml, options: 0).write(to: app.appendingPathComponent("Contents/Info.plist"))+ var game = LibraryGame(titleID: titleID, name: "Hades", appPath: app.path)+ game.inputs = ["base": ["/preview/Hades.nsp"]]+ return game+ }++ private func items(_ game: LibraryGame, running: Bool = false, older: Bool = false, active: UUID? = nil, folder: Bool = false,+ actions: ManageActions = ManageActions()) -> [ManageItem] {+ ManageItem.list(game: game, labels: { L10n.string($0, .en) }, running: running, olderTools: older, activeBuildID: active,+ hasBuildFolder: folder, actions: actions)+ }++ func testAReadyGameHasEveryRowInTheOldOrderAndRemoveLastInRed() throws {+ var game = try readyGame()+ game.artworkPath = "/art.png"+ let list = items(game, folder: true)+ XCTAssertEqual(list.map(\.id), ["rebuild", "options", "saves", "artwork", "resetArtwork", "reveal", "freeSpace", "remove"])+ XCTAssertEqual(list.map(\.title), ["library.buildAgain", "launch.title", "saves.menu", "library.changeArtwork", "library.resetArtwork", "install.reveal", "free.menu", "library.remove"]+ .map { L10n.string($0, .en) })+ XCTAssertTrue(list.allSatisfy(\.enabled))+ XCTAssertEqual(list.last?.destructive, true)+ XCTAssertEqual(list.last?.separatorBefore, true)+ XCTAssertEqual(list.filter(\.destructive).count, 1)+ XCTAssertEqual(list.filter(\.separatorBefore).count, 1)+ }++ func testANotBuiltGameLeavesOutTheRowsThatNeedABuild() {+ var game = LibraryGame(titleID: titleID, name: "Hades")+ var list = items(game)+ XCTAssertEqual(list.map(\.id), ["rebuild", "saves", "artwork", "remove"], "no launch options, Finder or Free space without a build")+ XCTAssertFalse(list[0].enabled, "no recorded inputs: nothing to build again")+ game.inputs = ["base": ["/preview/Hades.nsp"]]+ list = items(game)+ XCTAssertTrue(list[0].enabled)+ }++ func testWhileABuildRunsRebuildIsOffAndRemoveIsOffOnlyForTheGameBuilding() throws {+ let game = try readyGame()+ var list = items(game, running: true, active: game.id)+ XCTAssertFalse(list.first { $0.id == "rebuild" }!.enabled)+ XCTAssertFalse(list.first { $0.id == "remove" }!.enabled)+ XCTAssertTrue(list.first { $0.id == "saves" }!.enabled)+ list = items(game, running: true, active: UUID())+ XCTAssertFalse(list.first { $0.id == "rebuild" }!.enabled, "any running build blocks a new one")+ XCTAssertTrue(list.first { $0.id == "remove" }!.enabled, "another game's build does not block removing this one")+ }++ func testOlderToolsRenameTheFirstRow() throws {+ let game = try readyGame()+ XCTAssertNotEqual(items(game)[0].title, items(game, older: true)[0].title)+ XCTAssertEqual(items(game, older: true)[0].title, L10n.string("library.rebuild", .en))+ }++ func testRowsRunTheirActions() throws {+ let game = try readyGame()+ var log: [String] = []+ let actions = ManageActions(rebuild: { log.append("rebuild") }, options: { log.append("options") }, saves: { log.append("saves") },+ changeArtwork: { log.append("artwork") }, resetArtwork: { log.append("reset") }, reveal: { log.append("reveal") },+ freeSpace: { log.append("free") }, remove: { log.append("remove") })+ for item in items(game, folder: true, actions: actions) { item.run() }+ XCTAssertEqual(log, ["rebuild", "options", "saves", "artwork", "reveal", "free", "remove"])+ }++ func testTheControllerLandsOnTheFirstUsableRow() throws {+ let game = try readyGame()+ XCTAssertEqual(ManagePad.firstFocus(items(game)), "manage.rebuild")+ XCTAssertEqual(ManagePad.firstFocus(items(LibraryGame(titleID: titleID, name: "Hades"))), "manage.saves", "Build again is off: the next row")+ XCTAssertNil(ManagePad.firstFocus([]))+ }++ func testYOpensTheMenuAndNotSaves() {+ XCTAssertEqual(ManagePad.route(.y, menuOpen: false, sheetOpen: false, hasGame: true), .open)+ XCTAssertEqual(ManagePad.route(.y, menuOpen: false, sheetOpen: true, hasGame: true), .pass, "not over a sheet")+ XCTAssertEqual(ManagePad.route(.y, menuOpen: false, sheetOpen: false, hasGame: false), .pass, "no selected game")+ }++ func testBClosesAndXLRYAreIgnoredWhileOpen() {+ XCTAssertEqual(ManagePad.route(.b, menuOpen: true, sheetOpen: false, hasGame: true), .close)+ for button in [LauncherGamepad.Action.x, .l, .r, .y] {+ XCTAssertEqual(ManagePad.route(button, menuOpen: true, sheetOpen: false, hasGame: true), .swallow)+ }+ for button in [LauncherGamepad.Action.up, .down, .left, .right, .a] {+ XCTAssertEqual(ManagePad.route(button, menuOpen: true, sheetOpen: false, hasGame: true), .pass)+ }+ XCTAssertEqual(ManagePad.route(.b, menuOpen: false, sheetOpen: false, hasGame: true), .pass, "closed: B keeps going back")+ }++ func testTheDPadMovesInTheMenusScopeAndAActivates() throws {+ let game = try readyGame()+ var log: [String] = []+ let rows = items(game, actions: ManageActions(rebuild: { log.append("rebuild") }, options: { log.append("options") }, saves: { log.append("saves") }))+ let focus = PadFocus()+ focus.setFrames(rows.enumerated().map { .init(id: $1.padID, frame: CGRect(x: 0, y: CGFloat($0) * 36, width: 250, height: 36)) }, scope: "manage")+ focus.scope = "manage"+ focus.show(default: ManagePad.firstFocus(rows))+ XCTAssertEqual(focus.focused, "manage.rebuild")+ focus.move(dx: 0, dy: 1); focus.move(dx: 0, dy: 1)+ XCTAssertEqual(focus.focused, "manage.saves")+ for row in rows { focus.register(row.padID, .init(activate: row.run)) }+ focus.activate()+ XCTAssertEqual(log, ["saves"])+ }+}