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
Launch options are saved choices in the game app's own preferences, and the launcher reads launcher.json schema 1
v0lumehi1d1fa5348924
diff --git a/frontend/Sources/NSPortBuilder/LaunchOptionsView.swift b/frontend/Sources/NSPortBuilder/LaunchOptionsView.swiftindex 65efb68d..0b8d37de 100644--- a/frontend/Sources/NSPortBuilder/LaunchOptionsView.swift+++ b/frontend/Sources/NSPortBuilder/LaunchOptionsView.swift@@ -3,13 +3,15 @@ import SwiftUI/// A game's launch options: the settings its Mac app was packed with (dm/launcher.json), drawn as the/// iPhone launcher draws them, grouped by section. The basic settings come first, then the game's mods, and the rest-/// under Advanced settings. Play passes them to the app as its environment.+/// under Advanced settings. A row of the list is a saved choice in the app's own preferences domain (SavedChoices.swift), which the+/// app reads at every start; Play passes only the launch overrides (what the list has no row for, the mods) as its environment.struct LaunchOptionsView: View {@ObservedObject var m: BuildModel@ObservedObject var library: GameLibrarylet gameID: UUID@Environment(\.dismiss) private var dismiss@State private var advancedOpen = false+ @State private var choicesRevision = 0 // bumped by a change: the values are read from the store again@State private var modsRevision = 0 // bumped by Refresh: the folder is read again@EnvironmentObject private var focus: PadFocus@@ -17,6 +19,12 @@ struct LaunchOptionsView: View {private var settings: [LaunchSetting]? {game.flatMap { LaunchSetting.forMac(app: $0.appPath, titleID: $0.titleID, repo: m.repoPath, labels: m.t) }}+ private var store: SavedChoices? { game.map { SavedChoices(app: $0.appPath, titleID: $0.titleID) } }+ /// A saved choice for a row of the list, else the tested default; what only this launcher has comes from the library.+ private func value(_ s: LaunchSetting, _ game: LibraryGame) -> String {+ _ = choicesRevision+ return s.storeBacked ? (store?.current(s) ?? s.def) : game.launchValue(s)+ }private var modsFolder: URL? { game.map { GameMod.folder(for: $0, library: library.folder) } }private var mods: [GameMod] {_ = modsRevision@@ -25,6 +33,7 @@ struct LaunchOptionsView: View {}var body: some View {+ let _ = choicesRevisionVStack(alignment: .leading, spacing: 0) {HStack(alignment: .firstTextBaseline) {VStack(alignment: .leading, spacing: 4) {@@ -72,10 +81,10 @@ struct LaunchOptionsView: View {HStack(spacing: 14) {Text(m.t("launch.applied")).font(.manrope(12)).foregroundStyle(.secondary).lineLimit(2)Spacer(minLength: 8)- if let game, !game.launchOptions.isEmpty {- Button(m.t("launch.reset")) { library.resetLaunchOptions(for: gameID) }+ if let game, let settings, !game.launchOptions.isEmpty || (store?.hasChoices(settings) ?? false) {+ Button(m.t("launch.reset")) { reset(settings) }.buttonStyle(LauncherSecondaryButtonStyle())- .padTarget("opt.reset", scope: "launch") { library.resetLaunchOptions(for: gameID) }+ .padTarget("opt.reset", scope: "launch") { reset(settings) }}Button { dismiss() } label: {Text(m.t("launch.done")).font(.manrope(13.5, .bold)).foregroundStyle(.black)@@ -88,6 +97,7 @@ struct LaunchOptionsView: View {.padding(.horizontal, 30).padding(.vertical, 16)}.padScope("launch", focus)+ .onAppear { library.migrateLaunchOptions() }.frame(width: 600, height: 700).background(LauncherPalette.background).font(.manrope(13))@@ -98,10 +108,12 @@ struct LaunchOptionsView: View {// ---- groups of settings ----@ViewBuilder private func groups(_ rows: [LaunchSetting], _ game: LibraryGame, all: [LaunchSetting]) -> some View {- ForEach(sections(rows), id: \.self) { section in- let inSection = rows.filter { $0.sectionTitle == section }+ // A sub-setting (needs) is drawn only while its parent has the value; a section left empty is not drawn+ let shown = rows.filter { $0.isShown(in: all) { value($0, game) } }+ ForEach(LaunchSetting.orderedSections(shown), id: \.self) { section in+ let inSection = shown.filter { $0.sectionTitle == section }VStack(alignment: .leading, spacing: 10) {- heading(m.t("launch.section." + section))+ heading(sectionName(section))card {ForEach(inSection) { s inrow(s, game, all: all)@@ -124,19 +136,31 @@ struct LaunchOptionsView: View {private var divider: some View { Divider().opacity(0.25).padding(.leading, 18) }- private func sections(_ settings: [LaunchSetting]) -> [String] {- settings.reduce(into: []) { if !$0.contains($1.sectionTitle) { $0.append($1.sectionTitle) } }+ /// The translated heading of a section this launcher knows; a section it does not know is drawn under its own name.+ private func sectionName(_ section: String) -> String {+ let key = "launch.section." + section+ let name = m.t(key)+ return name == key ? section : name+ }++ private func set(_ s: LaunchSetting, _ value: String) {+ if s.storeBacked { store?.set(s, value) } else { library.setLaunchOption(s, value, for: gameID) }+ choicesRevision += 1}- private func set(_ s: LaunchSetting, _ value: String) { library.setLaunchOption(s, value, for: gameID) }+ private func reset(_ settings: [LaunchSetting]) {+ store?.reset(settings)+ library.resetLaunchOptions(for: gameID)+ choicesRevision += 1+ }/// Docked unless the console mode chosen is handheld (DM_OPMODE 0), for the render scale's pixels.private func docked(_ game: LibraryGame, _ all: [LaunchSetting]) -> Bool {- all.first { $0.env == "DM_OPMODE" }.map { game.launchValue($0) != "0" } ?? true+ all.first { $0.env == "DM_OPMODE" }.map { value($0, game) != "0" } ?? true}@ViewBuilder private func row(_ s: LaunchSetting, _ game: LibraryGame, all: [LaunchSetting]) -> some View {- let value = game.launchValue(s)+ let value = self.value(s, game)let isDocked = docked(game, all)let pixels = s.kind == "range" ? s.pixels(scale: Double(value) ?? 1, docked: isDocked) : nilHStack(alignment: .center, spacing: 16) {diff --git a/frontend/Sources/NSPortBuilder/LauncherView.swift b/frontend/Sources/NSPortBuilder/LauncherView.swiftindex 20286b83..14505af7 100644--- a/frontend/Sources/NSPortBuilder/LauncherView.swift+++ b/frontend/Sources/NSPortBuilder/LauncherView.swift@@ -86,6 +86,7 @@ struct ContentView: View {.frame(minWidth: 900, idealWidth: 1280, minHeight: 680, idealHeight: 900).onAppear {gamepad.perform = padAction+ if performStartupChecks { library.migrateLaunchOptions() }refreshArtwork()if performStartupChecks { library.discover(); fetchArtwork(); m.refreshDevices(); checkTools() }if performStartupChecks {@@ -638,11 +639,11 @@ struct ContentView: View {let configuration = NSWorkspace.OpenConfiguration()// The launch options; the app's launcher (dm/mac/launcher.c) keeps a variable that is already set.// The keyboard and controller layout (Settings → Controls) goes to every game; a build whose host does not read it plays with the default keys.- var environment = controls.environment- if let settings = LaunchSetting.forMac(app: game.appPath, titleID: game.titleID, repo: m.repoPath, labels: m.t) {- environment.merge(game.launchEnvironment(settings)) { _, own in own }- }- environment.merge(game.modEnvironment(GameMod.list(in: GameMod.folder(for: game, library: library.folder), titleID: game.titleID))) { _, mods in mods }+ // They stay launch overrides (the environment) for now: DM_KEYMAP and DM_PAD_MAP become saved choices only when seedds/nxnative#386 merges.+ library.migrateLaunchOptions()+ let settings = LaunchSetting.forMac(app: game.appPath, titleID: game.titleID, repo: m.repoPath, labels: m.t) ?? []+ let mods = GameMod.list(in: GameMod.folder(for: game, library: library.folder), titleID: game.titleID)+ let environment = game.startEnvironment(controls: controls.environment, settings: settings, mods: mods)if !environment.isEmpty { configuration.environment = environment }NSWorkspace.shared.openApplication(at: URL(fileURLWithPath: game.appPath), configuration: configuration) { _, error inDispatchQueue.main.async {diff --git a/frontend/Sources/NSPortBuilder/Library.swift b/frontend/Sources/NSPortBuilder/Library.swiftindex 099bfbc4..81868798 100644--- a/frontend/Sources/NSPortBuilder/Library.swift+++ b/frontend/Sources/NSPortBuilder/Library.swift@@ -67,8 +67,12 @@ struct LaunchSetting: Decodable, Identifiable {var level: String? = nil/// The 3D views' base size the setting scales, docked and handheld ([width, height]); the render scale's row shows pixels with it.var base: [String: [Int]]? = nil+ /// `<VAR>=<value>` (schema 1, optional): the row is a sub-setting, shown only while the row that sets <VAR> has that value.+ var needs: String? = nil/// The value that leaves the variable unset (DM_FULLSCREEN is on when it is set at all).var unsetValue: String? = nil+ /// A setting this launcher adds itself (launcher.json has no row for it) is not a saved choice: the store has no rule for it.+ var storeBacked: Bool { unsetValue == nil }var id: String { env }var sectionTitle: String { section ?? "Game" }/// The rows the sheet shows first, as seedds/nxnative#374 groups them; the rest are under Advanced settings.@@ -82,21 +86,21 @@ struct LaunchSetting: Decodable, Identifiable {func accepts(_ v: String) -> Bool { // a saved choice the build still offersswitch kind {case "choice": return options?.contains { $0.first == v } ?? false- case "range":- guard let n = Double(v), n.isFinite, let lo = min, let hi = max else { return false }+ case "range": // as dm/mac/launcher.c: no leading space, no hex, no NaN+ guard !v.isEmpty, !(v.first?.isWhitespace ?? true), !v.contains("x"), !v.contains("X"),+ let n = Double(v), n.isFinite, let lo = min, let hi = max else { return false }return n >= lo && n <= hicase "toggle": return v == onValue || v == offValuedefault: return true}}- enum CodingKeys: String, CodingKey { case env, kind, label, note, def = "default", section, options, min, max, step, on, off, level, base }+ enum CodingKeys: String, CodingKey { case env, kind, label, note, def = "default", section, options, min, max, step, on, off, level, base, needs }- private struct File: Decodable { let settings: [LaunchSetting] }- /// The settings a Mac app was packed with; nil for an app packed before they were.+ /// The settings a Mac app was packed with; nil for an app packed before they were (see LaunchList for the schema).static func read(app: String) -> [LaunchSetting]? {let url = URL(fileURLWithPath: app).appendingPathComponent("Contents/Resources/dm/launcher.json")guard let data = try? Data(contentsOf: url) else { return nil }- return (try? JSONDecoder().decode(File.self, from: data))?.settings+ return LaunchList.parse(data)?.settings}/// The app's settings as the Mac shows them: the Mac-only Display mode added when the list has none (the host reads@@ -168,15 +172,17 @@ struct GameMod: Identifiable, Equatable {}extension LibraryGame {- /// The value each setting takes: the player's choice while the build still offers it, else the game's default.+ /// The value of a setting this launcher keeps itself (not a saved choice): the player's choice while the build still offers it,+ /// else the game's default. Saved choices are read through SavedChoices.func launchValue(_ s: LaunchSetting) -> String {launchOptions[s.env].flatMap { s.accepts($0) ? $0 : nil } ?? s.def}- /// Every setting goes into the app's environment, as the iPhone launcher sets them before the game starts; one at- /// its unset value (Display mode: Window) stays out.+ /// The launch overrides of the settings only this launcher has (Display mode); one at its unset value (Window) stays out.+ /// The rows of launcher.json are saved choices (SavedChoices) and are not passed: the app reads them itself, and a value here+ /// would override a choice made elsewhere.func launchEnvironment(_ settings: [LaunchSetting]) -> [String: String] {- Dictionary(uniqueKeysWithValues: settings.compactMap { s in+ Dictionary(uniqueKeysWithValues: settings.filter { !$0.storeBacked }.compactMap { s inlet v = launchValue(s)return s.unsetValue == v ? nil : (s.env, v)})@@ -423,6 +429,19 @@ final class GameLibrary: ObservableObject {upsert(game)}+ /// The one-time move of the launch options an earlier version kept in the library file into each app's preferences domain+ /// (SavedChoices.migrate). The field stays decoded so an old library file loads; what is left in it is only what the store+ /// has no row for. Runs for every game that has options and an app with a settings list; a game without one waits.+ func migrateLaunchOptions() {+ var changed = false+ for i in games.indices where !games[i].launchOptions.isEmpty && !games[i].appPath.isEmpty {+ guard let settings = LaunchSetting.read(app: games[i].appPath) else { continue }+ let store = SavedChoices(app: games[i].appPath, titleID: games[i].titleID)+ for env in store.migrate(games[i].launchOptions, settings: settings) { games[i].launchOptions[env] = nil; changed = true }+ }+ if changed { save() }+ }+func resetLaunchOptions(for id: UUID) {guard var game = games.first(where: { $0.id == id }) else { return }game.launchOptions = [:]diff --git a/frontend/Sources/NSPortBuilder/Localization.swift b/frontend/Sources/NSPortBuilder/Localization.swiftindex 0764d70c..f699a892 100644--- a/frontend/Sources/NSPortBuilder/Localization.swift+++ b/frontend/Sources/NSPortBuilder/Localization.swift@@ -152,7 +152,7 @@ enum L10n {"launch.title": ("\u{542f}\u{52a8}\u{9009}\u{9879}", "Launch options"),"launch.reset": ("\u{6062}\u{590d}\u{6d4b}\u{8bd5}\u{9ed8}\u{8ba4}\u{503c}", "Reset to tested defaults"),"launch.done": ("\u{5b8c}\u{6210}", "Done"),- "launch.applied": ("\u{4e0b}\u{6b21}\u{4ece}\u{8fd9}\u{91cc}\u{5f00}\u{59cb}\u{6e38}\u{620f}\u{65f6}\u{751f}\u{6548}\u{3002}", "Applied the next time you press Play here."),+ "launch.applied": ("已保存到这个游戏应用中,每次启动都会生效。", "Saved in the game’s app: applies every time it starts."),"launch.none": ("\u{8fd9}\u{4e2a}\u{7248}\u{672c}\u{6ca1}\u{6709}\u{9644}\u{5e26}\u{542f}\u{52a8}\u{9009}\u{9879}\u{5217}\u{8868}\u{3002}", "This build carries no list of launch options."),"launch.section.Game": ("\u{6e38}\u{620f}", "Game"),"launch.section.Controls": ("\u{63a7}\u{5236}", "Controls"),diff --git a/frontend/Sources/NSPortBuilder/SavedChoices.swift b/frontend/Sources/NSPortBuilder/SavedChoices.swiftnew file mode 100644index 00000000..b3aca9b5--- /dev/null+++ b/frontend/Sources/NSPortBuilder/SavedChoices.swift@@ -0,0 +1,133 @@+import Foundation++/// A Mac game's launch options as seedds/nxnative keeps them (docs/frontends.md, "Saved choices"): one string per setting under+/// `launcher.<VAR>` in the built app's own preferences domain (its CFBundleIdentifier, `org.nxnative.<title ID lowercased>` unless the+/// app was packed with another). Only a choice that differs from the tested default is kept; dm/mac/launcher.c reads the keys at every+/// start, so a start from Finder or the Dock has them too, and the app's own settings window shares them.+///+/// What is stored and what is not:+/// - Every row of the app's launcher.json is a saved choice.+/// - A setting this launcher adds that launcher.json has no row for (Display mode, DM_FULLSCREEN, today) is not: launcher.c would+/// ignore a key it has no rule for. It stays in the library file and goes into the environment at Play, like the mods'+/// DM_ROMFS_OVERLAY and the Controls page's DM_KEYMAP / DM_PAD_MAP (those become saved choices when seedds/nxnative#386 merges).+/// - A launch override (anything in the environment at Play) is temporary and is never written here.+struct SavedChoices {+ let domain: String++ init(domain: String) { self.domain = domain }++ /// The app's preferences domain: CFBundleIdentifier from its Info.plist, else the default the packer uses.+ init(app: String, titleID: String) { self.init(domain: Self.domain(app: app, titleID: titleID)) }++ static func domain(app: String, titleID: String) -> String {+ let plist = URL(fileURLWithPath: app).appendingPathComponent("Contents/Info.plist")+ if let data = try? Data(contentsOf: plist),+ let info = try? PropertyListSerialization.propertyList(from: data, format: nil) as? [String: Any],+ let id = info["CFBundleIdentifier"] as? String, !id.isEmpty { return id }+ return "org.nxnative." + titleID.lowercased()+ }++ static func key(_ env: String) -> String { "launcher." + env }++ /// The stored value, whatever it is (nil when there is none); the migration only asks whether the key is taken.+ func raw(_ env: String) -> Any? { CFPreferencesCopyAppValue(Self.key(env) as CFString, domain as CFString) }++ /// The saved choice the way launcher.c reads it: a string this build still offers, else nil (the tested default applies).+ func value(_ s: LaunchSetting) -> String? {+ guard let v = raw(s.env) as? String, s.accepts(v) else { return nil }+ return v+ }++ /// What the setting is set to: the saved choice, else the tested default.+ func current(_ s: LaunchSetting) -> String { value(s) ?? s.def }++ /// A choice equal to the tested default removes the key, so the setting follows a later build's defaults.+ func set(_ s: LaunchSetting, _ v: String) {+ if s.isDefault(v) || !s.accepts(v) { CFPreferencesSetAppValue(Self.key(s.env) as CFString, nil, domain as CFString) }+ else { CFPreferencesSetAppValue(Self.key(s.env) as CFString, v as CFString, domain as CFString) }+ CFPreferencesAppSynchronize(domain as CFString)+ }++ /// "Reset to tested defaults": the keys of the settings the player can change.+ func reset(_ settings: [LaunchSetting]) {+ for s in settings where s.storeBacked { CFPreferencesSetAppValue(Self.key(s.env) as CFString, nil, domain as CFString) }+ CFPreferencesAppSynchronize(domain as CFString)+ }++ /// Whether any setting has a saved choice (the Reset button shows).+ func hasChoices(_ settings: [LaunchSetting]) -> Bool { settings.contains { $0.storeBacked && raw($0.env) != nil } }++ /// The one-time move of the options an earlier launcher kept in the library file: a valid choice that differs from the default+ /// goes to the domain where it has no value yet. Returns the variables that are the store's now (to drop from the library).+ @discardableResult+ func migrate(_ legacy: [String: String], settings: [LaunchSetting]) -> Set<String> {+ var moved = Set<String>()+ for s in settings where s.storeBacked {+ guard let v = legacy[s.env] else { continue }+ moved.insert(s.env)+ if raw(s.env) == nil, s.accepts(v), !s.isDefault(v) { set(s, v) }+ }+ return moved+ }+}++/// launcher.json as a reader sees it: the schema version and the rows it can draw.+struct LaunchList {+ var schema: Int+ var settings: [LaunchSetting]+ /// The newest schema this launcher knows. A newer major version is read as far as it can be (rows of a kind it does not know are+ /// left out) and noted in the log, never refused: schema 1 only grows by optional fields, and a later schema's rows that still+ /// have a known kind are drawn the same way.+ static let knownSchema = 1+ static let kinds: Set<String> = ["choice", "range", "toggle"]++ private struct Lossy: Decodable {+ let row: LaunchSetting?+ init(from decoder: Decoder) throws { row = try? LaunchSetting(from: decoder) }+ }+ private struct File: Decodable {+ let schema: Int?+ let settings: [Lossy]+ }++ static func parse(_ data: Data, log: (String) -> Void = { FileHandle.standardError.write(Data(($0 + "\n").utf8)) }) -> LaunchList? {+ guard let file = try? JSONDecoder().decode(File.self, from: data) else { return nil }+ let schema = file.schema ?? 1 // a list written before the field existed is 1+ if schema > knownSchema { log("launcher.json is schema \(schema); this launcher knows \(knownSchema): drawing the rows it understands") }+ let rows = file.settings.compactMap(\.row).filter { kinds.contains($0.kind) }+ return LaunchList(schema: schema, settings: rows)+ }+}++extension LaunchSetting {+ /// Sections this launcher has names for; any other is drawn after them, in the order of its first row.+ static let knownSections = ["Game", "Controls", "Performance"]++ /// The sections of `rows` in the order to draw: the known ones in the order of their first rows, then the unknown ones in list order.+ static func orderedSections(_ rows: [LaunchSetting]) -> [String] {+ let all = rows.reduce(into: [String]()) { if !$0.contains($1.sectionTitle) { $0.append($1.sectionTitle) } }+ return all.filter { knownSections.contains($0) } + all.filter { !knownSections.contains($0) }+ }++ /// `needs` (`<VAR>=<value>`): a sub-setting, drawn only while the row that sets <VAR> has that value. A row naming a variable the+ /// list does not have, or a needs it cannot parse, stays drawn.+ func isShown(in list: [LaunchSetting], value: (LaunchSetting) -> String) -> Bool {+ guard let needs, let eq = needs.firstIndex(of: "=") else { return true }+ let variable = String(needs[..<eq]), wanted = String(needs[needs.index(after: eq)...])+ guard let parent = list.first(where: { $0.env == variable }) else { return true }+ return value(parent) == wanted+ }+}++extension LibraryGame {+ /// The environment a Mac game is started with: launch overrides only, never written to the store. The rows of launcher.json are+ /// saved choices the app reads itself; what is here is the Controls page's layout, what only this launcher has (Display mode),+ /// the mods, and DM_LAUNCHER=0 (this launcher is the settings window, so the app's own is skipped; saved choices still apply).+ func startEnvironment(controls: [String: String], settings: [LaunchSetting], mods: [GameMod]) -> [String: String] {+ var environment = controls+ environment.merge(launchEnvironment(settings)) { _, own in own }+ environment.merge(modEnvironment(mods)) { _, mods in mods }+ environment["DM_LAUNCHER"] = "0"+ return environment+ }+}diff --git a/frontend/Tests/NSPortBuilderTests/LibraryTests.swift b/frontend/Tests/NSPortBuilderTests/LibraryTests.swiftindex aa256301..119055cd 100644--- a/frontend/Tests/NSPortBuilderTests/LibraryTests.swift+++ b/frontend/Tests/NSPortBuilderTests/LibraryTests.swift@@ -12,7 +12,13 @@ final class LibraryTests: XCTestCase {try FileManager.default.createDirectory(at: temporary, withIntermediateDirectories: true)}+ /// Every test app carries this bundle ID, so a saved choice goes to a preferences domain of this run and never to a real game's.+ private var bundleID: String { "org.nxnative.frontendtests." + temporary.lastPathComponent }+override func tearDownWithError() throws {+ let domain = bundleID as CFString+ for key in (CFPreferencesCopyKeyList(domain, kCFPreferencesCurrentUser, kCFPreferencesAnyHost) as? [String]) ?? [] { CFPreferencesSetAppValue(key as CFString, nil, domain) }+ CFPreferencesAppSynchronize(domain)try FileManager.default.removeItem(at: temporary)}@@ -23,7 +29,7 @@ final class LibraryTests: XCTestCase {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": name, "CFBundleExecutable": "nxnative"]+ let info: [String: Any] = ["DMTitleID": titleID, "CFBundleDisplayName": name, "CFBundleExecutable": "nxnative", "CFBundleIdentifier": bundleID]try PropertyListSerialization.data(fromPropertyList: info, format: .xml, options: 0).write(to: app.appendingPathComponent("Contents/Info.plist"))return app@@ -116,25 +122,30 @@ final class LibraryTests: XCTestCase {let file = temporary.appendingPathComponent("library.json")let library = GameLibrary(file: file)let id = try library.addApp(app)- XCTAssertEqual(library.games[0].launchEnvironment(settings), ["DM_FPS_TARGET": "30", "DM_RENDER_SCALE": "1.0", "DM_FPS_HOLD": "on"])- library.setLaunchOption(settings[0], "60", for: id)- library.setLaunchOption(settings[1], "1.00", for: id) // the default, as a slider writes it: not kept- library.setLaunchOption(settings[2], "off", for: id)- XCTAssertEqual(GameLibrary(file: file).games[0].launchOptions, ["DM_FPS_TARGET": "60", "DM_FPS_HOLD": "off"])- XCTAssertEqual(library.games[0].launchEnvironment(settings), ["DM_FPS_TARGET": "60", "DM_RENDER_SCALE": "1.0", "DM_FPS_HOLD": "off"])- library.setLaunchOption(settings[0], "30", for: id)- XCTAssertNil(library.games[0].launchOptions["DM_FPS_TARGET"])- library.resetLaunchOptions(for: id)- XCTAssertTrue(library.games[0].launchOptions.isEmpty)+ let store = SavedChoices(app: app.path, titleID: titleID)+ XCTAssertEqual(library.games[0].launchEnvironment(settings), [:], "the rows of launcher.json are saved choices, not launch overrides")+ store.set(settings[0], "60")+ store.set(settings[1], "1.00") // the default, as a slider writes it: not kept+ store.set(settings[2], "off")+ XCTAssertEqual(store.raw("DM_FPS_TARGET") as? String, "60")+ XCTAssertNil(store.raw("DM_RENDER_SCALE"))+ XCTAssertEqual(store.raw("DM_FPS_HOLD") as? String, "off")+ XCTAssertTrue(GameLibrary(file: file).games[0].launchOptions.isEmpty, "the library file no longer holds them")+ store.set(settings[0], "30")+ XCTAssertNil(store.raw("DM_FPS_TARGET"))+ store.reset(settings)+ XCTAssertFalse(store.hasChoices(settings))}func testLaunchOptionTheBuildNoLongerOffersFallsBackToItsDefault() throws {let app = try makeApp(titleID)try writeSettings(app)let settings = try XCTUnwrap(LaunchSetting.read(app: app.path))- var game = LibraryGame(titleID: titleID, name: "Hades", appPath: app.path)- game.launchOptions = ["DM_FPS_TARGET": "120", "DM_RENDER_SCALE": "2", "DM_FPS_HOLD": "maybe"]- XCTAssertEqual(game.launchEnvironment(settings), ["DM_FPS_TARGET": "30", "DM_RENDER_SCALE": "1.0", "DM_FPS_HOLD": "on"])+ let store = SavedChoices(app: app.path, titleID: titleID)+ for (key, value) in [("DM_FPS_TARGET", "120"), ("DM_RENDER_SCALE", "2"), ("DM_FPS_HOLD", "maybe")] {+ CFPreferencesSetAppValue(SavedChoices.key(key) as CFString, value as CFString, store.domain as CFString)+ }+ XCTAssertEqual(settings.map(store.current), ["30", "1.0", "on"])}func testBannersComeFromTheTitleListAndTakeTheHero() async throws {@@ -618,7 +629,7 @@ final class LibraryTests: XCTestCase {try shot("build", ContentView(model: model, library: library, initialPage: .builds, performStartupChecks: false), size: NSSize(width: 1280, height: 940))if let upscale = LaunchSetting.read(app: library.games.first { $0.id == botwID }!.appPath)?.first(where: { $0.env == "DM_PRESENT_UPSCALE" }) {- library.setLaunchOption(upscale, "metalfx", for: botwID)+ SavedChoices(app: library.games.first { $0.id == botwID }!.appPath, titleID: "01007EF00011E000").set(upscale, "metalfx")}try shot("launch-options", LaunchOptionsView(m: model, library: library, gameID: botwID), size: NSSize(width: 600, height: 700), trafficLights: false) // a sheet: no window controls of its own}@@ -730,7 +741,7 @@ final class LibraryTests: XCTestCase {let dm = URL(fileURLWithPath: first.appPath).appendingPathComponent("Contents/Resources/dm")try FileManager.default.createDirectory(at: dm, withIntermediateDirectories: true)try FileManager.default.copyItem(at: URL(fileURLWithPath: json), to: dm.appendingPathComponent("launcher.json"))- if let fps = LaunchSetting.read(app: first.appPath)?.first(where: { $0.env == "DM_FPS_TARGET" }) { library.setLaunchOption(fps, "60", for: first.id) }+ if let fps = LaunchSetting.read(app: first.appPath)?.first(where: { $0.env == "DM_FPS_TARGET" }) { SavedChoices(app: first.appPath, titleID: first.titleID).set(fps, "60") }let host = NSHostingView(rootView: LaunchOptionsView(m: model, library: library, gameID: first.id).environmentObject(PadFocus()))let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 600, height: 700), styleMask: [.titled], backing: .buffered, defer: false)window.contentView = hostdiff --git a/frontend/Tests/NSPortBuilderTests/SavedChoicesTests.swift b/frontend/Tests/NSPortBuilderTests/SavedChoicesTests.swiftnew file mode 100644index 00000000..9cc990d6--- /dev/null+++ b/frontend/Tests/NSPortBuilderTests/SavedChoicesTests.swift@@ -0,0 +1,177 @@+import XCTest+@testable import NSPortBuilder++/// The launch options as saved choices in the app's own preferences domain, and launcher.json schema 1. Every app here has a+/// bundle ID of this run, so nothing touches a real game's domain; tearDown removes it.+final class SavedChoicesTests: XCTestCase {+ private var temporary: URL!+ private let titleID = "01007EF00011E000"+ private var bundleID: String { "org.nxnative.frontendtests.saved." + temporary.lastPathComponent }++ override func setUpWithError() throws {+ temporary = FileManager.default.temporaryDirectory.appendingPathComponent("nxnative-saved-" + UUID().uuidString)+ try FileManager.default.createDirectory(at: temporary, withIntermediateDirectories: true)+ }++ override func tearDownWithError() throws {+ let domain = bundleID as CFString+ for key in (CFPreferencesCopyKeyList(domain, kCFPreferencesCurrentUser, kCFPreferencesAnyHost) as? [String]) ?? [] {+ CFPreferencesSetAppValue(key as CFString, nil, domain)+ }+ CFPreferencesAppSynchronize(domain)+ try FileManager.default.removeItem(at: temporary)+ }++ private let fps = #"{"env": "DM_FPS_TARGET", "kind": "choice", "section": "Game", "label": "Frame rate", "note": "", "default": "30", "options": [["30", "30 fps"], ["60", "60 fps"]]}"#+ private let scale = #"{"env": "DM_RENDER_SCALE", "kind": "range", "section": "Game", "label": "Render scale", "note": "", "default": "1.0", "min": 0.5, "max": 1.0, "step": 0.05}"#+ private let hold = #"{"env": "DM_FPS_HOLD", "kind": "toggle", "section": "Performance", "label": "Hold", "note": "", "default": "on", "on": "on", "off": "off"}"#++ private func app(_ rows: [String], schema: Int? = 1, bundle: Bool = true) throws -> String {+ let app = temporary.appendingPathComponent("Game.app")+ let dm = app.appendingPathComponent("Contents/Resources/dm")+ try FileManager.default.createDirectory(at: dm, withIntermediateDirectories: true)+ let head = schema.map { "\"schema\": \($0), " } ?? ""+ try Data(#"{\#(head)"game": "\#(titleID)", "settings": [\#(rows.joined(separator: ","))]}"#.utf8).write(to: dm.appendingPathComponent("launcher.json"))+ var info: [String: Any] = ["DMTitleID": titleID]+ if bundle { info["CFBundleIdentifier"] = bundleID }+ try PropertyListSerialization.data(fromPropertyList: info, format: .xml, options: 0).write(to: app.appendingPathComponent("Contents/Info.plist"))+ return app.path+ }++ func testDomainIsTheBundleIDElseThePackersDefault() throws {+ let path = try app([fps])+ XCTAssertEqual(SavedChoices(app: path, titleID: titleID).domain, bundleID)+ let plain = try app([fps], bundle: false)+ XCTAssertEqual(SavedChoices(app: plain, titleID: titleID).domain, "org.nxnative.01007ef00011e000")+ }++ func testWriteReadAndRemoveKeepOnlyNonDefaults() throws {+ let list = try XCTUnwrap(LaunchSetting.read(app: try app([fps, scale, hold])))+ let store = SavedChoices(domain: bundleID)+ XCTAssertEqual(list.map(store.current), ["30", "1.0", "on"])+ store.set(list[0], "60")+ store.set(list[1], "0.75")+ store.set(list[2], "off")+ XCTAssertEqual(store.raw("DM_FPS_TARGET") as? String, "60", "a string under launcher.<VAR>")+ XCTAssertEqual(list.map(store.current), ["60", "0.75", "off"])+ store.set(list[0], "30") // the default: the key goes+ store.set(list[1], "1.00") // a slider's spelling of the default+ XCTAssertNil(store.raw("DM_FPS_TARGET"))+ XCTAssertNil(store.raw("DM_RENDER_SCALE"))+ XCTAssertTrue(store.hasChoices(list))+ store.reset(list)+ XCTAssertFalse(store.hasChoices(list))+ XCTAssertNil(store.raw("DM_FPS_HOLD"))+ }++ func testValidationIsLauncherCs() throws {+ let list = try XCTUnwrap(LaunchSetting.read(app: try app([fps, scale, hold])))+ let store = SavedChoices(domain: bundleID)+ func put(_ env: String, _ v: Any) { CFPreferencesSetAppValue(SavedChoices.key(env) as CFString, v as CFPropertyList, bundleID as CFString) }+ put("DM_FPS_TARGET", "120"); put("DM_FPS_HOLD", "maybe"); put("DM_RENDER_SCALE", "2")+ XCTAssertEqual(list.map(store.current), ["30", "1.0", "on"],"values the build does not offer are ignored")+ for bad in ["0x1", " 0.8", "nan", "", "0.4", "1.01", "1e0x"] { put("DM_RENDER_SCALE", bad); XCTAssertNil(store.value(list[1]), bad) }+ for good in ["0.5", "1", "1.0", "0.85"] { put("DM_RENDER_SCALE", good); XCTAssertEqual(store.value(list[1]), good) }+ put("DM_FPS_TARGET", 60 as NSNumber) // not a string+ XCTAssertNil(store.value(list[0]))+ put("DM_FPS_TARGET", "60"); put("DM_FPS_HOLD", "off")+ XCTAssertEqual(store.value(list[0]), "60"); XCTAssertEqual(store.value(list[2]), "off")+ }++ func testMigrationMovesLegacyOptionsOnceAndOnlyWhereTheDomainHasNone() throws {+ let path = try app([fps, scale, hold])+ let file = temporary.appendingPathComponent("library.json")+ var game = LibraryGame(titleID: titleID, name: "Zelda", appPath: path)+ game.launchOptions = ["DM_FPS_TARGET": "60", "DM_RENDER_SCALE": "9", "DM_FPS_HOLD": "off", "DM_FULLSCREEN": "1", "DM_OLD": "x"]+ try JSONEncoder().encode([game]).write(to: file)+ let library = GameLibrary(file: file)+ let store = SavedChoices(domain: bundleID)+ CFPreferencesSetAppValue(SavedChoices.key("DM_FPS_HOLD") as CFString, "on" as CFString, bundleID as CFString) // already chosen in the app's window+ library.migrateLaunchOptions()+ XCTAssertEqual(store.raw("DM_FPS_TARGET") as? String, "60")+ XCTAssertNil(store.raw("DM_RENDER_SCALE"), "an invalid value is dropped, not written")+ XCTAssertEqual(store.raw("DM_FPS_HOLD") as? String, "on", "the domain's own value wins")+ XCTAssertEqual(library.games[0].launchOptions, ["DM_FULLSCREEN": "1", "DM_OLD": "x"], "what the store has no row for stays")+ XCTAssertEqual(GameLibrary(file: file).games[0].launchOptions, library.games[0].launchOptions, "and it is saved")+ store.set(try XCTUnwrap(LaunchSetting.read(app: path)).first!, "30")+ library.migrateLaunchOptions()+ XCTAssertNil(store.raw("DM_FPS_TARGET"), "once: a second run does not bring the old value back")+ // An old library file still loads+ try Data(#"[{"id": "\#(UUID().uuidString)", "titleID": "\#(titleID)", "name": "Z", "launchOptions": {"DM_FPS_TARGET": "60"}}]"#.utf8).write(to: file)+ XCTAssertEqual(GameLibrary(file: file).games[0].launchOptions, ["DM_FPS_TARGET": "60"])+ }++ func testNeedsShowsASubSettingOnlyWhileTheParentHasTheValue() throws {+ let rumble = #"{"env": "DM_RUMBLE", "kind": "toggle", "section": "Game", "label": "Rumble", "note": "", "default": "1", "on": "1", "off": "0"}"#+ let strength = #"{"env": "DM_RUMBLE_GAIN", "kind": "range", "section": "Game", "label": "Strength", "note": "", "default": "1.0", "min": 0, "max": 1, "step": 0.1, "needs": "DM_RUMBLE=1"}"#+ let orphan = #"{"env": "DM_X", "kind": "toggle", "section": "Game", "label": "X", "note": "", "default": "0", "on": "1", "off": "0", "needs": "DM_NOT_IN_LIST=1"}"#+ let list = try XCTUnwrap(LaunchSetting.read(app: try app([rumble, strength, orphan])))+ func shown(_ rumbleValue: String) -> [String] {+ list.filter { $0.isShown(in: list) { $0.env == "DM_RUMBLE" ? rumbleValue : $0.def } }.map(\.env)+ }+ XCTAssertEqual(shown("1"), ["DM_RUMBLE", "DM_RUMBLE_GAIN", "DM_X"])+ XCTAssertEqual(shown("0"), ["DM_RUMBLE", "DM_X"], "a row naming a variable the list lacks stays shown")+ }++ func testAnUnknownSectionComesAfterTheKnownOnesInListOrder() throws {+ func row(_ env: String, _ section: String) -> String {+ #"{"env": "\#(env)", "kind": "toggle", "section": "\#(section)", "label": "L", "note": "", "default": "0", "on": "1", "off": "0"}"#+ }+ let list = try XCTUnwrap(LaunchSetting.read(app: try app([row("DM_A", "Picture"), row("DM_B", "Game"), row("DM_C", "Audio"), row("DM_D", "Performance"), row("DM_E", "Picture")])))+ XCTAssertEqual(LaunchSetting.orderedSections(list), ["Game", "Performance", "Picture", "Audio"])+ }++ func testARangeTakesItsBoundsFromTheRowAndPictureIsDrawn() throws {+ let wide = #"{"env": "DM_RENDER_SCALE", "kind": "range", "section": "Picture", "label": "Render scale", "note": "", "default": "1.0", "min": 0.5, "max": 1.35, "step": 0.05, "base": {"docked": [1600, 900], "handheld": [1280, 720]}}"#+ let list = try XCTUnwrap(LaunchSetting.read(app: try app([fps, wide])))+ let s = list[1]+ XCTAssertEqual(s.max, 1.35)+ XCTAssertTrue(s.accepts("1.35")); XCTAssertFalse(s.accepts("1.4"))+ XCTAssertEqual(s.pixels(scale: 1.35, docked: true), "2160×1215", "no ceiling of 1.0 in the pixel display")+ let store = SavedChoices(domain: bundleID)+ store.set(s, "1.35")+ XCTAssertEqual(store.current(s), "1.35")+ XCTAssertEqual(LaunchSetting.orderedSections(list), ["Game", "Picture"])+ }++ func testTheRowsBaseWinsOverTheProfilesRenderBase() throws {+ let withBase = scale.dropLast() + #", "base": {"docked": [1920, 1080], "handheld": [1280, 720]}}"#+ let path = try app([String(withBase)])+ let profile = temporary.appendingPathComponent("repo/dm/games/\(titleID)")+ try FileManager.default.createDirectory(at: profile, withIntermediateDirectories: true)+ try "title_id\t\(titleID)\nrender_base\t1600x900 1280x720\n".write(to: profile.appendingPathComponent("game.tsv"), atomically: true, encoding: .utf8)+ let s = try XCTUnwrap(LaunchSetting.forMac(app: path, titleID: titleID, repo: temporary.appendingPathComponent("repo").path, labels: { $0 })?.first)+ XCTAssertEqual(s.pixels(scale: 1, docked: true), "1920×1080")+ // Without a base in the row the profile's still applies+ let plain = try app([scale])+ let p = try XCTUnwrap(LaunchSetting.forMac(app: plain, titleID: titleID, repo: temporary.appendingPathComponent("repo").path, labels: { $0 })?.first)+ XCTAssertEqual(p.pixels(scale: 1, docked: true), "1600×900")+ }++ func testAHigherSchemaIsReadAsFarAsItCanBeAndLogged() throws {+ let future = #"{"env": "DM_Z", "kind": "dial", "section": "Game", "label": "Z", "note": "", "default": "0"}"#+ let data = Data(#"{"schema": 2, "game": "\#(titleID)", "settings": [\#(fps), \#(future), {"broken": true}]}"#.utf8)+ var logged: [String] = []+ let parsed = try XCTUnwrap(LaunchList.parse(data) { logged.append($0) })+ XCTAssertEqual(parsed.schema, 2)+ XCTAssertEqual(parsed.settings.map(\.env), ["DM_FPS_TARGET"], "a kind it cannot draw and a row it cannot read are left out")+ XCTAssertEqual(logged.count, 1)+ var none: [String] = []+ XCTAssertEqual(LaunchList.parse(Data(#"{"game": "\#(titleID)", "settings": []}"#.utf8)) { none.append($0) }?.schema, 1)+ XCTAssertTrue(none.isEmpty)+ }++ func testStartEnvironmentSkipsTheAppsWindowAndPassesOnlyOverrides() throws {+ let path = try app([fps, scale])+ let settings = try XCTUnwrap(LaunchSetting.forMac(app: path, titleID: titleID, repo: "", labels: { $0 }))+ var game = LibraryGame(titleID: titleID, name: "Zelda", appPath: path)+ let store = SavedChoices(domain: bundleID)+ store.set(settings[0], "60")+ var env = game.startEnvironment(controls: ["DM_KEYMAP": "a=b"], settings: settings, mods: [])+ XCTAssertEqual(env, ["DM_LAUNCHER": "0", "DM_KEYMAP": "a=b"], "saved choices are not in the environment, where they would override the store")+ game.launchOptions["DM_FULLSCREEN"] = "1"+ env = game.startEnvironment(controls: [:], settings: settings, mods: [])+ XCTAssertEqual(env, ["DM_LAUNCHER": "0", "DM_FULLSCREEN": "1"], "a launcher-only setting is an override, never written to the store")+ XCTAssertNil(store.raw("DM_FULLSCREEN"))+ }+}