Skip to content

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

Launch options: a game's mods (#34)

v0lumehi0b2b1336db8b
diff --git a/frontend/Sources/NSPortBuilder/LaunchOptionsView.swift b/frontend/Sources/NSPortBuilder/LaunchOptionsView.swift
index fabf04e9..65efb68d 100644
--- a/frontend/Sources/NSPortBuilder/LaunchOptionsView.swift
+++ b/frontend/Sources/NSPortBuilder/LaunchOptionsView.swift
@@ -2,7 +2,7 @@ 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, grouped by section. The basic settings come first, and the rest
+/// 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.
struct LaunchOptionsView: View {
@ObservedObject var m: BuildModel
@@ -10,12 +10,19 @@ struct LaunchOptionsView: View {
let gameID: UUID
@Environment(\.dismiss) private var dismiss
@State private var advancedOpen = false
+ @State private var modsRevision = 0 // bumped by Refresh: the folder is read again
@EnvironmentObject private var focus: PadFocus
private var game: LibraryGame? { library.games.first { $0.id == gameID } }
private var settings: [LaunchSetting]? {
game.flatMap { LaunchSetting.forMac(app: $0.appPath, titleID: $0.titleID, repo: m.repoPath, labels: m.t) }
}
+ private var modsFolder: URL? { game.map { GameMod.folder(for: $0, library: library.folder) } }
+ private var mods: [GameMod] {
+ _ = modsRevision
+ guard let game, let modsFolder else { return [] }
+ return GameMod.list(in: modsFolder, titleID: game.titleID)
+ }
var body: some View {
VStack(alignment: .leading, spacing: 0) {
@@ -32,6 +39,7 @@ struct LaunchOptionsView: View {
ScrollView {
VStack(alignment: .leading, spacing: 24) {
groups(settings.filter(\.isBasic), game, all: settings)
+ modsSection(game)
let advanced = settings.filter { !$0.isBasic }
if !advanced.isEmpty {
card {
@@ -193,4 +201,78 @@ struct LaunchOptionsView: View {
}
}
}
+
+ // ---- mods ----
+
+ /// The game's mods folder as switches. A mod changes the files the game reads, saves included: the note says so, and
+ /// Show saves opens the folder to back them up before switching one.
+ @ViewBuilder private func modsSection(_ game: LibraryGame) -> some View {
+ let list = mods
+ VStack(alignment: .leading, spacing: 10) {
+ heading(m.t("launch.mods"))
+ card {
+ if list.isEmpty {
+ HStack(spacing: 16) {
+ VStack(alignment: .leading, spacing: 3) {
+ Text(m.t("launch.modsNone")).font(.manrope(14, .medium))
+ Text(m.t("launch.modsHow")).font(.manrope(12)).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)
+ }
+ Spacer()
+ }
+ .padding(.horizontal, 18).padding(.vertical, 13)
+ } else {
+ ForEach(list) { mod in
+ HStack(spacing: 16) {
+ VStack(alignment: .leading, spacing: 3) {
+ Text(mod.name).font(.manrope(14, .medium)).lineLimit(1)
+ if !mod.usable {
+ Text(m.t("launch.modCode")).font(.manrope(12)).foregroundStyle(.secondary)
+ }
+ }
+ Spacer(minLength: 12)
+ Toggle("", isOn: Binding(get: { mod.usable && game.mods.contains(mod.name) },
+ set: { library.setMod(mod.name, on: $0, for: gameID) }))
+ .labelsHidden().toggleStyle(LauncherSwitchStyle()).disabled(!mod.usable)
+ }
+ .padding(.horizontal, 18).padding(.vertical, 13).frame(minHeight: 52)
+ .padTarget("mod." + mod.name, scope: "launch", radius: 10,
+ activate: { if mod.usable { library.setMod(mod.name, on: !game.mods.contains(mod.name), for: gameID) } },
+ adjust: { _ in if mod.usable { library.setMod(mod.name, on: !game.mods.contains(mod.name), for: gameID) } })
+ divider
+ }
+ }
+ if list.isEmpty { divider }
+ HStack(spacing: 10) {
+ Spacer()
+ Button(m.t("launch.modsRefresh")) { modsRevision += 1 }
+ .padTarget("mods.refresh", scope: "launch") { modsRevision += 1 }
+ Button(m.t("launch.modsOpen")) { openModsFolder() }
+ .padTarget("mods.open", scope: "launch") { openModsFolder() }
+ Button(m.t("launch.savesShow")) { showSaves(game) }
+ .padTarget("mods.saves", scope: "launch") { showSaves(game) }
+ }
+ .buttonStyle(LauncherSecondaryButtonStyle())
+ .padding(.horizontal, 18).padding(.vertical, 12)
+ }
+ Text(m.t(list.count > 1 ? "launch.modsNoteOrder" : "launch.modsNote")).font(.manrope(12)).foregroundStyle(.secondary)
+ .padding(.leading, 2).fixedSize(horizontal: false, vertical: true)
+ }
+ }
+
+ private func openModsFolder() {
+ guard let folder = modsFolder else { return }
+ try? FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
+ NSWorkspace.shared.open(folder)
+ modsRevision += 1
+ }
+
+ /// The app's saves (dm/mac/launcher.c: ~/Library/Application Support/nxnative/<title ID>/), to back them up.
+ private func showSaves(_ game: LibraryGame) {
+ let support = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0]
+ .appendingPathComponent("nxnative").appendingPathComponent(game.titleID)
+ let save = support.appendingPathComponent("save")
+ let target = FileManager.default.fileExists(atPath: save.path) ? save : support
+ if FileManager.default.fileExists(atPath: target.path) { NSWorkspace.shared.activateFileViewerSelecting([target]) }
+ else { NSWorkspace.shared.open(support.deletingLastPathComponent()) }
+ }
}
diff --git a/frontend/Sources/NSPortBuilder/LauncherView.swift b/frontend/Sources/NSPortBuilder/LauncherView.swift
index b2c7aeb8..02e214a5 100644
--- a/frontend/Sources/NSPortBuilder/LauncherView.swift
+++ b/frontend/Sources/NSPortBuilder/LauncherView.swift
@@ -553,6 +553,7 @@ struct ContentView: View {
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 }
if !environment.isEmpty { configuration.environment = environment }
NSWorkspace.shared.openApplication(at: URL(fileURLWithPath: game.appPath), configuration: configuration) { _, error in
DispatchQueue.main.async {
diff --git a/frontend/Sources/NSPortBuilder/Library.swift b/frontend/Sources/NSPortBuilder/Library.swift
index f66877f0..9c6ba28c 100644
--- a/frontend/Sources/NSPortBuilder/Library.swift
+++ b/frontend/Sources/NSPortBuilder/Library.swift
@@ -14,6 +14,7 @@ struct LibraryGame: Codable, Identifiable, Equatable {
var outputDirectory = ""
var artworkPath = ""
var launchOptions: [String: String] = [:]
+ var mods: [String] = [] // the mods (folder names in the game's mods folder) switched on
var iosAppPath = ""
var installedDevice = ""
@@ -42,6 +43,7 @@ extension LibraryGame {
outputDirectory = try c.decodeIfPresent(String.self, forKey: .outputDirectory) ?? ""
artworkPath = try c.decodeIfPresent(String.self, forKey: .artworkPath) ?? ""
launchOptions = try c.decodeIfPresent([String: String].self, forKey: .launchOptions) ?? [:]
+ mods = try c.decodeIfPresent([String].self, forKey: .mods) ?? []
iosAppPath = try c.decodeIfPresent(String.self, forKey: .iosAppPath) ?? ""
installedDevice = try c.decodeIfPresent(String.self, forKey: .installedDevice) ?? ""
}
@@ -125,6 +127,40 @@ struct LaunchSetting: Decodable, Identifiable {
}
}
+/// A folder in the game's mods folder: RomFS files that replace the game's own (DM_ROMFS_OVERLAY, hle_fs.c). The files are
+/// found in <mod>/romfs, in an Atmosphère layout (<mod>/atmosphere/contents/<title ID>/romfs, <mod>/contents/<title ID>/romfs)
+/// or in the folder itself. A mod with only exefs/ changes the game's code, which the rewriter does not take: listed, not usable.
+struct GameMod: Identifiable, Equatable {
+ let name: String
+ let romfs: String?
+ var id: String { name }
+ var usable: Bool { romfs != nil }
+
+ static func folder(for game: LibraryGame, library: String) -> URL {
+ let root = library.isEmpty
+ ? FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0].appendingPathComponent("NS Port Builder")
+ : URL(fileURLWithPath: library)
+ return root.appendingPathComponent("mods").appendingPathComponent(game.titleID)
+ }
+
+ static func list(in folder: URL, titleID: String) -> [GameMod] {
+ let fm = FileManager.default
+ let names = ((try? fm.contentsOfDirectory(atPath: folder.path)) ?? []).filter { !$0.hasPrefix(".") }.sorted {
+ $0.localizedStandardCompare($1) == .orderedAscending
+ }
+ return names.compactMap { name in
+ var dir: ObjCBool = false
+ let mod = folder.appendingPathComponent(name)
+ guard fm.fileExists(atPath: mod.path, isDirectory: &dir), dir.boolValue else { return nil }
+ let candidates = ["romfs", "atmosphere/contents/\(titleID)/romfs", "contents/\(titleID)/romfs"].map { mod.appendingPathComponent($0).path }
+ if let found = candidates.first(where: { fm.fileExists(atPath: $0) }) { return GameMod(name: name, romfs: found) }
+ let top = ((try? fm.contentsOfDirectory(atPath: mod.path)) ?? []).filter { !$0.hasPrefix(".") }
+ let codeOnly = top.allSatisfy { ["exefs", "atmosphere", "contents"].contains($0.lowercased()) } && !top.isEmpty
+ return GameMod(name: name, romfs: codeOnly || top.isEmpty ? nil : mod.path)
+ }
+ }
+}
+
extension LibraryGame {
/// The value each setting takes: the player's choice while the build still offers it, else the game's default.
func launchValue(_ s: LaunchSetting) -> String {
@@ -140,6 +176,12 @@ extension LibraryGame {
})
}
+ /// DM_ROMFS_OVERLAY for the mods switched on that can be used, in the list's order: where two replace one file, the
+ /// one higher in the list wins (the host looks in the folders in order).
+ func modEnvironment(_ available: [GameMod]) -> [String: String] {
+ let paths = available.filter { mods.contains($0.name) }.compactMap(\.romfs)
+ return paths.isEmpty ? [:] : ["DM_ROMFS_OVERLAY": paths.joined(separator: ":")]
+ }
}
struct MacGameBundle {
@@ -349,6 +391,14 @@ final class GameLibrary: ObservableObject {
upsert(game)
}
+ /// A mod switched on or off for one game.
+ func setMod(_ name: String, on: Bool, for id: UUID) {
+ guard var game = games.first(where: { $0.id == id }) else { return }
+ game.mods.removeAll { $0 == name }
+ if on { game.mods.append(name) }
+ upsert(game)
+ }
+
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.swift
index 6abc5d6c..ed9b5c90 100644
--- a/frontend/Sources/NSPortBuilder/Localization.swift
+++ b/frontend/Sources/NSPortBuilder/Localization.swift
@@ -445,6 +445,15 @@ enum L10n {
"launch.advancedCount": ("%ld 项", "%ld settings"),
"launch.scaleOfDocked": ("底座模式 %2$@ 的 %1$ld%%", "%ld%% of %@ docked"),
"launch.scaleOfHandheld": ("掌机模式 %2$@ 的 %1$ld%%", "%ld%% of %@ handheld"),
+ "launch.mods": ("模组", "Mods"),
+ "launch.modsNone": ("还没有模组", "No mods yet"),
+ "launch.modsHow": ("把每个模组放进模组文件夹中自己的文件夹(打开模组文件夹)。修改游戏代码的模组(exefs)不受支持。", "Put each mod in a folder of its own in the mods folder (Open mods folder). Mods that change the game’s code (exefs) are not supported."),
+ "launch.modCode": ("修改游戏代码(exefs),不受支持", "Changes the game’s code (exefs): not supported"),
+ "launch.modsRefresh": ("刷新", "Refresh"),
+ "launch.modsOpen": ("打开模组文件夹", "Open mods folder"),
+ "launch.savesShow": ("显示存档", "Show saves"),
+ "launch.modsNote": ("模组会改变游戏读取的文件。开关模组前请先备份存档:用模组存的档,去掉模组后可能无法读取。", "A mod changes the files the game reads. Back up the saves before switching a mod on or off: a save made with a mod may not load without it."),
+ "launch.modsNoteOrder": ("模组会改变游戏读取的文件。开关模组前请先备份存档:用模组存的档,去掉模组后可能无法读取。两个模组替换同一个文件时,列表中靠上的生效。", "A mod changes the files the game reads. Back up the saves before switching a mod on or off: a save made with a mod may not load without it. Where two mods replace the same file, the one higher in the list wins."),
"pad.play": ("开始游戏", "Play"),
"pad.options": ("启动选项", "Options"),
"pad.back": ("返回", "Back"),
diff --git a/frontend/Tests/NSPortBuilderTests/LaunchOptionsTests.swift b/frontend/Tests/NSPortBuilderTests/LaunchOptionsTests.swift
index af85ec68..7823be3f 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: Display mode, the basic / advanced split and the render scale in pixels.
+/// Launch options beyond the app's own list: Display mode, the basic / advanced split, the render scale in pixels, and mods.
final class LaunchOptionsTests: XCTestCase {
private var temporary: URL!
@@ -58,4 +58,23 @@ final class LaunchOptionsTests: XCTestCase {
"without render_base the row stays in percent")
}
+ func testModsAreFoundInTheirLayoutsAndPassedInListOrder() throws {
+ var game = LibraryGame(titleID: "01007EF00011E000", name: "Zelda")
+ let folder = GameMod.folder(for: game, library: temporary.path)
+ let fm = FileManager.default
+ for path in ["B Plain/Actor/x.bin", "A Romfs/romfs/Actor/y.bin", "C Atmosphere/atmosphere/contents/01007EF00011E000/romfs/z.bin", "D Code/exefs/main.npdm"] {
+ let file = folder.appendingPathComponent(path)
+ try fm.createDirectory(at: file.deletingLastPathComponent(), withIntermediateDirectories: true)
+ try Data([1]).write(to: file)
+ }
+ let mods = GameMod.list(in: folder, titleID: game.titleID)
+ XCTAssertEqual(mods.map(\.name), ["A Romfs", "B Plain", "C Atmosphere", "D Code"])
+ XCTAssertEqual(mods.map(\.usable), [true, true, true, false])
+ XCTAssertEqual(game.modEnvironment(mods), [:])
+ game.mods = ["C Atmosphere", "D Code", "A Romfs"]
+ XCTAssertEqual(game.modEnvironment(mods)["DM_ROMFS_OVERLAY"],
+ [folder.appendingPathComponent("A Romfs/romfs").path,
+ folder.appendingPathComponent("C Atmosphere/atmosphere/contents/01007EF00011E000/romfs").path].joined(separator: ":"),
+ "the list's order (higher wins), and a code-only mod left out")
+ }
}