Skip to content

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

Library: owned games only, with an Owned/Built switch

v0lumehi0e2a9a466630
diff --git a/frontend-qt/nspb_qt/localization.py b/frontend-qt/nspb_qt/localization.py
index 6899f94a..88feecf0 100644
--- a/frontend-qt/nspb_qt/localization.py
+++ b/frontend-qt/nspb_qt/localization.py
@@ -427,12 +427,8 @@ TABLE: dict[str, tuple[str, str, str, str]] = {
'library.profileUpdated': ('游戏档案有更新', "This game's profile updated", "This game's profile updated", 'Spielprofil aktualisiert'),
'library.profileUpdatedShort': ('档案有更新', 'Profile updated', 'Profile updated', 'Profil aktualisiert'),
'library.profileUpdatedHelp': ('这个游戏的档案(dm/games)自上次构建后有了更改:修复、着色器表或兼容性调整。重新构建即可用上。', "This game's own profile (dm/games) changed since it was built: fixes, shader tables or compatibility work. Rebuild to get them.", "This game's own profile (dm/games) changed since it was built: fixes, shader tables or compatibility work. Rebuild to get them.", 'Das eigene Spielprofil (dm/games) hat sich seit dem Build geändert: Fehlerbehebungen, Shader-Tabellen oder Kompatibilitätsarbeit. Zum Übernehmen neu bauen.'),
- 'filter.all': ('全部', 'All', 'Alla', 'Alle'),
'filter.owned': ('已拥有', 'Owned', 'Im ägo', 'Im Besitz'),
'filter.built': ('已构建', 'Built', 'Byggda', 'Gebaut'),
- 'library.notOwned': ('未拥有', 'Not owned', 'Ej ägd', 'Nicht im Besitz'),
- 'library.notOwnedShort': ('未拥有', 'Not owned', 'Ej ägd', 'Nicht im Besitz'),
- 'library.notOwnedHint': ('这个游戏在 nxnative 的支持列表里:把它的文件加入游戏文件夹后即可构建。', 'This game is in nxnative’s supported list: add its files to your games folder and it builds.', 'Spelet finns i nxnatives lista: lägg till dess filer i din spelmapp så byggs det.', 'Dieses Spiel ist in nxnatives Liste: füge seine Dateien in deinen Spieleordner ein, dann lässt es sich bauen.'),
'library.rebuild': ('用当前工具重新构建…', 'Rebuild with current tools…', 'Bygg om med aktuella verktyg …', 'Mit aktuellen Werkzeugen neu bauen …'),
'library.rebuildShort': ('重新构建', 'Rebuild', 'Bygg om', 'Neu bauen'),
'library.buildForMac': ('为 Mac 构建', 'Build for Mac', 'Bygg för Mac', 'Für Mac bauen'),
diff --git a/frontend/Sources/NSPortBuilder/LauncherView.swift b/frontend/Sources/NSPortBuilder/LauncherView.swift
index 8ac2465b..d1d0da21 100644
--- a/frontend/Sources/NSPortBuilder/LauncherView.swift
+++ b/frontend/Sources/NSPortBuilder/LauncherView.swift
@@ -21,14 +21,29 @@ enum LauncherPalette {
static let unbuilt = Color(red: 0.57, green: 0.58, blue: 0.61)
}
-/// The library's filter ("全部 / 已拥有 / 已构建"): remembered between launches.
+/// The library's filter: every game in the games folder, or only those with a build. Remembered between launches.
enum LibraryFilter: String, CaseIterable, Identifiable {
- case all, owned, built
+ case owned, built
var id: String { rawValue }
var labelKey: String { "filter." + rawValue }
- static func load() -> LibraryFilter { LibraryFilter(rawValue: UserDefaults.standard.string(forKey: "libraryFilter") ?? "") ?? .all }
- func save() { UserDefaults.standard.set(rawValue, forKey: "libraryFilter") }
+ /// Owned shows every game without reading its build, so the default filter costs nothing per card.
+ func includes(_ game: LibraryGame) -> Bool { self == .owned || game.isReady || game.hasIOSBuild }
+
+ static func load(_ defaults: UserDefaults = .standard) -> LibraryFilter {
+ LibraryFilter(rawValue: defaults.string(forKey: "libraryFilter") ?? "") ?? .owned
+ }
+ func save(_ defaults: UserDefaults = .standard) { defaults.set(rawValue, forKey: "libraryFilter") }
+
+ /// The selection and the controller's focus after a switch to this filter. A selected game the filter hides gives way to the
+ /// first one it shows, and a focus on a hidden card is dropped, so neither the hero nor the A button reaches a game that is not
+ /// on screen.
+ func reconcile(games: [LibraryGame], selectedID: UUID?, focused: String?) -> (selectedID: UUID?, focused: String?) {
+ let shown = games.filter(includes)
+ let selection = shown.contains { $0.id == selectedID } ? selectedID : shown.first?.id
+ guard let focused, focused.hasPrefix("card.") else { return (selection, focused) }
+ return (selection, shown.contains { "card." + $0.id.uuidString == focused } ? focused : nil)
+ }
}
struct ContentView: View {
@@ -96,33 +111,26 @@ struct ContentView: View {
if injectedDriver { consoleDriver.setPadMerge(on) }
}
- /// The games nxnative has profiles for, loaded from the checkout's dm/games: the "All" filter shows
- /// these beside the player's own, covers scraped the same way.
- @State private var supportedGames: [LibraryGame] = []
- /// A profile-only card the player focused: it has no build, so the hero shows a hint instead of Play.
- @State private var selectedUnowned: String?
- @State private var libraryFilter: LibraryFilter = LibraryFilter.load() {
- didSet { if libraryFilter != oldValue { libraryFilter.save(); selectedUnowned = nil; library.selectedID = nil } }
- }
+ @State private var libraryFilter: LibraryFilter = LibraryFilter.load()
- private func loadSupportedGames() {
- supportedGames = SupportedGames.load(repo: m.repoPath)
+ private func setLibraryFilter(_ filter: LibraryFilter) {
+ guard filter != libraryFilter else { return }
+ withAnimation(.easeInOut(duration: 0.2)) { libraryFilter = filter }
+ filter.save()
+ let after = filter.reconcile(games: library.games, selectedID: library.selectedID, focused: padFocus.focused)
+ if after.selectedID != library.selectedID { library.selectedID = after.selectedID }
+ if after.focused != padFocus.focused { padFocus.focused = after.focused }
}
- private func isUnowned(_ game: LibraryGame) -> Bool {
- !library.games.contains { $0.titleID == game.titleID }
+ private var filteredGames: [LibraryGame] {
+ library.games.filter { (search.isEmpty || $0.name.localizedCaseInsensitiveContains(search)) && libraryFilter.includes($0) }
}
- private var filteredGames: [LibraryGame] {
- let owned = library.games.filter { search.isEmpty || $0.name.localizedCaseInsensitiveContains(search) }
- let unowned = supportedGames
- .filter { s in !library.games.contains { $0.titleID == s.titleID } }
- .filter { search.isEmpty || $0.name.localizedCaseInsensitiveContains(search) }
- switch libraryFilter {
- case .all: return owned + unowned
- case .owned: return owned
- case .built: return owned.filter { $0.isReady || $0.hasIOSBuild }
- }
+ /// The hero's game: the selection, unless the filter hides it, then the first game the filter shows.
+ private var heroGame: LibraryGame? {
+ guard libraryFilter != .owned else { return library.selected }
+ if let selected = library.selected, libraryFilter.includes(selected) { return selected }
+ return library.games.first(where: libraryFilter.includes)
}
var body: some View {
@@ -202,7 +210,6 @@ struct ContentView: View {
refreshArtwork()
readSignatures()
if performStartupChecks { library.discover(); fetchArtwork(); m.refreshDevices(); checkTools() }
- loadSupportedGames()
if performStartupChecks {
m.checkDeps()
if m.repoOK && m.repoIsGit { m.checkRepoUpdates(silent: true) } else { m.adoptAtLaunch() }
@@ -221,7 +228,7 @@ struct ContentView: View {
readSignatures()
if performStartupChecks { fetchArtwork() }
}
- .onChange(of: m.repoPath) { _ in refreshArtwork(); loadSupportedGames(); if performStartupChecks { checkTools() } }
+ .onChange(of: m.repoPath) { _ in refreshArtwork(); if performStartupChecks { checkTools() } }
// A clone, pull or update check has finished (the automatic pull at launch among them): the checkout may have moved
.onReceive(m.$repoBusy.removeDuplicates().dropFirst()) { busy in if !busy && performStartupChecks { checkTools() } }
.onChange(of: library.selectedID) { _ in resignNote = nil } // the last re-sign's note belongs to its game
@@ -430,14 +437,13 @@ struct ContentView: View {
private var libraryPage: some View {
GeometryReader { geometry in
- if library.games.isEmpty && supportedGames.isEmpty {
+ if library.games.isEmpty {
emptyLibrary
} else {
ScrollView {
VStack(alignment: .leading, spacing: 0) {
- if let entry = currentHero {
- hero(entry.game, unowned: entry.unowned,
- width: geometry.size.width, height: max(240, geometry.size.height - collectionHeight))
+ if let game = heroGame {
+ hero(game, width: geometry.size.width, height: max(240, geometry.size.height - collectionHeight))
}
// The hero takes what the collection leaves: the row's height grows with the window's width (its cards
// do, up to 300 pt), so a fixed share left a fullscreen window's cards cut off at the bottom
@@ -475,7 +481,7 @@ struct ContentView: View {
.padding(48).frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .leading)
}
- private func hero(_ game: LibraryGame, unowned: Bool = false, width: CGFloat, height: CGFloat) -> some View {
+ private func hero(_ game: LibraryGame, width: CGFloat, height: CGFloat) -> some View {
ZStack(alignment: .bottomLeading) {
if let image = artwork[game.id] {
Image(nsImage: image).resizable().scaledToFill()
@@ -510,11 +516,6 @@ struct ContentView: View {
Text(game.name).font(.manrope(min(68, width * 0.052), .heavy))
.tracking(-1.6).lineLimit(2).shadow(color: .black.opacity(0.25), radius: 12)
HStack(spacing: 18) {
- if unowned {
- Text(m.t("library.notOwnedHint"))
- .font(.manrope(14)).foregroundStyle(.secondary)
- .fixedSize(horizontal: false, vertical: true).frame(maxWidth: 460, alignment: .leading)
- } else {
Button { primaryAction(game) } label: {
LauncherHeroActionLabel(
title: game.primary == .play ? m.t("library.play")
@@ -539,7 +540,6 @@ struct ContentView: View {
.buttonStyle(.plain).accessibilityLabel(m.t("library.manage"))
.anchorPreference(key: ManageAnchorKey.self, value: .bounds) { $0 }
.padTarget("hero.manage", scope: "main", radius: 12) { manageOpenFor = game.id }
- }
}
// A free Apple ID's provisioning profile lasts 7 days. Say when this app's runs out, and offer the
// re-sign at any time: renewing early (before a trip, say) is as valid as renewing just in time.
@@ -573,56 +573,33 @@ struct ContentView: View {
.frame(width: width, height: height).clipped()
}
- /// The hero's game: the player's selection, else the focused profile-only card. The unowned flag rides
- /// along (a transient var on the copy, never persisted).
- private var currentHero: (game: LibraryGame, unowned: Bool)? {
- if let id = selectedUnowned, let game = supportedGames.first(where: { $0.titleID == id }) {
- return (game, true)
- }
- if library.selectedID == nil, let first = filteredGames.first { return (first, isUnowned(first)) }
- if let game = filteredGames.first(where: { $0.id == library.selectedID }) { return (game, isUnowned(game)) }
- return nil
- }
-
private func collection(width: CGFloat) -> some View {
let cardWidth = min(300, max(190, (width - 124) / 5))
let step = cardWidth + 14
+ let games = filteredGames
+ let heroID = heroGame?.id
return VStack(alignment: .leading, spacing: 18) {
- HStack {
+ HStack(spacing: 16) {
Text(m.t("library.collection")).font(.manrope(28, .bold)).tracking(-0.6)
Spacer()
- Text(String(format: m.t("library.gameCount"), filteredGames.count))
+ LauncherSegmented(options: LibraryFilter.allCases.map { ($0.rawValue, m.t($0.labelKey)) },
+ selection: libraryFilter.rawValue) { setLibraryFilter(LibraryFilter(rawValue: $0) ?? .owned) }
+ .frame(width: LauncherControl.width)
+ .padTarget("library.filter", scope: "main", radius: 17,
+ activate: { setLibraryFilter(libraryFilter == .owned ? .built : .owned) },
+ adjust: { setLibraryFilter($0 > 0 ? .built : .owned) })
+ Text(String(format: m.t("library.gameCount"), libraryFilter == .owned ? library.games.count : library.games.filter(libraryFilter.includes).count))
.font(.manrope(12)).foregroundStyle(.secondary)
}
- HStack(spacing: 8) {
- ForEach(LibraryFilter.allCases) { f in
- Button {
- withAnimation(.easeInOut(duration: 0.2)) { libraryFilter = f }
- } label: {
- Text(m.t(f.labelKey)).font(.manrope(13, libraryFilter == f ? .bold : .medium))
- .padding(.horizontal, 14).padding(.vertical, 7)
- .background(libraryFilter == f ? Color.white.opacity(0.12) : Color.white.opacity(0.05),
- in: Capsule())
- .overlay(Capsule().strokeBorder(libraryFilter == f ? LauncherPalette.cream.opacity(0.55) : Color.white.opacity(0.08)))
- .contentShape(Capsule())
- }
- .buttonStyle(.plain)
- .accessibilityAddTraits(libraryFilter == f ? .isSelected : [])
- }
- Spacer()
- }
- if filteredGames.isEmpty {
+ if games.isEmpty {
Text(m.t("library.noResults")).foregroundStyle(.secondary).padding(.vertical, 28)
} else {
ScrollViewReader { proxy in
ScrollView(.horizontal, showsIndicators: false) {
HStack(alignment: .top, spacing: 14) {
- ForEach(filteredGames) { game in
+ ForEach(games) { game in
let _ = LauncherWork.count(.card)
- let unowned = isUnowned(game)
- Button {
- if unowned { selectedUnowned = game.titleID } else { selectedUnowned = nil; library.selectedID = game.id }
- } label: {
+ Button { library.selectedID = game.id } label: {
VStack(alignment: .leading, spacing: 8) {
ZStack {
if let image = artwork[game.id] {
@@ -634,29 +611,18 @@ struct ContentView: View {
}
.frame(width: cardWidth, height: cardWidth / 1.8).clipped()
.clipShape(RoundedRectangle(cornerRadius: 5))
- .overlay(alignment: .topTrailing) {
- if unowned {
- Text(m.t("library.notOwnedShort"))
- .font(.manrope(10, .bold)).tracking(0.4)
- .foregroundStyle(.white).padding(.horizontal, 7).padding(.vertical, 3)
- .background(LauncherPalette.unbuilt.opacity(0.85), in: Capsule())
- .padding(6)
- }
- }
.overlay(RoundedRectangle(cornerRadius: 5).strokeBorder(
- (unowned ? selectedUnowned == game.titleID : game.id == library.selectedID) ? LauncherPalette.cream : .clear, lineWidth: 2))
+ game.id == heroID ? LauncherPalette.cream : .clear, lineWidth: 2))
Text(game.name).font(.manrope(16, .semibold)).lineLimit(1)
status(game)
- Capsule().fill((unowned ? selectedUnowned == game.titleID : game.id == library.selectedID) ? LauncherPalette.cream : .clear)
+ Capsule().fill(game.id == heroID ? LauncherPalette.cream : .clear)
.frame(height: 3).padding(.top, 4)
}
.frame(width: cardWidth, alignment: .leading).contentShape(Rectangle())
}
.buttonStyle(.plain)
- .accessibilityAddTraits((unowned ? selectedUnowned == game.titleID : game.id == library.selectedID) ? .isSelected : [])
- .padTarget("card." + game.id.uuidString, scope: "main", radius: 7) {
- if !launching && !unowned { primaryAction(game) } // a profile-only card has nothing to run
- }
+ .accessibilityAddTraits(game.id == heroID ? .isSelected : [])
+ .padTarget("card." + game.id.uuidString, scope: "main", radius: 7) { if !launching { primaryAction(game) } }
}
}
// Room for the controller's focus ring, which sits 4 pt outside a card: the row clips at its edges, so it
diff --git a/frontend/Sources/NSPortBuilder/Localization.swift b/frontend/Sources/NSPortBuilder/Localization.swift
index 09aa1d60..6430cf2a 100644
--- a/frontend/Sources/NSPortBuilder/Localization.swift
+++ b/frontend/Sources/NSPortBuilder/Localization.swift
@@ -470,12 +470,8 @@ enum L10n {
"library.profileUpdated": ("游戏档案有更新", "This game's profile updated"),
"library.profileUpdatedShort": ("档案有更新", "Profile updated"),
"library.profileUpdatedHelp": ("这个游戏的档案(dm/games)自上次构建后有了更改:修复、着色器表或兼容性调整。重新构建即可用上。", "This game's own profile (dm/games) changed since it was built: fixes, shader tables or compatibility work. Rebuild to get them."),
- "filter.all": ("全部", "All"),
"filter.owned": ("已拥有", "Owned"),
"filter.built": ("已构建", "Built"),
- "library.notOwned": ("未拥有", "Not owned"),
- "library.notOwnedShort": ("未拥有", "Not owned"),
- "library.notOwnedHint": ("这个游戏在 nxnative 的支持列表里:把它的文件加入游戏文件夹后即可构建。", "This game is in nxnative\u{2019}s supported list: add its files to your games folder and it builds."),
"library.rebuild": ("用当前工具重新构建…", "Rebuild with current tools…"),
"library.rebuildShort": ("重新构建", "Rebuild"),
"library.buildForMac": ("\u{4e3a} Mac \u{6784}\u{5efa}", "Build for Mac"),
@@ -1378,12 +1374,8 @@ enum L10n {
"library.play": "Spela",
"library.olderTools": "Byggt med äldre verktyg",
"library.olderToolsShort": "Äldre verktyg",
- "filter.all": "Alla",
"filter.owned": "Im ägo",
"filter.built": "Byggda",
- "library.notOwned": "Ej ägd",
- "library.notOwnedShort": "Ej ägd",
- "library.notOwnedHint": "Spelet finns i nxnatives lista: lägg till dess filer i din spelmapp så byggs det.",
"library.olderToolsHelp": "Byggverktygen har ändrats på ett sätt som påverkar spelet sedan det byggdes. Bygg om det för att få ändringarna.",
"library.rebuild": "Bygg om med aktuella verktyg …",
"library.rebuildShort": "Bygg om",
@@ -2241,12 +2233,8 @@ enum L10n {
"library.olderTools": "Mit älteren Werkzeugen gebaut",
"library.olderToolsShort": "Ältere Werkzeuge",
"library.olderToolsHelp": "Die Build-Werkzeuge haben sich seit dem Build so geändert, dass es dieses Spiel betrifft. Baue es neu, um die Änderungen zu bekommen.",
- "filter.all": "Alle",
"filter.owned": "Im Besitz",
"filter.built": "Gebaut",
- "library.notOwned": "Nicht im Besitz",
- "library.notOwnedShort": "Nicht im Besitz",
- "library.notOwnedHint": "Dieses Spiel ist in nxnatives Liste: füge seine Dateien in deinen Spieleordner ein, dann lässt es sich bauen.",
"library.pin": "Diesen Build behalten",
"library.pinHelp": "Dieser Build ist als spielbar bekannt. Engine-Updates markieren ihn nicht mehr als älter. Änderungen am Spielprofil werden weiterhin gezeigt.",
"library.unpin": "Build nicht mehr behalten",
diff --git a/frontend/Sources/NSPortBuilder/PadFocus.swift b/frontend/Sources/NSPortBuilder/PadFocus.swift
index 0498b9d5..7545d631 100644
--- a/frontend/Sources/NSPortBuilder/PadFocus.swift
+++ b/frontend/Sources/NSPortBuilder/PadFocus.swift
@@ -31,10 +31,14 @@ final class PadFocus: ObservableObject {
/// Left / right: the target's own value when it holds one, else a move.
func horizontal(_ step: Int) {
- if let id = focused, let adjust = handlers[id]?.adjust { adjust(step) } else { move(dx: CGFloat(step), dy: 0) }
+ if let id = focused, onScreen(id), let adjust = handlers[id]?.adjust { adjust(step) } else { move(dx: CGFloat(step), dy: 0) }
}
- func activate() { if let id = focused { handlers[id]?.activate?() } }
+ func activate() { if let id = focused, onScreen(id) { handlers[id]?.activate?() } }
+
+ /// Handlers outlive their views, so a target that is no longer drawn (a card the library filter or the search hides) is
+ /// recognised by its missing frame: A and left / right do nothing on it.
+ private func onScreen(_ id: String) -> Bool { frames.values.contains { $0.contains { $0.id == id } } }
/// The nearest target in the direction, scored by distance along it plus twice the distance across it. Left and right
/// stay in the row (the target must overlap it vertically), so the last card does not jump to a button across the
diff --git a/frontend/Sources/NSPortBuilder/SupportedGames.swift b/frontend/Sources/NSPortBuilder/SupportedGames.swift
deleted file mode 100644
index b9225713..00000000
--- a/frontend/Sources/NSPortBuilder/SupportedGames.swift
+++ /dev/null
@@ -1,27 +0,0 @@
-import Foundation
-
-/// Every game nxnative has a profile for: `dm/games/<title ID>/game.tsv` of the checkout. The library's
-/// "All" filter shows these beside the games the player owns, covers scraped the same way, so the
-/// collection doubles as the list of what the engine supports today.
-enum SupportedGames {
- /// Lightweight library entries (title ID and name only, no paths). A game the player owns is matched
- /// by title ID and shown from their own entry instead.
- static func load(repo: String) -> [LibraryGame] {
- guard !repo.isEmpty else { return [] }
- let fm = FileManager.default
- let gamesDir = repo + "/dm/games"
- guard let entries = try? fm.contentsOfDirectory(atPath: gamesDir) else { return [] }
- var games: [LibraryGame] = []
- for entry in entries.sorted() {
- guard entry.count == 16, entry.allSatisfy(\.isHexDigit), entry != "0000000000000000" else { continue }
- let tsv = gamesDir + "/" + entry + "/game.tsv"
- guard let text = try? String(contentsOfFile: tsv, encoding: .utf8) else { continue }
- let name = text.split(separator: "\n").compactMap { line -> String? in
- let parts = line.split(separator: "\t", maxSplits: 1)
- return parts.first == "name" && parts.count > 1 ? String(parts[1]) : nil
- }.first ?? entry
- games.append(LibraryGame(titleID: entry, name: name))
- }
- return games
- }
-}
diff --git a/frontend/Tests/NSPortBuilderTests/LauncherControlWidthTests.swift b/frontend/Tests/NSPortBuilderTests/LauncherControlWidthTests.swift
index 0e63a306..91720ffc 100644
--- a/frontend/Tests/NSPortBuilderTests/LauncherControlWidthTests.swift
+++ b/frontend/Tests/NSPortBuilderTests/LauncherControlWidthTests.swift
@@ -32,6 +32,19 @@ final class LauncherControlWidthTests: XCTestCase {
}
}
+ /// The library's Owned/Built switch is one LauncherControl wide, so each label fits its half in bold, without shrinking.
+ func testLibraryFilterLabelsFitTheirSegment() throws {
+ let room = (LauncherControl.width - 2 * 3 - 2) / 2 - 2 * 12
+ for filter in LibraryFilter.allCases {
+ for lang in Lang.allCases {
+ let text = L10n.string(filter.labelKey, lang)
+ let font = try XCTUnwrap(Typography.manropeFont(size: 12.5, weight: .bold))
+ let line = CTLineCreateWithAttributedString(NSAttributedString(string: text, attributes: [.font: font]))
+ XCTAssertLessThanOrEqual(CTLineGetTypographicBounds(line, nil, nil, nil), room, "\(lang) \(filter.labelKey): \(text)")
+ }
+ }
+ }
+
// MARK: Real pages
private final class Samples { var all: [LauncherControlSample] = [] }
diff --git a/frontend/Tests/NSPortBuilderTests/LibraryTests.swift b/frontend/Tests/NSPortBuilderTests/LibraryTests.swift
index eb750720..0bd5c099 100644
--- a/frontend/Tests/NSPortBuilderTests/LibraryTests.swift
+++ b/frontend/Tests/NSPortBuilderTests/LibraryTests.swift
@@ -49,6 +49,42 @@ final class LibraryTests: XCTestCase {
XCTAssertEqual(GameLibrary(file: file).games.first?.pinned, false)
}
+ /// The library opens on the player's own games: Owned is the default, also for the "all" an earlier build may have stored.
+ func testLibraryFilterDefaultsToOwned() throws {
+ let defaults = try XCTUnwrap(UserDefaults(suiteName: "nxnative-tests-filter-" + temporary.lastPathComponent))
+ XCTAssertEqual(LibraryFilter.load(defaults), .owned)
+ defaults.set("all", forKey: "libraryFilter")
+ XCTAssertEqual(LibraryFilter.load(defaults), .owned)
+ LibraryFilter.built.save(defaults)
+ XCTAssertEqual(LibraryFilter.load(defaults), .built)
+ defaults.removePersistentDomain(forName: "nxnative-tests-filter-" + temporary.lastPathComponent)
+ }
+
+ /// Built hides the games without a build. The selection moves to a game it shows, and a controller's focus on a hidden card
+ /// is dropped, so A cannot start a game that is not on screen.
+ func testBuiltFilterKeepsSelectionAndFocusOnShownGames() throws {
+ let built = LibraryGame(titleID: titleID, name: "Hades", appPath: try makeApp(titleID).path)
+ let unbuilt = LibraryGame(titleID: "0100000000010000", name: "Celeste")
+ let games = [unbuilt, built]
+ XCTAssertEqual(games.filter(LibraryFilter.owned.includes).map(\.id), [unbuilt.id, built.id])
+ XCTAssertEqual(games.filter(LibraryFilter.built.includes).map(\.id), [built.id])
+
+ let hidden = LibraryFilter.built.reconcile(games: games, selectedID: unbuilt.id, focused: "card." + unbuilt.id.uuidString)
+ XCTAssertEqual(hidden.selectedID, built.id)
+ XCTAssertNil(hidden.focused)
+
+ let shown = LibraryFilter.built.reconcile(games: games, selectedID: built.id, focused: "card." + built.id.uuidString)
+ XCTAssertEqual(shown.selectedID, built.id)
+ XCTAssertEqual(shown.focused, "card." + built.id.uuidString)
+
+ let elsewhere = LibraryFilter.built.reconcile(games: games, selectedID: unbuilt.id, focused: "top.build")
+ XCTAssertEqual(elsewhere.focused, "top.build", "a focus outside the row stays")
+
+ let none = LibraryFilter.built.reconcile(games: [unbuilt], selectedID: unbuilt.id, focused: nil)
+ XCTAssertNil(none.selectedID)
+ XCTAssertEqual(LibraryFilter.owned.reconcile(games: games, selectedID: nil, focused: nil).selectedID, unbuilt.id)
+ }
+
func testReadyRequiresMatchingGameAndCompleteExecutables() throws {
let app = try makeApp(titleID)
var game = LibraryGame(titleID: titleID, name: "Hades", appPath: app.path)
diff --git a/frontend/Tests/NSPortBuilderTests/PadFocusTests.swift b/frontend/Tests/NSPortBuilderTests/PadFocusTests.swift
index 8bb9d517..89c42081 100644
--- a/frontend/Tests/NSPortBuilderTests/PadFocusTests.swift
+++ b/frontend/Tests/NSPortBuilderTests/PadFocusTests.swift
@@ -48,4 +48,19 @@ final class PadFocusTests: XCTestCase {
f.scope = "launch"
XCTAssertNil(f.focused, "another scope starts without a focus")
}
+
+ /// A card the library filter hides keeps its handler but loses its frame: A does not start it, and moves skip it.
+ func testAHiddenTargetIsNeitherActivatedNorReached() {
+ let f = grid()
+ var activated = 0
+ f.register("card.2", .init(activate: { activated += 1 }, adjust: nil))
+ f.show(default: "card.2")
+ f.setFrames([.init(id: "card.1", frame: CGRect(x: 0, y: 300, width: 200, height: 120)),
+ .init(id: "card.3", frame: CGRect(x: 440, y: 300, width: 200, height: 120))], scope: "main")
+ f.activate()
+ XCTAssertEqual(activated, 0)
+ f.focused = "card.1"
+ f.move(dx: 1, dy: 0)
+ XCTAssertEqual(f.focused, "card.3")
+ }
}
diff --git a/frontend/Tests/NSPortBuilderTests/SupportedGamesTests.swift b/frontend/Tests/NSPortBuilderTests/SupportedGamesTests.swift
deleted file mode 100644
index 48476c54..00000000
--- a/frontend/Tests/NSPortBuilderTests/SupportedGamesTests.swift
+++ /dev/null
@@ -1,42 +0,0 @@
-import XCTest
-@testable import NSPortBuilder
-
-/// The "All" filter's data (SupportedGames.swift): every profile in the checkout's dm/games becomes a
-/// lightweight library entry, owned games matched later by title ID.
-final class SupportedGamesTests: XCTestCase {
- private var repo: URL!
-
- override func setUpWithError() throws {
- repo = FileManager.default.temporaryDirectory.appendingPathComponent("supported-" + UUID().uuidString)
- for (id, name) in [("0100535012974000", "Hades"), ("0100152000022000", "Mario Kart 8 Deluxe")] {
- let dir = repo.appendingPathComponent("dm/games/\(id)")
- try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
- try "program_id\t\(id)\nname\t\(name)\n".write(to: dir.appendingPathComponent("game.tsv"), atomically: true, encoding: .utf8)
- }
- // Not profiles: a stray folder with a non-ID name, a folder without game.tsv, tests and docs
- try FileManager.default.createDirectory(at: repo.appendingPathComponent("dm/games/notes"), withIntermediateDirectories: true)
- try FileManager.default.createDirectory(at: repo.appendingPathComponent("dm/games/0100F2C0115B6000"), withIntermediateDirectories: true)
- try "prose".write(to: repo.appendingPathComponent("dm/games/notes/README.md"), atomically: true, encoding: .utf8)
- }
-
- override func tearDownWithError() throws { try? FileManager.default.removeItem(at: repo) }
-
- func testEveryProfileFolderBecomesAnEntryNamedFromItsTable() {
- let games = SupportedGames.load(repo: repo.path)
- XCTAssertEqual(games.map(\.titleID), ["0100152000022000", "0100535012974000"])
- XCTAssertEqual(games.map(\.name), ["Mario Kart 8 Deluxe", "Hades"])
- }
-
- func testAnEntryHasNoPathsAndIsNotReady() {
- for game in SupportedGames.load(repo: repo.path) {
- XCTAssertEqual(game.appPath, "")
- XCTAssertFalse(game.isReady)
- XCTAssertEqual(game.inputs, [:])
- }
- }
-
- func testAnEmptyOrMissingRepoGivesNothing() {
- XCTAssertTrue(SupportedGames.load(repo: "").isEmpty)
- XCTAssertTrue(SupportedGames.load(repo: repo.appendingPathComponent("missing").path).isEmpty)
- }
-}