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: Display mode, and the render scale in pixels (#35, #36)
v0lumehic84f68180e1e
diff --git a/frontend/Sources/NSPortBuilder/LaunchOptionsView.swift b/frontend/Sources/NSPortBuilder/LaunchOptionsView.swiftindex 8321b664..2cac9d1d 100644--- a/frontend/Sources/NSPortBuilder/LaunchOptionsView.swift+++ b/frontend/Sources/NSPortBuilder/LaunchOptionsView.swift@@ -13,7 +13,7 @@ struct LaunchOptionsView: View {private var game: LibraryGame? { library.games.first { $0.id == gameID } }private var settings: [LaunchSetting]? {- game.flatMap { LaunchSetting.read(app: $0.appPath) }+ game.flatMap { LaunchSetting.forMac(app: $0.appPath, titleID: $0.titleID, repo: m.repoPath, labels: m.t) }}var body: some View {@@ -29,7 +29,7 @@ struct LaunchOptionsView: View {if let settings, !settings.isEmpty, let game {ScrollView {VStack(alignment: .leading, spacing: 24) {- groups(settings.filter(\.isBasic), game)+ groups(settings.filter(\.isBasic), game, all: settings)let advanced = settings.filter { !$0.isBasic }if !advanced.isEmpty {card {@@ -45,7 +45,7 @@ struct LaunchOptionsView: View {}.buttonStyle(.plain)}- if advancedOpen { groups(advanced, game) }+ if advancedOpen { groups(advanced, game, all: settings) }}}.padding(.horizontal, 30).padding(.bottom, 24)@@ -81,14 +81,14 @@ struct LaunchOptionsView: View {// ---- groups of settings ----- @ViewBuilder private func groups(_ rows: [LaunchSetting], _ game: LibraryGame) -> some View {+ @ViewBuilder private func groups(_ rows: [LaunchSetting], _ game: LibraryGame, all: [LaunchSetting]) -> some View {ForEach(sections(rows), id: \.self) { section inlet inSection = rows.filter { $0.sectionTitle == section }VStack(alignment: .leading, spacing: 10) {heading(m.t("launch.section." + section))card {ForEach(inSection) { s in- row(s, game)+ row(s, game, all: all)if s.id != inSection.last?.id { divider }}}@@ -114,24 +114,35 @@ struct LaunchOptionsView: View {private func set(_ s: LaunchSetting, _ value: String) { library.setLaunchOption(s, value, for: gameID) }- @ViewBuilder private func row(_ s: LaunchSetting, _ game: LibraryGame) -> some View {+ /// 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+ }++ @ViewBuilder private func row(_ s: LaunchSetting, _ game: LibraryGame, all: [LaunchSetting]) -> some View {let value = game.launchValue(s)+ let isDocked = docked(game, all)+ let pixels = s.kind == "range" ? s.pixels(scale: Double(value) ?? 1, docked: isDocked) : nilHStack(alignment: .center, spacing: 16) {VStack(alignment: .leading, spacing: 3) {Text(s.label).font(.manrope(14, .medium))- if !s.note.isEmpty {+ if let full = s.kind == "range" ? s.pixels(scale: 1, docked: isDocked) : nil {+ // The render scale in pixels: the share of the game's own size in the console mode chosen+ Text(String(format: m.t(isDocked ? "launch.scaleOfDocked" : "launch.scaleOfHandheld"), Int(((Double(value) ?? 1) * 100).rounded()), full))+ .font(.manrope(12)).foregroundStyle(.secondary)+ } else if !s.note.isEmpty {Text(s.note).font(.manrope(12)).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)}}Spacer(minLength: 12)- control(s, value).frame(width: LaunchControl.width, alignment: .trailing)+ control(s, value, pixels: pixels).frame(width: LaunchControl.width, alignment: .trailing)}.padding(.horizontal, 18).padding(.vertical, 13).frame(minHeight: 52)}/// The setting's control, filling the column every row shares (a toggle keeps its size at the column's right edge).- @ViewBuilder private func control(_ s: LaunchSetting, _ value: String) -> some View {+ @ViewBuilder private func control(_ s: LaunchSetting, _ value: String, pixels: String?) -> some View {HStack(spacing: 10) {switch s.kind {case "choice":@@ -146,9 +157,9 @@ struct LaunchOptionsView: View {LauncherSlider(value: Double(value) ?? Double(s.def) ?? lo, range: lo...hi, step: s.step ?? 0.05) {set(s, String(format: "%.2f", $0))}- Text("\(Int(((Double(value) ?? 0) * 100).rounded()))%")+ Text(pixels ?? "\(Int(((Double(value) ?? 0) * 100).rounded()))%").font(.manrope(13, .semibold)).monospacedDigit().foregroundStyle(.secondary)- .frame(width: 44, alignment: .trailing)+ .frame(width: pixels == nil ? 44 : 72, alignment: .trailing)default:Spacer(minLength: 0)Toggle("", isOn: Binding(get: { value == s.onValue }, set: { set(s, $0 ? s.onValue : s.offValue) }))diff --git a/frontend/Sources/NSPortBuilder/LauncherView.swift b/frontend/Sources/NSPortBuilder/LauncherView.swiftindex 7af84ea2..cdfff77d 100644--- a/frontend/Sources/NSPortBuilder/LauncherView.swift+++ b/frontend/Sources/NSPortBuilder/LauncherView.swift@@ -475,7 +475,9 @@ struct ContentView: View {// 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.read(app: game.appPath) { environment.merge(game.launchEnvironment(settings)) { _, own in own } }+ 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 }+ }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 ca74b5a4..f66877f0 100644--- a/frontend/Sources/NSPortBuilder/Library.swift+++ b/frontend/Sources/NSPortBuilder/Library.swift@@ -57,10 +57,14 @@ struct LaunchSetting: Decodable, Identifiable {let on, off: String? // toggle: the values the variable takes/// "basic" for a setting shown first (settings.tsv's level column, seedds/nxnative#399); without it, `basicByDefault` decides.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+ /// The value that leaves the variable unset (DM_FULLSCREEN is on when it is set at all).+ var unsetValue: String? = nilvar 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.- static let basicByDefault: Set = ["DM_FPS_TARGET", "DM_RENDER_SCALE", "DM_OPMODE", "DM_LANG", "DM_RUMBLE"]+ static let basicByDefault: Set = ["DM_FPS_TARGET", "DM_RENDER_SCALE", "DM_FULLSCREEN", "DM_OPMODE", "DM_LANG", "DM_RUMBLE"]var isBasic: Bool { level.map { $0 == "basic" } ?? Self.basicByDefault.contains(env) }var onValue: String { on ?? "1" }var offValue: String { off ?? "0" }@@ -77,7 +81,7 @@ struct LaunchSetting: Decodable, Identifiable {default: return true}}- enum CodingKeys: String, CodingKey { case env, kind, label, note, def = "default", section, options, min, max, step, on, off, level }+ enum CodingKeys: String, CodingKey { case env, kind, label, note, def = "default", section, options, min, max, step, on, off, level, base }private struct File: Decodable { let settings: [LaunchSetting] }/// The settings a Mac app was packed with; nil for an app packed before they were.@@ -86,6 +90,39 @@ struct LaunchSetting: Decodable, Identifiable {guard let data = try? Data(contentsOf: url) else { return nil }return (try? JSONDecoder().decode(File.self, from: 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+ /// DM_FULLSCREEN in front_mac.m; a list from settings.tsv will carry it as a platform:mac row), and the render scale's+ /// base size from the game's profile in the repository when the list does not carry it (render_base).+ static func forMac(app: String, titleID: String, repo: String, labels: (String) -> String) -> [LaunchSetting]? {+ guard var list = read(app: app) else { return nil }+ if !list.contains(where: { $0.env == "DM_FULLSCREEN" }) {+ let display = LaunchSetting(env: "DM_FULLSCREEN", kind: "choice", label: labels("launch.display"), note: "", def: "",+ section: "Game", options: [["", labels("launch.display.window")], ["1", labels("launch.display.fullscreen")]],+ min: nil, max: nil, step: nil, on: nil, off: nil, unsetValue: "")+ list.insert(display, at: (list.firstIndex { $0.env == "DM_RENDER_SCALE" }).map { $0 + 1 } ?? 0)+ }+ if let i = list.firstIndex(where: { $0.env == "DM_RENDER_SCALE" && $0.base == nil }), let base = renderBase(titleID: titleID, repo: repo) {+ list[i].base = base+ }+ return list+ }++ /// render_base in the game's profile ("1600x900 1280x720": docked, then handheld).+ static func renderBase(titleID: String, repo: String) -> [String: [Int]]? {+ let path = repo + "/dm/games/" + titleID + "/game.tsv"+ guard !repo.isEmpty, let text = try? String(contentsOfFile: path, encoding: .utf8),+ let line = text.split(separator: "\n").first(where: { $0.hasPrefix("render_base\t") }) else { return nil }+ let sizes = line.dropFirst("render_base\t".count).split(separator: " ").map { $0.split(separator: "x").compactMap { Int($0) } }+ guard sizes.count == 2, sizes.allSatisfy({ $0.count == 2 }) else { return nil }+ return ["docked": sizes[0], "handheld": sizes[1]]+ }++ /// The render scale as pixels: the base size of the console mode chosen (DM_OPMODE: 1 docked, 0 handheld) times the scale.+ func pixels(scale: Double, docked: Bool) -> String? {+ guard let size = base?[docked ? "docked" : "handheld"], size.count == 2 else { return nil }+ return "\(Int((Double(size[0]) * scale).rounded()))×\(Int((Double(size[1]) * scale).rounded()))"+ }}extension LibraryGame {@@ -94,10 +131,15 @@ extension LibraryGame {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.+ /// 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.func launchEnvironment(_ settings: [LaunchSetting]) -> [String: String] {- Dictionary(uniqueKeysWithValues: settings.map { ($0.env, launchValue($0)) })+ Dictionary(uniqueKeysWithValues: settings.compactMap { s in+ let v = launchValue(s)+ return s.unsetValue == v ? nil : (s.env, v)+ })}+}struct MacGameBundle {diff --git a/frontend/Sources/NSPortBuilder/Localization.swift b/frontend/Sources/NSPortBuilder/Localization.swiftindex e3b3982a..7dd4dc01 100644--- a/frontend/Sources/NSPortBuilder/Localization.swift+++ b/frontend/Sources/NSPortBuilder/Localization.swift@@ -438,8 +438,13 @@ enum L10n {"controls.fn.LS": ("按下左摇杆", "Left stick press"),"controls.fn.RS": ("按下右摇杆", "Right stick press"),"controls.fn.Shake": ("摇动手柄", "Shake"),+ "launch.display": ("显示模式", "Display mode"),+ "launch.display.window": ("窗口", "Window"),+ "launch.display.fullscreen": ("全屏", "Fullscreen"),"launch.advanced": ("高级设置", "Advanced settings"),"launch.advancedCount": ("%ld 项", "%ld settings"),+ "launch.scaleOfDocked": ("底座模式 %2$@ 的 %1$ld%%", "%ld%% of %@ docked"),+ "launch.scaleOfHandheld": ("掌机模式 %2$@ 的 %1$ld%%", "%ld%% of %@ handheld"),"msg.archiveLog": ("归档:%@ → %@", "Archive: %@ → %@"),]diff --git a/frontend/Tests/NSPortBuilderTests/LaunchOptionsTests.swift b/frontend/Tests/NSPortBuilderTests/LaunchOptionsTests.swiftindex 96648ce6..af85ec68 100644--- a/frontend/Tests/NSPortBuilderTests/LaunchOptionsTests.swift+++ b/frontend/Tests/NSPortBuilderTests/LaunchOptionsTests.swift@@ -1,7 +1,7 @@import XCTest@testable import NSPortBuilder-/// Launch options beyond the app's own list: the basic / advanced split.+/// Launch options beyond the app's own list: Display mode, the basic / advanced split and the render scale in pixels.final class LaunchOptionsTests: XCTestCase {private var temporary: URL!@@ -12,23 +12,50 @@ final class LaunchOptionsTests: XCTestCase {override func tearDownWithError() throws { try FileManager.default.removeItem(at: temporary) }- /// A Mac app with a launcher.json of the given rows.- private func app(_ rows: String) throws -> String {+ /// A Mac app with a launcher.json of the given rows, and a repository with a profile for its title ID.+ private func app(_ rows: String, renderBase: String? = nil) throws -> (app: String, repo: String) {let app = temporary.appendingPathComponent("Game.app")let dm = app.appendingPathComponent("Contents/Resources/dm")try FileManager.default.createDirectory(at: dm, withIntermediateDirectories: true)try #"{"game": "01007EF00011E000", "settings": [\#(rows)]}"#.write(to: dm.appendingPathComponent("launcher.json"), atomically: true, encoding: .utf8)- return app.path+ let profile = temporary.appendingPathComponent("repo/dm/games/01007EF00011E000")+ try FileManager.default.createDirectory(at: profile, withIntermediateDirectories: true)+ try "title_id\t01007EF00011E000\n\(renderBase.map { "render_base\t\($0)\n" } ?? "")".write(to: profile.appendingPathComponent("game.tsv"), atomically: true, encoding: .utf8)+ return (app.path, temporary.appendingPathComponent("repo").path)}private let scale = #"{"env": "DM_RENDER_SCALE", "kind": "range", "label": "Render scale", "note": "", "default": "1.0", "section": "Game", "min": 0.5, "max": 1.0, "step": 0.05}"#+ private let opmode = #"{"env": "DM_OPMODE", "kind": "choice", "label": "Console mode", "note": "", "default": "1", "section": "Game", "options": [["1", "Docked"], ["0", "Handheld"]]}"#private let hud = #"{"env": "DM_METAL_HUD", "kind": "toggle", "label": "Metal HUD", "note": "", "default": "0", "section": "Performance", "on": "1", "off": "0"}"#+ func testDisplayModeComesAfterTheRenderScaleAndWindowLeavesTheVariableUnset() throws {+ let (app, repo) = try app([scale, opmode].joined(separator: ","))+ let list = try XCTUnwrap(LaunchSetting.forMac(app: app, titleID: "01007EF00011E000", repo: repo, labels: { $0 }))+ XCTAssertEqual(list.map(\.env), ["DM_RENDER_SCALE", "DM_FULLSCREEN", "DM_OPMODE"])+ var game = LibraryGame(titleID: "01007EF00011E000", name: "Zelda")+ XCTAssertNil(game.launchEnvironment(list)["DM_FULLSCREEN"], "the host starts fullscreen when the variable is set at all")+ game.launchOptions["DM_FULLSCREEN"] = "1"+ XCTAssertEqual(game.launchEnvironment(list)["DM_FULLSCREEN"], "1")+ }+func testBasicRowsFirstTheRestAdvancedUnlessTheListSaysOtherwise() throws {- let list = try XCTUnwrap(LaunchSetting.read(app: try app([scale, hud].joined(separator: ","))))- XCTAssertEqual(list.filter(\.isBasic).map(\.env), ["DM_RENDER_SCALE"])+ let leveled = #"{"env": "DM_METAL_HUD", "kind": "toggle", "label": "Metal HUD", "note": "", "default": "0", "section": "Performance", "on": "1", "off": "0", "level": "basic"}"#+ let (app, repo) = try app([scale, hud].joined(separator: ","))+ let list = try XCTUnwrap(LaunchSetting.forMac(app: app, titleID: "01007EF00011E000", repo: repo, labels: { $0 }))+ XCTAssertEqual(list.filter(\.isBasic).map(\.env), ["DM_RENDER_SCALE", "DM_FULLSCREEN"])XCTAssertEqual(list.filter { !$0.isBasic }.map(\.env), ["DM_METAL_HUD"])- let leveled = hud.replacingOccurrences(of: #""off": "0"}"#, with: #""off": "0", "level": "basic"}"#)- XCTAssertTrue(try XCTUnwrap(LaunchSetting.read(app: try app(leveled))).first!.isBasic, "a level in launcher.json (seedds/nxnative#399) wins over the default split")+ let (app2, _) = try self.app(leveled)+ XCTAssertTrue(try XCTUnwrap(LaunchSetting.read(app: app2)).first!.isBasic, "a level in launcher.json wins over the default split")}++ func testRenderScaleInPixelsFromTheProfile() throws {+ let (app, repo) = try app(scale, renderBase: "1600x900 1280x720")+ let s = try XCTUnwrap(LaunchSetting.forMac(app: app, titleID: "01007EF00011E000", repo: repo, labels: { $0 })?.first)+ XCTAssertEqual(s.pixels(scale: 0.5, docked: true), "800×450")+ XCTAssertEqual(s.pixels(scale: 0.75, docked: false), "960×540")+ let (plain, repo2) = try self.app(scale)+ XCTAssertNil(try XCTUnwrap(LaunchSetting.forMac(app: plain, titleID: "01007EF00011E000", repo: repo2, labels: { $0 })?.first).pixels(scale: 1, docked: true),+ "without render_base the row stays in percent")+ }+}