Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
86 changes: 67 additions & 19 deletions frontend/Sources/NSPortBuilder/LaunchOptionsView.swift
Original file line number Diff line number Diff line change
@@ -1,15 +1,20 @@
import AppKit
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, one screen grouped by section. Play passes them to the app as its environment.
/// iPhone launcher draws them, grouped by section. The basic settings come first, and the rest
/// under Advanced settings. Play passes them to the app as its environment.
struct LaunchOptionsView: View {
@ObservedObject var m: BuildModel
@ObservedObject var library: GameLibrary
let gameID: UUID
@Environment(\.dismiss) private var dismiss
@State private var advancedOpen = false

private var game: LibraryGame? { library.games.first { $0.id == gameID } }
private var settings: [LaunchSetting]? { game.flatMap { LaunchSetting.read(app: $0.appPath) } }
private var settings: [LaunchSetting]? {
game.flatMap { LaunchSetting.forMac(app: $0.appPath, titleID: $0.titleID, repo: m.repoPath, labels: m.t) }
}

var body: some View {
VStack(alignment: .leading, spacing: 0) {
Expand All @@ -24,20 +29,23 @@ struct LaunchOptionsView: View {
if let settings, !settings.isEmpty, let game {
ScrollView {
VStack(alignment: .leading, spacing: 24) {
ForEach(sections(settings), id: \.self) { section in
let rows = settings.filter { $0.sectionTitle == section }
VStack(alignment: .leading, spacing: 10) {
Text(m.t("launch.section." + section)).font(.manrope(15, .semibold)).foregroundStyle(.secondary)
.padding(.leading, 2)
VStack(spacing: 0) {
ForEach(rows) { s in
row(s, game)
if s.id != rows.last?.id { Divider().opacity(0.25).padding(.leading, 18) }
groups(settings.filter(\.isBasic), game, all: settings)
let advanced = settings.filter { !$0.isBasic }
if !advanced.isEmpty {
card {
Button { withAnimation(.easeInOut(duration: 0.18)) { advancedOpen.toggle() } } label: {
HStack(spacing: 8) {
Text(m.t("launch.advanced")).font(.manrope(14, .medium))
Image(systemName: "chevron.right").font(.system(size: 10, weight: .bold)).foregroundStyle(.secondary)
.rotationEffect(.degrees(advancedOpen ? 90 : 0))
Spacer()
Text(String(format: m.t("launch.advancedCount"), advanced.count)).font(.manrope(12)).foregroundStyle(.secondary)
}
.padding(.horizontal, 18).frame(minHeight: 52).contentShape(Rectangle())
}
.background(LauncherPalette.surface.opacity(0.75), in: RoundedRectangle(cornerRadius: 14))
.overlay(RoundedRectangle(cornerRadius: 14).strokeBorder(Color.white.opacity(0.06)))
.buttonStyle(.plain)
}
if advancedOpen { groups(advanced, game, all: settings) }
}
}
.padding(.horizontal, 30).padding(.bottom, 24)
Expand Down Expand Up @@ -71,30 +79,70 @@ struct LaunchOptionsView: View {
.tint(LauncherPalette.cream)
}

// ---- 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 }
VStack(alignment: .leading, spacing: 10) {
heading(m.t("launch.section." + section))
card {
ForEach(inSection) { s in
row(s, game, all: all)
if s.id != inSection.last?.id { divider }
}
}
}
}
}

private func heading(_ text: String) -> some View {
Text(text).font(.manrope(15, .semibold)).foregroundStyle(.secondary).padding(.leading, 2)
}

private func card<Content: View>(@ViewBuilder _ content: () -> Content) -> some View {
VStack(spacing: 0, content: content)
.background(LauncherPalette.surface.opacity(0.75), in: RoundedRectangle(cornerRadius: 14))
.overlay(RoundedRectangle(cornerRadius: 14).strokeBorder(Color.white.opacity(0.06)))
}

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) } }
}

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) : nil
HStack(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":
Expand All @@ -109,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) }))
Expand Down
4 changes: 3 additions & 1 deletion frontend/Sources/NSPortBuilder/LauncherView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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 in
DispatchQueue.main.async {
Expand Down
53 changes: 50 additions & 3 deletions frontend/Sources/NSPortBuilder/Library.swift
Original file line number Diff line number Diff line change
Expand Up @@ -55,8 +55,17 @@ struct LaunchSetting: Decodable, Identifiable {
let options: [[String]]? // choice: [value, label]
let min, max, step: Double? // range
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? = 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.
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" }
func isDefault(_ v: String) -> Bool { // a range compares as numbers (a slider writes 1.00 for 1.0)
Expand All @@ -72,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 }
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.
Expand All @@ -81,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 {
Expand All @@ -89,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 {
Expand Down
7 changes: 7 additions & 0 deletions frontend/Sources/NSPortBuilder/Localization.swift
Original file line number Diff line number Diff line change
Expand Up @@ -438,6 +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: %@ → %@"),
]

Expand Down
61 changes: 61 additions & 0 deletions frontend/Tests/NSPortBuilderTests/LaunchOptionsTests.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import XCTest
@testable import NSPortBuilder

/// 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!

override func setUpWithError() throws {
temporary = FileManager.default.temporaryDirectory.appendingPathComponent("nxnative-launch-" + UUID().uuidString)
try FileManager.default.createDirectory(at: temporary, withIntermediateDirectories: true)
}

override func tearDownWithError() throws { try FileManager.default.removeItem(at: temporary) }

/// 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)
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 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 (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")
}

}