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
The shell settings page works, and a gear opens it in every library layout
v0lumehi4c164da2ffe6
diff --git a/frontend-ios/Sources/ShellDemo/ShellDemoApp.swift b/frontend-ios/Sources/ShellDemo/ShellDemoApp.swiftindex 5a8f195e..4cecb900 100644--- a/frontend-ios/Sources/ShellDemo/ShellDemoApp.swift+++ b/frontend-ios/Sources/ShellDemo/ShellDemoApp.swift@@ -82,6 +82,7 @@ struct DemoScreen: View {actions: actions, input: input, initialSelection: initialSelection,initialDetailOpen: scenario == "settings",initialControllersOpen: scenario.hasPrefix("controllers"),+ initialShellSettingsOpen: scenario == "shell-settings",initialFocusVisible: scenario == "focus")}@@ -152,7 +153,9 @@ struct DemoScreen: View {}}, onShowLog: { _ in notice = demoText("Show log requested. The host supplies the log.") },onAppUpdate: { notice = demoText("App update requested. The host supplies update instructions.") },- onBack: { notice = demoText("Back requested.") })+ onBack: { notice = demoText("Back requested.") },+ onPickShellData: { notice = demoText("Choose game data requested. The host supplies the picker.") },+ onPickShellCloud: { notice = demoText("Choose cloud folder requested. The host supplies the picker.") })}}diff --git a/frontend-ios/Sources/ShellHost/EngineLaunchPlan.swift b/frontend-ios/Sources/ShellHost/EngineLaunchPlan.swiftindex 2a4f9635..b2373889 100644--- a/frontend-ios/Sources/ShellHost/EngineLaunchPlan.swift+++ b/frontend-ios/Sources/ShellHost/EngineLaunchPlan.swift@@ -20,7 +20,7 @@ public struct EngineLaunchPlan: Equatable, Sendable {/// The save and temp folders.public var foldersToCreate: [URL]- public static func make(game: LaunchableGame, appResources: URL, documents: URL, envFileText: String?, shellPerformanceHUD: Bool? = nil,+ public static func make(game: LaunchableGame, appResources: URL, documents: URL, envFileText: String?,fileManager fm: FileManager = .default) -> EngineLaunchPlan {let manifest = game.manifest, fw = game.frameworkURL, gdir = game.appFolderfunc isDirectory(_ url: URL) -> Bool {@@ -48,8 +48,6 @@ public struct EngineLaunchPlan: Equatable, Sendable {// The shell already showed its own settings, the per-game launcher screen stays out of the way.env["DM_LAUNCHER"] = "0"for (key, value) in game.environment { env[key] = value }- // The shell-level default applies only when the game's own settings left the HUD unset (#398's settings page).- if env["DM_METAL_HUD"] == nil, let hud = shellPerformanceHUD { env["DM_METAL_HUD"] = hud ? "1" : "0" }var fromFile: [String] = []for (key, value) in parseEnvFile(envFileText ?? "") where env[key] == nil {diff --git a/frontend-ios/Sources/ShellHost/GameCatalogue.swift b/frontend-ios/Sources/ShellHost/GameCatalogue.swiftindex c35bb819..8c195486 100644--- a/frontend-ios/Sources/ShellHost/GameCatalogue.swift+++ b/frontend-ios/Sources/ShellHost/GameCatalogue.swift@@ -173,8 +173,10 @@ public enum GameCatalogue {public enum DataSource: Equatable, Sendable {/// The app's own `Documents/games/<title ID>/`.case app- /// A folder the player picked, through a bookmark.+ /// A folder the player picked for this game, through a bookmark.case picked+ /// The data folder the player picked once for every game, in the shell's settings.+ case shell}public struct DataResolution: Equatable, Sendable {@@ -201,7 +203,7 @@ public enum DataLocator {}switch global { // the shell-level data folder: the game's own bookmark wins, this backs it upcase .url(let url):- if let dir = holder(of: url, manifest: manifest, fm) { result.url = dir; result.source = .picked; return result }+ if let dir = holder(of: url, manifest: manifest, fm) { result.url = dir; result.source = .shell; return result }case .stale, .none: break}if let dir = holder(of: appFolder, manifest: manifest, fm) { result.url = dir; result.source = .app }diff --git a/frontend-ios/Sources/ShellHost/GameSettingsStore.swift b/frontend-ios/Sources/ShellHost/GameSettingsStore.swiftindex 558efaa0..099e7996 100644--- a/frontend-ios/Sources/ShellHost/GameSettingsStore.swift+++ b/frontend-ios/Sources/ShellHost/GameSettingsStore.swift@@ -13,30 +13,42 @@ public enum GameDefaults {/// A game's saved choices over its `launcher.json`. As in dm/ios/Sources/LauncherSettings.swift, only a choice that/// differs from the tested default is stored (a setting left alone follows a later build's defaults), a saved value-/// the game no longer offers reads as the default, and reset forgets every saved choice.+/// the game no longer offers reads as the default, and reset forgets every saved choice. A setting the player left alone+/// takes the shell's default for its variable (`shell`) when the game offers that value: game > shell > built-in.public struct GameSettingsStore {public let profile: LauncherProfileprivate let defaults: UserDefaults+ private let shell: [String: String]- public init(profile: LauncherProfile, defaults: UserDefaults) {+ public init(profile: LauncherProfile, defaults: UserDefaults, shell: [String: String] = [:]) {self.profile = profileself.defaults = defaults+ self.shell = shell}/// The saved value as a string, as launcher.c reads it (not `string(forKey:)`, which turns a number into one).- public func value(of setting: LauncherSetting) -> String {- let saved = defaults.object(forKey: setting.defaultsKey) as? String- return saved.flatMap { setting.accepts($0) ? $0 : nil } ?? setting.def+ private func saved(_ setting: LauncherSetting) -> String? {+ (defaults.object(forKey: setting.defaultsKey) as? String).flatMap { setting.accepts($0) ? $0 : nil }}+ /// What the game does without a saved choice: the shell's default when the game offers it, else its own.+ private func fallback(_ setting: LauncherSetting) -> String {+ shell[setting.env].flatMap { setting.accepts($0) ? $0 : nil } ?? setting.def+ }++ public func value(of setting: LauncherSetting) -> String { saved(setting) ?? fallback(setting) }+public func values() -> [String: String] {Dictionary(uniqueKeysWithValues: profile.settings.map { ($0.env, value(of: $0)) })}- /// Saves a choice. False when the game has no such setting or does not offer the value.+ /// Saves a choice. False when the game has no such setting or does not offer the value. A choice equal to what the+ /// game does anyway is forgotten, so it follows a later default. The game's own default is still saved when the shell+ /// asks for something else, or the shell's value would win again.@discardableResult public func set(_ env: String, to value: String) -> Bool {guard let setting = profile.settings.first(where: { $0.env == env }), setting.accepts(value) else { return false }- if setting.isDefault(value) { defaults.removeObject(forKey: setting.defaultsKey) } else { defaults.set(value, forKey: setting.defaultsKey) }+ let follows = shell[setting.env].flatMap { setting.accepts($0) ? $0 : nil }.map { $0 == value } ?? setting.isDefault(value)+ if follows { defaults.removeObject(forKey: setting.defaultsKey) } else { defaults.set(value, forKey: setting.defaultsKey) }return true}@@ -46,7 +58,7 @@ public struct GameSettingsStore {}public var hasModifiedSettings: Bool {- profile.settings.contains { !$0.isDefault(value(of: $0)) }+ profile.settings.contains { setting in saved(setting).map { !setting.isDefault($0) } ?? false }}}diff --git a/frontend-ios/Sources/ShellHost/HostText.swift b/frontend-ios/Sources/ShellHost/HostText.swiftindex 59bf6f91..13dfc6cc 100644--- a/frontend-ios/Sources/ShellHost/HostText.swift+++ b/frontend-ios/Sources/ShellHost/HostText.swift@@ -3,7 +3,7 @@ import ShellUI/// The host layer's own words, from `Resources/Localizable.xcstrings` (English source, like ShellUI).func hostText(_ key: String.LocalizationValue) -> String {- String(localized: key, bundle: .module)+ String(localized: key, bundle: ShellLanguage.bundle(.module))}/// What is wrong with a bundle that cannot run at all. Each cause has one plain sentence for the player.diff --git a/frontend-ios/Sources/ShellHost/Resources/Localizable.xcstrings b/frontend-ios/Sources/ShellHost/Resources/Localizable.xcstringsindex ba188482..964a99f4 100644--- a/frontend-ios/Sources/ShellHost/Resources/Localizable.xcstrings+++ b/frontend-ios/Sources/ShellHost/Resources/Localizable.xcstrings@@ -17,6 +17,22 @@}}},+ "%@ (from Settings)": {+ "localizations": {+ "en": {+ "stringUnit": {+ "state": "translated",+ "value": "%@ (from Settings)"+ }+ },+ "zh-Hans": {+ "stringUnit": {+ "state": "translated",+ "value": "%@(来自设置)"+ }+ }+ }+ },"%@ appears twice in launcher.json.": {"localizations": {"en": {diff --git a/frontend-ios/Sources/ShellHost/ShellHostModel.swift b/frontend-ios/Sources/ShellHost/ShellHostModel.swiftindex d58b2472..97776ea0 100644--- a/frontend-ios/Sources/ShellHost/ShellHostModel.swift+++ b/frontend-ios/Sources/ShellHost/ShellHostModel.swift@@ -65,12 +65,44 @@ public struct ShellHostConfig: Sendable {@ObservationIgnored private var dataStores: [String: BookmarkStore] = [:]@ObservationIgnored private var cloudStores: [String: BookmarkStore] = [:]@ObservationIgnored private var artwork: [URL: Artwork] = [:]-- public init(config: ShellHostConfig, launcher: any GameLauncher = StubGameLauncher(), picker: any FolderPicker = NoFolderPicker()) {+ /// The shell-level settings every game falls back to (game > shell > built-in).+ @ObservationIgnored public let shellSettings: ShellSettingsStore+ @ObservationIgnored private let shellData: BookmarkStore+ @ObservationIgnored private let shellCloud: BookmarkStore+ @ObservationIgnored private var shellChoices: [String]+ @ObservationIgnored nonisolated(unsafe) private var defaultsObserver: (any NSObjectProtocol)?++ public init(config: ShellHostConfig, launcher: any GameLauncher = StubGameLauncher(), picker: any FolderPicker = NoFolderPicker(),+ shellSettings: ShellSettingsStore = .current) {self.config = configself.launcher = launcherself.picker = picker+ self.shellSettings = shellSettings+ shellData = BookmarkStore(defaults: shellSettings.defaults, key: ShellSettingsStore.dataFolderKey)+ shellCloud = BookmarkStore(defaults: shellSettings.defaults, key: ShellSettingsStore.cloudSavesKey)+ shellChoices = Self.choices(of: shellSettings)reload()+ defaultsObserver = NotificationCenter.default.addObserver(forName: UserDefaults.didChangeNotification, object: nil, queue: .main) { [weak self] _ in+ MainActor.assumeIsolated { self?.defaultsDidChange() }+ }+ }++ deinit { defaultsObserver.map(NotificationCenter.default.removeObserver) }++ /// What the details show of the shell settings besides the folders: the interface language and the overlay default.+ private static func choices(of settings: ShellSettingsStore) -> [String] {+ [settings.language, settings.gameDefaults.sorted { $0.key < $1.key }.map { "\($0.key)=\($0.value)" }.joined(separator: ",")]+ }++ /// Builds the details again, in the same order. The texts the host writes follow the interface language, so a+ /// change of it comes through here, and so does a change of a shell folder or of the performance overlay.+ public func refreshAll() {+ shellChoices = Self.choices(of: shellSettings)+ details = entries.map(detail(for:))+ }++ private func defaultsDidChange() {+ if Self.choices(of: shellSettings) != shellChoices { refreshAll() }}// MARK: Catalogue@@ -112,27 +144,10 @@ public struct ShellHostConfig: Sendable {return s}- /// The shell-level settings every game falls back to (ShellSettingsStore: game > shell > built-in).- public private(set) var shellSettings = ShellSettingsStore()-- /// The shell-level data folder as a bookmark resolution, for the locator's global source.- private func globalData() -> BookmarkResolution {- guard let data = shellSettings.dataBookmark else { return .none }- // BookmarkStore reads through UserDefaults; a volatile in-memory store carrying just the global bookmark- // keeps that contract. The resolution is cheap, so no caching is needed.- let name = "shell-global-data"- UserDefaults().removePersistentDomain(forName: name) // start clean every call- let suite = UserDefaults(suiteName: name) ?? .standard- suite.set(data, forKey: BookmarkStore.gameDataKey)- let resolution = BookmarkStore(defaults: suite, key: BookmarkStore.gameDataKey).resolve()- UserDefaults().removePersistentDomain(forName: name)- return resolution- }-private func data(for entry: CatalogueEntry) -> DataResolution {guard let manifest = entry.manifest, entry.problem == nil else { return .missing }return DataLocator.locate(manifest: manifest, picked: dataStore(entry.id).resolve(), appFolder: appFolder(for: entry.id),- global: globalData())+ global: shellData.resolve())}private func image(_ url: URL?) -> Artwork? {@@ -153,24 +168,28 @@ public struct ShellHostConfig: Sendable {guard let profile = entry.profile, entry.problem == nil else {return GameDetail(game: tile, dataNote: dataNote(data, found: false))}- let store = GameSettingsStore(profile: profile, defaults: config.defaults(entry.id))+ let store = GameSettingsStore(profile: profile, defaults: config.defaults(entry.id), shell: shellSettings.gameDefaults)var cloud: String?var cloudNote = ""+ var cloudFromShell = falseswitch cloudStore(entry.id).resolve() {case .url(let url): cloud = url.lastPathComponentcase .stale: cloudNote = hostText("The folder you chose before is no longer readable. Please choose it again.")- case .none: break+ case .none:+ if case .url(let url) = shellCloud.resolve() { cloud = url.lastPathComponent; cloudFromShell = true }}return GameDetail(game: tile, sections: SettingsPresenter.sections(profile: profile, values: store.values()),dataSource: dataSource(data), dataNote: dataNote(data, found: data.found),- cloudSaves: cloud, cloudNote: cloudNote, dlc: dlc(data), hasModifiedSettings: store.hasModifiedSettings)+ cloudSaves: cloud, cloudNote: cloudNote, dlc: dlc(data), hasModifiedSettings: store.hasModifiedSettings,+ dataFromShell: data.source == .shell, cloudFromShell: cloudFromShell)}private func dataSource(_ data: DataResolution) -> String {switch data.source {case .app: hostText("This app's folder")case .picked: data.url?.lastPathComponent ?? ""+ case .shell: hostText("\(data.url?.lastPathComponent ?? "") (from Settings)")case nil: ""}}@@ -203,12 +222,14 @@ public struct ShellHostConfig: Sendable {onDisableCloudSaves: { [weak self] id in self?.disableCloudSaves(id) },onResetDefaults: { [weak self] id in self?.resetDefaults(id) },onShowLog: { [weak self] id in self?.showLog(id) },- onAppUpdate: { [weak self] in self?.appUpdate() })+ onAppUpdate: { [weak self] in self?.appUpdate() },+ onPickShellData: { [weak self] in self.map { model in Task { await model.pickShellDataNow() } } },+ onPickShellCloud: { [weak self] in self.map { model in Task { await model.pickShellCloudNow() } } })}public func change(_ id: String, setting: String, value: String) {guard let profile = entry(id)?.profile else { return }- GameSettingsStore(profile: profile, defaults: config.defaults(id)).set(setting, to: value)+ GameSettingsStore(profile: profile, defaults: config.defaults(id), shell: shellSettings.gameDefaults).set(setting, to: value)refresh(id)}@@ -252,6 +273,20 @@ public struct ShellHostConfig: Sendable {refresh(id)}+ func pickShellDataNow() async {+ guard let url = await picker.pickFolder() else { return }+ guard shellData.store(url) else { notice = hostText("That folder could not be remembered. Try a different one."); return }+ shellSettings.storeDataFolderName(url.lastPathComponent)+ refreshAll()+ }++ func pickShellCloudNow() async {+ guard let url = await picker.pickFolder() else { return }+ guard shellCloud.store(url) else { notice = hostText("That folder could not be remembered. Try a different one."); return }+ shellSettings.storeCloudSavesFolderName(url.lastPathComponent)+ refreshAll()+ }+public func disableCloudSaves(_ id: String) {cloudStore(id).clear()refresh(id)@@ -281,17 +316,29 @@ public struct ShellHostConfig: Sendable {guard let entry = entry(id), let manifest = entry.manifest, let profile = entry.profile, let framework = entry.frameworkURL,details.first(where: { $0.id == id })?.game.state == .playable, let dataURL = data(for: entry).url else { return }var cloud: URL?- if case .url(let url) = cloudStore(id).resolve() { cloud = url }+ switch cloudStore(id).resolve() {+ case .url(let url): cloud = url+ case .stale: break+ case .none: if case .url(let url) = shellCloud.resolve() { cloud = url }+ }// Remembered when Play is triggered, even if the launcher then fails (the stub). The order changes at the next load.LastPlayedStore(defaults: config.defaults(id)).record(config.now())refresh(id)let game = LaunchableGame(titleID: id, name: entry.title, manifest: manifest, directory: entry.directory, frameworkURL: framework, dataURL: dataURL,- appFolder: appFolder(for: id), environment: GameSettingsStore(profile: profile, defaults: config.defaults(id)).values(), cloudSavesURL: cloud)+ appFolder: appFolder(for: id), environment: launchEnvironment(profile: profile, id: id), cloudSavesURL: cloud)do { try await launcher.launch(game) }catch { notice = error.localizedDescription }}+ /// A game's values for the engine: its own choices, then the shell's defaults. A game whose settings list has no+ /// performance overlay row still gets the shell's choice.+ func launchEnvironment(profile: LauncherProfile, id: String) -> [String: String] {+ var env = GameSettingsStore(profile: profile, defaults: config.defaults(id), shell: shellSettings.gameDefaults).values()+ for (key, value) in shellSettings.gameDefaults where env[key] == nil { env[key] = value }+ return env+ }+// MARK: Controllers/// Starts reading GameController: the connected controllers become `controllers`, their buttons `input`.diff --git a/frontend-ios/Sources/ShellUI/CoverFlowView.swift b/frontend-ios/Sources/ShellUI/CoverFlowView.swiftindex 8e5f3784..8651917b 100644--- a/frontend-ios/Sources/ShellUI/CoverFlowView.swift+++ b/frontend-ios/Sources/ShellUI/CoverFlowView.swift@@ -15,6 +15,7 @@ struct CoverFlowView: View, Equatable {let primary: (GameDetail) -> Voidlet openSettings: () -> Voidlet openControllers: () -> Void+ let openShellSettings: () -> Void@State private var centredID: String?/// How far the carousel is scrolled: 0 with the first card in the middle.@State private var scrolled: CGFloat = 0@@ -106,6 +107,7 @@ struct CoverFlowView: View, Equatable {.accessibilityIdentifier("settings.open").shellTarget("lib.settings", radius: 22, action: openSettings)ControllerChip(count: controllers, action: openControllers)+ ShellSettingsChip(action: openShellSettings)}// On a phone on its side the hints share the row. At the largest sizes they would wrap into a tall block and the// title and chips, centred in it, would sink away from the top edge, so the row stops growing at xxLarge, as the@@ -393,3 +395,15 @@ struct ControllerChip: View {.shellTarget("lib.controllers", radius: 22, action: action)}}++/// The gear at the top-right corner, which opens the shell's own settings.+struct ShellSettingsChip: View {+ let action: () -> Void+ var body: some View {+ Button(action: action) { Image(systemName: "gearshape").frame(minWidth: 18) }+ .buttonStyle(ChipButtonStyle())+ .accessibilityLabel(ShellStrings.text("Settings"))+ .accessibilityIdentifier("shellSettings.open")+ .shellTarget("lib.shellSettings", radius: 22, action: action)+ }+}diff --git a/frontend-ios/Sources/ShellUI/GameDetailView.swift b/frontend-ios/Sources/ShellUI/GameDetailView.swiftindex 0f522ba0..aa75b0f0 100644--- a/frontend-ios/Sources/ShellUI/GameDetailView.swift+++ b/frontend-ios/Sources/ShellUI/GameDetailView.swift@@ -34,7 +34,7 @@ public struct GameDetailView: View {Button(ShellStrings.text("Choose…")) { actions.onPickGameData(detail.id) }.buttonStyle(ShellButtonStyle(fills: true)).accessibilityLabel(ShellStrings.text("Choose game data…")).shellTarget("set.data") { actions.onPickGameData(detail.id) }- if !detail.dataSource.isEmpty {+ if !detail.dataSource.isEmpty && !detail.dataFromShell {Button(ShellStrings.text("Use app data")) { actions.onUseAppData(detail.id) }.buttonStyle(ShellButtonStyle(fills: true)).shellTarget("set.appdata") { actions.onUseAppData(detail.id) }}@@ -49,7 +49,7 @@ public struct GameDetailView: View {note: detail.cloudNote.isEmpty ? ShellStrings.text("Choose the same iCloud Drive folder you use on your Mac.") : detail.cloudNote) {Button(ShellStrings.text("Choose folder…")) { actions.onPickCloudSaves(detail.id) }.buttonStyle(ShellButtonStyle(fills: true)).shellTarget("set.cloud") { actions.onPickCloudSaves(detail.id) }- if detail.cloudSaves != nil {+ if detail.cloudSaves != nil && !detail.cloudFromShell {Button(ShellStrings.text("Turn off")) { actions.onDisableCloudSaves(detail.id) }.buttonStyle(ShellButtonStyle(fills: true)).accessibilityLabel(ShellStrings.text("Turn off cloud saves")).shellTarget("set.cloud.off") { actions.onDisableCloudSaves(detail.id) }@@ -103,9 +103,22 @@ public struct GameDetailView: View {private var divider: some View { Rectangle().fill(.white.opacity(0.06)).frame(height: 1) }private func group<Content: View>(_ title: String, @ViewBuilder content: () -> Content) -> some View {+ SettingsGroup(title: title, content: content)+ }+}++/// A titled card of rows, for the game settings and the shell settings alike.+struct SettingsGroup<Content: View>: View {+ let title: String+ private let content: Content+ init(title: String, @ViewBuilder content: () -> Content) {+ self.title = title+ self.content = content()+ }+ var body: some View {VStack(alignment: .leading, spacing: 12) {SectionHeading(title: title)- VStack(alignment: .leading, spacing: 14) { content() }+ VStack(alignment: .leading, spacing: 14) { content }.frame(maxWidth: .infinity, alignment: .leading).shellCard()}@@ -113,7 +126,7 @@ public struct GameDetailView: View {}/// Where something comes from (game data, a cloud folder) and the buttons that change it.-private struct SourceRow<Buttons: View>: View {+struct SourceRow<Buttons: View>: View {let symbol: Stringlet title: Stringlet note: String@@ -138,10 +151,12 @@ private struct SourceRow<Buttons: View>: View {}}-private struct SettingControl: View, Equatable {+struct SettingControl: View, Equatable {/// Part of the comparison: two games can have identical rows, and the row must report to its own game.let gameID: Stringlet row: SettingRow+ /// The focus ids of the row's controls start with this, so a panel can tell its own from the library's.+ var targetPrefix = "set.row."let change: (String) -> Voidnonisolated static func == (lhs: Self, rhs: Self) -> Bool { lhs.gameID == rhs.gameID && lhs.row == rhs.row }@Environment(\.dynamicTypeSize) private var typeSize@@ -154,7 +169,7 @@ private struct SettingControl: View, Equatable {case .toggle(let on, let off):Toggle(isOn: Binding(get: { row.value == on }, set: { change($0 ? on : off) })) { label }.toggleStyle(CreamToggleStyle())- .shellTarget("set.row.\(row.id)", enabled: row.enabled) { change(row.value == on ? off : on) }+ .shellTarget("\(targetPrefix)\(row.id)", enabled: row.enabled) { change(row.value == on ? off : on) }case .choice(let options):let labels = options.map(\.label)let scale = ChoicePresentation.textScale(typeSize)@@ -212,7 +227,7 @@ private struct SettingControl: View, Equatable {.buttonStyle(.plain).accessibilityLabel(row.label + ", " + option.label).accessibilityAddTraits(chosen ? .isSelected : [])- .shellTarget("set.row.\(row.id).\(option.id)", enabled: row.enabled, radius: 8) { change(option.id) }+ .shellTarget("\(targetPrefix)\(row.id).\(option.id)", enabled: row.enabled, radius: 8) { change(option.id) }}}}@@ -226,7 +241,7 @@ private struct SettingControl: View, Equatable {ChoiceValueRow(row: row, valueLabel: options.first { $0.id == row.value }?.label ?? row.value) {pickChoice?(ChoiceRequest(gameID: gameID, row: row))}- .shellTarget("set.row.\(row.id)", enabled: row.enabled, radius: 11) { pickChoice?(ChoiceRequest(gameID: gameID, row: row)) }+ .shellTarget("\(targetPrefix)\(row.id)", enabled: row.enabled, radius: 11) { pickChoice?(ChoiceRequest(gameID: gameID, row: row)) }}private func rangeButton(_ symbol: String, min: Double, max: Double, delta: Double) -> some View {let action = { change(String(Swift.min(max, Swift.max(min, (Double(row.value) ?? min) + delta)))) }@@ -236,7 +251,7 @@ private struct SettingControl: View, Equatable {.buttonStyle(.plain).background(.white.opacity(0.055), in: Circle()).overlay(Circle().strokeBorder(.white.opacity(0.10))).accessibilityLabel(ShellStrings.text(symbol == "minus" ? "Decrease" : "Increase") + " " + row.label)- .shellTarget("set.row.\(row.id).\(symbol)", enabled: row.enabled, radius: 22, action: action)+ .shellTarget("\(targetPrefix)\(row.id).\(symbol)", enabled: row.enabled, radius: 22, action: action)}}diff --git a/frontend-ios/Sources/ShellUI/LibraryView.swift b/frontend-ios/Sources/ShellUI/LibraryView.swiftindex 280410df..4d88a6c5 100644--- a/frontend-ios/Sources/ShellUI/LibraryView.swift+++ b/frontend-ios/Sources/ShellUI/LibraryView.swift@@ -35,7 +35,9 @@ public struct LibraryView: View {public var input: ShellInput?@State private var selectedID: String?@State private var settingsOpen: Bool- @State private var shellSettingsOpen = false+ @State private var shellSettingsOpen: Bool+ /// The interface language in force. A change rebuilds the views, so every text is read again in the new language.+ @State private var shellLanguage = ShellSettingsStore.current.language@State private var controllersOpen: Bool/// The game whose How to fix or How to update explanation is open.@State private var helpGameID: String?@@ -60,7 +62,7 @@ public struct LibraryView: View {public init(games: [GameDetail], controllers: [ControllerInfo] = [], actions: ShellActions = ShellActions(),input: ShellInput? = nil, initialSelection: String? = nil, initialDetailOpen: Bool = false,- initialControllersOpen: Bool = false, initialFocusVisible: Bool = false) {+ initialControllersOpen: Bool = false, initialShellSettingsOpen: Bool = false, initialFocusVisible: Bool = false) {self.games = gamesself.controllers = controllersself.actions = actions@@ -69,6 +71,7 @@ public struct LibraryView: View {_selectedID = State(initialValue: first)_settingsOpen = State(initialValue: initialDetailOpen)_controllersOpen = State(initialValue: initialControllersOpen)+ _shellSettingsOpen = State(initialValue: initialShellSettingsOpen)_focus = State(initialValue: FocusAppearance(id: initialFocusVisible ? "lib.tile.\(first ?? "")" : nil, visible: initialFocusVisible))_touchMode = State(initialValue: !initialFocusVisible)}@@ -93,10 +96,8 @@ public struct LibraryView: View {EmptyLibraryView().overlay(alignment: .topTrailing) {HStack(spacing: 10) {- Button { shellSettingsOpen = true } label: {- Image(systemName: "gearshape")- }.buttonStyle(ChipButtonStyle()).accessibilityLabel(ShellStrings.text("Settings"))ControllerChip(count: controllers.count, action: openControllers)+ ShellSettingsChip(action: openShellSettings)}.padding(.top, 6).padding(.trailing, 16)}} else if let selected {@@ -169,29 +170,45 @@ public struct LibraryView: View {.accessibilityAddTraits(.isModal).transition(.move(edge: .trailing).combined(with: .opacity))}+ if shellSettingsOpen {+ Color.black.opacity(0.55 * (1 - min(1, edgeDrag / min(width, 520)))).ignoresSafeArea().accessibilityHidden(true)+ .onTapGesture { back() }+ ShellSettingsView(actions: actions, onClose: closeShellSettings)+ .frame(width: min(width, 520))+ .frame(maxHeight: .infinity)+ .background { ShellPalette.background.ignoresSafeArea() }+ .overlay(alignment: .leading) { Rectangle().fill(ShellPalette.hairline).frame(width: 1).ignoresSafeArea() }+ .offset(x: edgeDrag)+ .frame(maxWidth: .infinity, alignment: .trailing)+ .accessibilityAddTraits(.isModal)+ .transition(.move(edge: .trailing).combined(with: .opacity))+ }}.transformPreference(FocusTargets.self) { values invalues = values.filter { target inif controllersOpen { return target.id.hasPrefix("ctl.") }+ if shellSettingsOpen { return target.id.hasPrefix("shs.") }if helpGameID != nil { return target.id.hasPrefix("help.") }if choice != nil { return target.id.hasPrefix("pick.") }- return !target.id.hasPrefix("ctl.") && !target.id.hasPrefix("help.") && !target.id.hasPrefix("pick.")+ return !target.id.hasPrefix("ctl.") && !target.id.hasPrefix("help.") && !target.id.hasPrefix("pick.") && !target.id.hasPrefix("shs.")}}.coordinateSpace(name: "shell").background {- EdgeSwipeBack(enabled: (settingsOpen || controllersOpen) && choice == nil && helpGameID == nil,+ EdgeSwipeBack(enabled: (settingsOpen || controllersOpen || shellSettingsOpen) && choice == nil && helpGameID == nil,changed: { edgeDrag = $0 },- ended: { finishEdgeSwipe(travel: $0, velocity: $1, span: controllersOpen ? min(width, 520) : pane) },+ ended: { finishEdgeSwipe(travel: $0, velocity: $1, span: controllersOpen || shellSettingsOpen ? min(width, 520) : pane) },cancelled: cancelEdgeSwipe)}.onPreferenceChange(FocusTargets.self) { all in targets.values = all.filter { $0.frame.width > 1 } }.onAppear { self.layout = layout }.onChange(of: layout) { _, new in self.layout = new }}+ .id(shellLanguage).animation(reduceMotion ? nil : .smooth(duration: 0.35), value: layout).animation(reduceMotion ? nil : .smooth(duration: 0.3), value: settingsOpen).animation(reduceMotion ? nil : .smooth(duration: 0.3), value: controllersOpen)+ .animation(reduceMotion ? nil : .smooth(duration: 0.3), value: shellSettingsOpen).animation(reduceMotion ? nil : .smooth(duration: 0.25), value: helpGameID).animation(reduceMotion ? nil : .smooth(duration: 0.25), value: choice).environment(\.shellPickChoice, { request in openChoice(request) })@@ -217,23 +234,24 @@ public struct LibraryView: View {.onChange(of: games.map(\.id)) { _, ids inif !ids.contains(selectedID ?? "") { selectedID = ids.first; settingsOpen = false }}- .sheet(isPresented: $shellSettingsOpen) {- ShellSettingsView(store: ShellSettingsStore()) { key in- if key == "data" { actions.onPickShellData() } else { actions.onPickShellCloud() }- }+ .onReceive(NotificationCenter.default.publisher(for: UserDefaults.didChangeNotification)) { _ in+ let language = ShellSettingsStore.current.language+ if language != shellLanguage { shellLanguage = language }}}@ViewBuilder private func library(_ selected: GameDetail, layout: ShellLayout, size: CGSize, insets: EdgeInsets) -> some View {if layout.isCoverFlow {CoverFlowView(games: games, selected: selected, controllers: controllers.count, showsHints: !touchMode, screenInsets: insets,- select: select, primary: primary, openSettings: openSettings, openControllers: openControllers)+ select: select, primary: primary, openSettings: openSettings, openControllers: openControllers,+ openShellSettings: openShellSettings).equatable().transition(.opacity)} else {PortraitLibrary(games: games, selected: selected, wide: layout == .grid, size: size, topInset: insets.top, bottomInset: insets.bottom,controllers: controllers.count, select: select, primary: primary,- openSettings: openSettings, openControllers: openControllers, position: $libraryPosition)+ openSettings: openSettings, openControllers: openControllers, openShellSettings: openShellSettings,+ position: $libraryPosition).equatable().transition(.opacity)}@@ -328,6 +346,7 @@ public struct LibraryView: View {withAnimation(reduceMotion ? nil : .smooth(duration: 0.25)) { edgeDrag = 0 }}private func openSettings() {+ guard !shellSettingsOpen else { return }noteTouch()settingsOpen = truefocus.id = "set.back"@@ -336,7 +355,9 @@ public struct LibraryView: View {settingsOpen = falsefocus.id = "lib.settings"}- private func openControllers() { noteTouch(); controllersOpen = true; focus.id = "ctl.close" }+ private func openControllers() { guard !shellSettingsOpen else { return }; noteTouch(); controllersOpen = true; focus.id = "ctl.close" }+ private func openShellSettings() { noteTouch(); shellSettingsOpen = true; focus.id = "shs.close" }+ private func closeShellSettings() { shellSettingsOpen = false; focus.id = "lib.shellSettings" }private func openHelp(_ id: String) { returnFocus = focus.id; helpGameID = id; focus.id = "help.done" }private func closeHelp() { helpGameID = nil; focus.id = returnFocus }private func openChoice(_ request: ChoiceRequest) {@@ -348,18 +369,22 @@ public struct LibraryView: View {private func closeChoice() {guard let request = choice else { return }choice = nil- focus.id = "set.row.\(request.row.id)"+ focus.id = (request.gameID == ShellSettingsRows.gameID ? ShellSettingsRows.targetPrefix : "set.row.") + request.row.id}private func pickChoice(_ value: String) {noteTouch()guard let request = choice else { return }- if value != request.row.value { actions.onChange(request.gameID, request.row.id, value) }+ if value != request.row.value {+ if request.gameID == ShellSettingsRows.gameID { ShellSettingsRows.apply(request.row.id, value: value, to: .current) }+ else { actions.onChange(request.gameID, request.row.id, value) }+ }closeChoice()}private func back() {if choice != nil { closeChoice() }else if helpGameID != nil { closeHelp() }else if controllersOpen { controllersOpen = false; focus.id = "lib.controllers" }+ else if shellSettingsOpen { closeShellSettings() }else if settingsOpen { closeSettings() }else { actions.onBack() }}@@ -401,6 +426,7 @@ public struct LibraryView: View {if let choice { return "pick.\(choice.row.value)" }if helpGameID != nil { return "help.done" }if controllersOpen { return "ctl.close" }+ if shellSettingsOpen { return "shs.close" }if settingsOpen { return "set.back" }return selected.map { "lib.tile.\($0.id)" } ?? "lib.controllers"}diff --git a/frontend-ios/Sources/ShellUI/PortraitLibrary.swift b/frontend-ios/Sources/ShellUI/PortraitLibrary.swiftindex 8a90d7e7..73d68ea6 100644--- a/frontend-ios/Sources/ShellUI/PortraitLibrary.swift+++ b/frontend-ios/Sources/ShellUI/PortraitLibrary.swift@@ -17,6 +17,7 @@ struct PortraitLibrary: View, Equatable {let primary: (GameDetail) -> Voidlet openSettings: () -> Voidlet openControllers: () -> Void+ let openShellSettings: () -> Void@Binding var position: ScrollPosition@State private var rowID: String?/// Set while the row itself chose the game, so it does not scroll under the finger.@@ -78,7 +79,10 @@ struct PortraitLibrary: View, Equatable {.ignoresSafeArea(edges: wide ? [.top, .bottom] : .top).safeAreaInset(edge: .bottom, spacing: 0) { if !wide { bottomBar } }.overlay(alignment: .topTrailing) {- ControllerChip(count: controllers, action: openControllers).padding(.top, 6).padding(.trailing, 16)+ HStack(spacing: 10) {+ ControllerChip(count: controllers, action: openControllers)+ ShellSettingsChip(action: openShellSettings)+ }.padding(.top, 6).padding(.trailing, 16)}.onChange(of: focus.id) { _, id inguard let id, id.hasPrefix("lib.tile.") || id.hasPrefix("lib.recent.") else { return }diff --git a/frontend-ios/Sources/ShellUI/Resources/Localizable.xcstrings b/frontend-ios/Sources/ShellUI/Resources/Localizable.xcstringsindex 7807ca09..d5b5a955 100644--- a/frontend-ios/Sources/ShellUI/Resources/Localizable.xcstrings+++ b/frontend-ios/Sources/ShellUI/Resources/Localizable.xcstrings@@ -49,6 +49,22 @@}}},+ "Applies to the whole app.": {+ "localizations": {+ "en": {+ "stringUnit": {+ "state": "translated",+ "value": "Applies to the whole app."+ }+ },+ "zh-Hans": {+ "stringUnit": {+ "state": "translated",+ "value": "对整个 App 生效。"+ }+ }+ }+ },"Back": {"localizations": {"en": {@@ -337,6 +353,22 @@}}},+ "Follow device": {+ "localizations": {+ "en": {+ "stringUnit": {+ "state": "translated",+ "value": "Follow device"+ }+ },+ "zh-Hans": {+ "stringUnit": {+ "state": "translated",+ "value": "跟随设备"+ }+ }+ }+ },"For a bug report": {"localizations": {"en": {@@ -385,6 +417,38 @@}}},+ "Games look for their data here. Each game can have a folder of its own.": {+ "localizations": {+ "en": {+ "stringUnit": {+ "state": "translated",+ "value": "Games look for their data here. Each game can have a folder of its own."+ }+ },+ "zh-Hans": {+ "stringUnit": {+ "state": "translated",+ "value": "游戏会在这里查找游戏数据。每个游戏也可以单独指定文件夹。"+ }+ }+ }+ },+ "Games without a folder of their own save here. Choose the same iCloud Drive folder you use on your Mac.": {+ "localizations": {+ "en": {+ "stringUnit": {+ "state": "translated",+ "value": "Games without a folder of their own save here. Choose the same iCloud Drive folder you use on your Mac."+ }+ },+ "zh-Hans": {+ "stringUnit": {+ "state": "translated",+ "value": "没有单独指定文件夹的游戏会把存档保存在这里。请选择与 Mac 相同的 iCloud Drive 文件夹。"+ }+ }+ }+ },"How to fix": {"localizations": {"en": {@@ -449,6 +513,38 @@}}},+ "Interface": {+ "localizations": {+ "en": {+ "stringUnit": {+ "state": "translated",+ "value": "Interface"+ }+ },+ "zh-Hans": {+ "stringUnit": {+ "state": "translated",+ "value": "界面"+ }+ }+ }+ },+ "Language": {+ "localizations": {+ "en": {+ "stringUnit": {+ "state": "translated",+ "value": "Language"+ }+ },+ "zh-Hans": {+ "stringUnit": {+ "state": "translated",+ "value": "语言"+ }+ }+ }+ },"Library": {"localizations": {"en": {@@ -561,6 +657,22 @@}}},+ "No folder chosen": {+ "localizations": {+ "en": {+ "stringUnit": {+ "state": "translated",+ "value": "No folder chosen"+ }+ },+ "zh-Hans": {+ "stringUnit": {+ "state": "translated",+ "value": "未选择文件夹"+ }+ }+ }+ },"Off": {"localizations": {"en": {@@ -609,6 +721,22 @@}}},+ "Performance overlay": {+ "localizations": {+ "en": {+ "stringUnit": {+ "state": "translated",+ "value": "Performance overlay"+ }+ },+ "zh-Hans": {+ "stringUnit": {+ "state": "translated",+ "value": "性能浮层"+ }+ }+ }+ },"Play": {"localizations": {"en": {@@ -737,6 +865,22 @@}}},+ "Settings": {+ "localizations": {+ "en": {+ "stringUnit": {+ "state": "translated",+ "value": "Settings"+ }+ },+ "zh-Hans": {+ "stringUnit": {+ "state": "translated",+ "value": "设置"+ }+ }+ }+ },"Show log": {"localizations": {"en": {@@ -865,6 +1009,22 @@}}},+ "Used by games that have no choice of their own.": {+ "localizations": {+ "en": {+ "stringUnit": {+ "state": "translated",+ "value": "Used by games that have no choice of their own."+ }+ },+ "zh-Hans": {+ "stringUnit": {+ "state": "translated",+ "value": "游戏未单独设置时使用。"+ }+ }+ }+ },"Version %@": {"localizations": {"en": {diff --git a/frontend-ios/Sources/ShellUI/ShellInputs.swift b/frontend-ios/Sources/ShellUI/ShellInputs.swiftindex 8acfc0e2..b7abf4a9 100644--- a/frontend-ios/Sources/ShellUI/ShellInputs.swift+++ b/frontend-ios/Sources/ShellUI/ShellInputs.swift@@ -82,8 +82,12 @@ public struct GameDetail: Identifiable, Equatable, Sendable {public var cloudNote: Stringpublic var dlc: Stringpublic var hasModifiedSettings: Bool+ /// The data or cloud-saves folder is the shell settings' one, not one the player picked for this game.+ public var dataFromShell: Bool+ public var cloudFromShell: Boolpublic init(game: GameTile, sections: [SettingSection] = [], dataSource: String = "", dataNote: String = "",- cloudSaves: String? = nil, cloudNote: String = "", dlc: String = "", hasModifiedSettings: Bool = false) {+ cloudSaves: String? = nil, cloudNote: String = "", dlc: String = "", hasModifiedSettings: Bool = false,+ dataFromShell: Bool = false, cloudFromShell: Bool = false) {self.game = gameself.sections = sectionsself.dataSource = dataSource@@ -92,6 +96,8 @@ public struct GameDetail: Identifiable, Equatable, Sendable {self.cloudNote = cloudNoteself.dlc = dlcself.hasModifiedSettings = hasModifiedSettings+ self.dataFromShell = dataFromShell+ self.cloudFromShell = cloudFromShell}}diff --git a/frontend-ios/Sources/ShellUI/ShellSettingsStore.swift b/frontend-ios/Sources/ShellUI/ShellSettingsStore.swiftindex aa50feda..72f0654b 100644--- a/frontend-ios/Sources/ShellUI/ShellSettingsStore.swift+++ b/frontend-ios/Sources/ShellUI/ShellSettingsStore.swift@@ -9,8 +9,14 @@ public final class ShellSettingsStore: @unchecked Sendable {public static let cloudSavesKey = "globalCloudSavesBookmark"public static let languageKey = "interfaceLanguage" // "" = follow the device, "zh-Hans", "en"public static let performanceHUDKey = "performanceHUD" // true/false; a game's own row wins when set+ public static let dataFolderNameKey = "globalDataFolderName"+ public static let cloudSavesNameKey = "globalCloudSavesFolderName"- private let defaults: UserDefaults+ /// The store the app reads and writes. Tests and previews swap it.+ nonisolated(unsafe) public static var current = ShellSettingsStore()++ /// The suite itself, so the host keeps the folder bookmarks in it with its `BookmarkStore`.+ public let defaults: UserDefaultspublic init(defaults: UserDefaults = UserDefaults(suiteName: ShellSettingsStore.suiteName) ?? .standard) {self.defaults = defaults@@ -18,19 +24,39 @@ public final class ShellSettingsStore: @unchecked Sendable {public var dataBookmark: Data? { defaults.data(forKey: Self.dataFolderKey) }public var cloudSavesBookmark: Data? { defaults.data(forKey: Self.cloudSavesKey) }+ /// The folders' names for the page, written by the host when the player picks them.+ public var dataFolderName: String? { defaults.string(forKey: Self.dataFolderNameKey) }+ public var cloudSavesFolderName: String? { defaults.string(forKey: Self.cloudSavesNameKey) }public var language: String { defaults.string(forKey: Self.languageKey) ?? "" }public var performanceHUD: Bool? { // nil: no shell-level choice, the game's own row decidesdefaults.object(forKey: Self.performanceHUDKey) as? Bool}- public func storeDataBookmark(_ data: Data) { defaults.set(data, forKey: Self.dataFolderKey) }- public func storeCloudSavesBookmark(_ data: Data) { defaults.set(data, forKey: Self.cloudSavesKey) }+ public func storeDataFolderName(_ name: String) { defaults.set(name, forKey: Self.dataFolderNameKey) }+ public func storeCloudSavesFolderName(_ name: String) { defaults.set(name, forKey: Self.cloudSavesNameKey) }public func storeLanguage(_ code: String) { defaults.set(code, forKey: Self.languageKey) }public func storePerformanceHUD(_ on: Bool) { defaults.set(on, forKey: Self.performanceHUDKey) }- /// A per-game defaults that resolves a missing key from the shell store: the game wins, the shell backs it up.- public static func effective(_ gameDefaults: UserDefaults, shell: ShellSettingsStore, key: String) -> Bool? {- if gameDefaults.object(forKey: key) != nil { return gameDefaults.bool(forKey: key) }- return shell.performanceHUD+ /// The shell's value for each `DM_*` switch a game's own settings leave alone.+ public var gameDefaults: [String: String] {+ performanceHUD.map { ["DM_METAL_HUD": $0 ? "1" : "0"] } ?? [:]+ }+}++/// The interface language the player chose. Empty follows the device.+public enum ShellLanguage {+ public static let supported = ["zh-Hans", "en"]+ nonisolated(unsafe) private static var cache: [String: Bundle] = [:]+ private static let lock = NSLock()++ /// `bundle`, or its folder for the chosen language, so a string table is read in that language whatever the device uses.+ public static func bundle(_ bundle: Bundle, language: String = ShellSettingsStore.current.language) -> Bundle {+ guard supported.contains(language) else { return bundle }+ let key = bundle.bundlePath + "|" + language+ lock.lock(); defer { lock.unlock() }+ if let found = cache[key] { return found }+ guard let path = bundle.path(forResource: language, ofType: "lproj"), let localized = Bundle(path: path) else { return bundle }+ cache[key] = localized+ return localized}}diff --git a/frontend-ios/Sources/ShellUI/ShellSettingsView.swift b/frontend-ios/Sources/ShellUI/ShellSettingsView.swiftindex ac3e143f..220adbe3 100644--- a/frontend-ios/Sources/ShellUI/ShellSettingsView.swift+++ b/frontend-ios/Sources/ShellUI/ShellSettingsView.swift@@ -1,79 +1,104 @@import SwiftUI-import ShellUI-import UniformTypeIdentifiers-/// The shell-level settings: the game-data folder, the cloud-saves folder, the interface language and the default-/// performance HUD (ShellSettingsStore). A game's own settings and bookmarks win over these; these win over the-/// built-in defaults. The rows reuse the game settings' components, and the pickers use the same security-scoped-/// bookmarks as a game's own picks (BookmarkStore).-public struct ShellSettingsView: View {- @State private var store: ShellSettingsStore- @State private var dataNote = ""- @State private var cloudNote = ""- @State private var language: String- @State private var hudOn: Bool- private let pickFolder: (String) -> Void // key ("data" | "cloud"), the host runs the picker+/// The rows of the shell settings, in the game settings' own model so the same controls draw them. The game ID tells+/// the library that a change belongs to the shell and not to a game.+enum ShellSettingsRows {+ static let gameID = "shell"+ static let language = "shell.language"+ static let hud = "shell.hud"+ static let targetPrefix = "shs.row."- public init(store: ShellSettingsStore = ShellSettingsStore(),- pickFolder: @escaping (String) -> Void) {- _store = State(initialValue: store)- _language = State(initialValue: store.language)- _hudOn = State(initialValue: store.performanceHUD ?? false)- self.pickFolder = pickFolder+ static func languageRow(_ store: ShellSettingsStore) -> SettingRow {+ SettingRow(id: language, label: ShellStrings.text("Language"), note: ShellStrings.text("Applies to the whole app."),+ kind: .choice([SettingOption("", ShellStrings.text("Follow device")), SettingOption("zh-Hans", "中文"),+ SettingOption("en", "English")]),+ value: store.language)}- public var body: some View {- ScrollView {- VStack(alignment: .leading, spacing: 18) {- section(title: zh("游戏数据")) {- row(label: zh("统一游戏数据目录"), note: dataNote.isEmpty ? zh("新游戏优先在这里找游戏数据。每个游戏也可以单独指定。") : dataNote) {- Button(zh("选择文件夹…")) { pickFolder("data") }- }- }- section(title: zh("云存档")) {- row(label: zh("统一云存档目录"), note: cloudNote.isEmpty ? zh("选择与 Mac 相同的 iCloud Drive 文件夹,所有游戏默认共享它的存档结构。") : cloudNote) {- Button(zh("选择文件夹…")) { pickFolder("cloud") }- }- }- section(title: zh("界面")) {- row(label: zh("界面语言"), note: "") {- Picker("", selection: $language) {- Text(zh("跟随设备")).tag("")- Text("中文").tag("zh-Hans")- Text("English").tag("en")- }- .pickerStyle(.menu).onChange(of: language) { _, v in store.storeLanguage(v) }- }- row(label: zh("默认性能浮层"), note: zh("游戏未单独设置时使用。")) {- Toggle("", isOn: $hudOn).onChange(of: hudOn) { _, v in store.storePerformanceHUD(v) }- }- }- }- .padding(20)- }- .navigationTitle(zh("设置"))+ static func hudRow(_ store: ShellSettingsStore) -> SettingRow {+ SettingRow(id: hud, label: ShellStrings.text("Performance overlay"), note: ShellStrings.text("Used by games that have no choice of their own."),+ kind: .toggle(on: "1", off: "0"), value: store.performanceHUD == true ? "1" : "0")}- @ViewBuilder private func section<Content: View>(title: String, @ViewBuilder _ content: () -> Content) -> some View {- VStack(alignment: .leading, spacing: 10) {- Text(title).font(.headline).foregroundStyle(.secondary)- content()+ /// A change of one of the rows, from the row itself or from the list of choices.+ static func apply(_ id: String, value: String, to store: ShellSettingsStore) {+ switch id {+ case language where value.isEmpty || ShellLanguage.supported.contains(value): store.storeLanguage(value)+ case hud: store.storePerformanceHUD(value == "1")+ default: break}- .frame(maxWidth: .infinity, alignment: .leading)- .padding(16)- .background(.background.opacity(0.6), in: RoundedRectangle(cornerRadius: 14))}+}++/// The shell's own settings: the game-data folder, the cloud-saves folder, the language and the default performance+/// overlay. A game's own choices win over these, and these win over the built-in defaults. It looks like a game's+/// settings and takes a controller the same way, as a panel over the library.+struct ShellSettingsView: View {+ var store: ShellSettingsStore = .current+ var actions: ShellActions+ var onClose: () -> Void+ @Environment(\.accessibilityReduceMotion) private var reduceMotion+ @Environment(\.shellFocus) private var focus+ /// Counts the changes in the defaults, so the rows read the store again.+ @State private var revision = 0- @ViewBuilder private func row<Content: View>(label: String, note: String, @ViewBuilder _ control: () -> Content) -> some View {- HStack {- VStack(alignment: .leading, spacing: 3) {- Text(label)- if !note.isEmpty { Text(note).font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true) }+ var body: some View {+ let _ = revision+ GeometryReader { geometry in+ ScrollViewReader { proxy in+ ScrollView {+ VStack(alignment: .leading, spacing: 30) {+ HStack(alignment: .center) {+ Text(ShellStrings.text("Settings")).shellType(ShellType.pageTitle)+ .lineLimit(1).minimumScaleFactor(0.7).accessibilityAddTraits(.isHeader)+ Spacer(minLength: 8)+ Button(action: onClose) { Text(ShellStrings.text("Done")) }+ .buttonStyle(ChipButtonStyle())+ .accessibilityIdentifier("shellSettings.close")+ .shellTarget("shs.close", radius: 22, action: onClose)+ }.id("shs.top")+ SettingsGroup(title: ShellStrings.text("Game data")) {+ SourceRow(symbol: "folder", title: store.dataFolderName ?? ShellStrings.text("No folder chosen"),+ note: ShellStrings.text("Games look for their data here. Each game can have a folder of its own.")) {+ Button(ShellStrings.text("Choose folder…")) { actions.onPickShellData() }+ .buttonStyle(ShellButtonStyle(fills: true)).accessibilityIdentifier("shellSettings.data")+ .shellTarget("shs.data") { actions.onPickShellData() }+ }+ }+ SettingsGroup(title: ShellStrings.text("Cloud saves")) {+ SourceRow(symbol: store.cloudSavesFolderName == nil ? "icloud.slash" : "icloud",+ title: store.cloudSavesFolderName ?? ShellStrings.text("Off"),+ note: ShellStrings.text("Games without a folder of their own save here. Choose the same iCloud Drive folder you use on your Mac.")) {+ Button(ShellStrings.text("Choose folder…")) { actions.onPickShellCloud() }+ .buttonStyle(ShellButtonStyle(fills: true)).accessibilityIdentifier("shellSettings.cloud")+ .shellTarget("shs.cloud") { actions.onPickShellCloud() }+ }+ }+ SettingsGroup(title: ShellStrings.text("Interface")) {+ let language = ShellSettingsRows.languageRow(store), hud = ShellSettingsRows.hudRow(store)+ SettingControl(gameID: ShellSettingsRows.gameID, row: language, targetPrefix: ShellSettingsRows.targetPrefix) {+ ShellSettingsRows.apply(language.id, value: $0, to: store)+ }.equatable()+ Rectangle().fill(.white.opacity(0.06)).frame(height: 1)+ SettingControl(gameID: ShellSettingsRows.gameID, row: hud, targetPrefix: ShellSettingsRows.targetPrefix) {+ ShellSettingsRows.apply(hud.id, value: $0, to: store)+ }.equatable()+ }+ }+ .padding(24).padding(.bottom, geometry.safeAreaInsets.bottom).frame(maxWidth: 640)+ .frame(maxWidth: .infinity, alignment: .leading)+ }+ .scrollIndicators(.hidden)+ .ignoresSafeArea(edges: .bottom)+ .onChange(of: focus.id) { _, id in+ guard let id, id.hasPrefix("shs.") else { return }+ withAnimation(reduceMotion ? nil : .easeOut(duration: 0.18)) {+ proxy.scrollTo(id == "shs.close" ? "shs.top" : id, anchor: id == "shs.close" ? .top : .center)+ }+ }}- Spacer()- control()}+ .foregroundStyle(.white).preferredColorScheme(.dark)+ .onReceive(NotificationCenter.default.publisher(for: UserDefaults.didChangeNotification)) { _ in revision += 1 }}-- private func zh(_ s: String) -> String { s } // the words are already the device-language pair; Localizable covers them}diff --git a/frontend-ios/Sources/ShellUI/ShellStyle.swift b/frontend-ios/Sources/ShellUI/ShellStyle.swiftindex a2d1fea9..3589cd8a 100644--- a/frontend-ios/Sources/ShellUI/ShellStyle.swift+++ b/frontend-ios/Sources/ShellUI/ShellStyle.swift@@ -13,7 +13,8 @@ public enum ShellPalette {}enum ShellStrings {- static func text(_ key: String.LocalizationValue) -> String { String(localized: key, bundle: .module) }+ static var bundle: Bundle { .module }+ static func text(_ key: String.LocalizationValue) -> String { String(localized: key, bundle: ShellLanguage.bundle(bundle)) }}@MainActor public enum ShellFonts {diff --git a/frontend-ios/Tests/ShellHostTests/CatalogueStateTests.swift b/frontend-ios/Tests/ShellHostTests/CatalogueStateTests.swiftindex eb76f436..cf1e784c 100644--- a/frontend-ios/Tests/ShellHostTests/CatalogueStateTests.swift+++ b/frontend-ios/Tests/ShellHostTests/CatalogueStateTests.swift@@ -126,6 +126,21 @@ import ShellUI#expect(DataLocator.locate(manifest: m, picked: .url(img), appFolder: app).url == img.deletingLastPathComponent())}+ @Test func theShellFolderBacksTheGameAndSaysSo() throws {+ let box = try Sandbox()+ let m = try manifest()+ let app = box.appData.appendingPathComponent(Fixtures.orbit)+ let shared = box.root.appendingPathComponent("Drive/All", isDirectory: true)+ try box.write("", to: shared.appendingPathComponent("fixture.marker"))+ let r = DataLocator.locate(manifest: m, picked: .none, appFolder: app, global: .url(shared))+ #expect(r.source == .shell && r.url == shared)+ let own = box.root.appendingPathComponent("Drive/Own", isDirectory: true)+ try box.write("", to: own.appendingPathComponent("fixture.marker"))+ #expect(DataLocator.locate(manifest: m, picked: .url(own), appFolder: app, global: .url(shared)).source == .picked)+ try box.giveAppData()+ #expect(DataLocator.locate(manifest: m, picked: .none, appFolder: app, global: .stale).source == .app)+ }+@Test func staleBookmarkIsReported() throws {let box = try Sandbox()let r = DataLocator.locate(manifest: try manifest(), picked: .stale, appFolder: box.appData.appendingPathComponent(Fixtures.orbit))diff --git a/frontend-ios/Tests/ShellHostTests/ShellHostModelTests.swift b/frontend-ios/Tests/ShellHostTests/ShellHostModelTests.swiftindex c733251e..bd53ac21 100644--- a/frontend-ios/Tests/ShellHostTests/ShellHostModelTests.swift+++ b/frontend-ios/Tests/ShellHostTests/ShellHostModelTests.swift@@ -166,6 +166,123 @@ final class Clock: @unchecked Sendable { var date: Date; init(_ d: Date) { date#expect(orbit.dataNote.contains("no longer readable"))}+ private func shellSettings() -> ShellSettingsStore { ShellSettingsStore(defaults: UserDefaults(suiteName: "t-shell-\(UUID().uuidString)")!) }++ /// The orbit fixture with a performance overlay row of its own, like a game whose list has `DM_METAL_HUD`.+ private func giveOrbitAnOverlayRow(_ box: Sandbox) throws {+ let url = box.games.appendingPathComponent(Fixtures.orbit).appendingPathComponent("launcher.json")+ var json = try #require(JSONSerialization.jsonObject(with: Data(contentsOf: url)) as? [String: Any])+ var settings = try #require(json["settings"] as? [[String: Any]])+ settings.append(["env": "DM_METAL_HUD", "kind": "toggle", "section": "Performance", "label": "Overlay", "note": "", "default": "0", "on": "1", "off": "0"])+ json["settings"] = settings+ try JSONSerialization.data(withJSONObject: json).write(to: url)+ }++ @Test func theShellOverlayChoiceReachesTheEngineUnlessTheGameChoseItself() async throws {+ let box = try Sandbox()+ try box.giveAppData()+ try giveOrbitAnOverlayRow(box)+ let shell = shellSettings()+ shell.storePerformanceHUD(true)+ let launcher = RecordingLauncher()+ let model = ShellHostModel(config: box.config(), launcher: launcher, shellSettings: shell)+ #expect(try value(model, "DM_METAL_HUD") == "1", "the page shows what the engine will get")+ await model.playNow(Fixtures.orbit)+ let first = try #require(launcher.launched.last)+ #expect(first.environment["DM_METAL_HUD"] == "1")+ let plan = EngineLaunchPlan.make(game: first, appResources: box.root, documents: box.root, envFileText: "DM_METAL_HUD=0\n")+ #expect(plan.environment["DM_METAL_HUD"] == "1")+ model.actions.onChange(Fixtures.orbit, "DM_METAL_HUD", "0")+ #expect(try value(model, "DM_METAL_HUD") == "0")+ await model.playNow(Fixtures.orbit)+ #expect(launcher.launched.last?.environment["DM_METAL_HUD"] == "0", "the game's choice wins over the shell's")+ }++ @Test func aGameWithoutAnOverlayRowStillGetsTheShellChoice() async throws {+ let box = try Sandbox()+ try box.giveAppData()+ let shell = shellSettings()+ let launcher = RecordingLauncher()+ let model = ShellHostModel(config: box.config(), launcher: launcher, shellSettings: shell)+ await model.playNow(Fixtures.orbit)+ #expect(launcher.launched.last?.environment["DM_METAL_HUD"] == nil, "no shell choice, nothing is set")+ shell.storePerformanceHUD(false)+ await model.playNow(Fixtures.orbit)+ #expect(launcher.launched.last?.environment["DM_METAL_HUD"] == "0")+ }++ @Test func aChangedShellOverlayChoiceUpdatesTheDetails() throws {+ let box = try Sandbox()+ try giveOrbitAnOverlayRow(box)+ let shell = shellSettings()+ let model = ShellHostModel(config: box.config(), shellSettings: shell)+ #expect(try value(model, "DM_METAL_HUD") == "0")+ shell.storePerformanceHUD(true)+ NotificationCenter.default.post(name: UserDefaults.didChangeNotification, object: nil)+ #expect(try value(model, "DM_METAL_HUD") == "1")+ }++ @Test func theShellCloudFolderBacksAGameWithoutOne() async throws {+ let box = try Sandbox()+ try box.giveAppData()+ let shared = box.root.appendingPathComponent("iCloud/Shared Saves", isDirectory: true)+ let own = box.root.appendingPathComponent("iCloud/Own Saves", isDirectory: true)+ for folder in [shared, own] { try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) }+ let shell = shellSettings()+ let launcher = RecordingLauncher()+ let model = ShellHostModel(config: box.config(), launcher: launcher, picker: FakePicker(url: shared), shellSettings: shell)+ #expect(try detail(model).cloudSaves == nil)+ await model.pickShellCloudNow()+ #expect(shell.cloudSavesFolderName == "Shared Saves" && shell.cloudSavesBookmark != nil)+ var orbit = try detail(model)+ #expect(orbit.cloudSaves == "Shared Saves" && orbit.cloudFromShell)+ #expect(try detail(model, Fixtures.chain).cloudSaves == "Shared Saves")+ await model.playNow(Fixtures.orbit)+ #expect(launcher.launched.last?.cloudSavesURL?.lastPathComponent == "Shared Saves")+ // The game's own folder wins+ let own2 = ShellHostModel(config: box.config(), launcher: launcher, picker: FakePicker(url: own), shellSettings: shell)+ await own2.pickCloudSavesNow(Fixtures.orbit)+ orbit = try detail(own2)+ #expect(orbit.cloudSaves == "Own Saves" && !orbit.cloudFromShell)+ await own2.playNow(Fixtures.orbit)+ #expect(launcher.launched.last?.cloudSavesURL?.lastPathComponent == "Own Saves")+ // Turning the game's folder off falls back to the shell's, and the game's setting stays untouched in between+ own2.actions.onDisableCloudSaves(Fixtures.orbit)+ #expect(try detail(own2).cloudSaves == "Shared Saves")+ }++ @Test func theShellDataFolderIsNotPresentedAsThePlayersPickForTheGame() async throws {+ let box = try Sandbox()+ let drive = box.root.appendingPathComponent("Drive/Switch", isDirectory: true)+ try box.write("", to: drive.appendingPathComponent("fixture.marker"))+ let shell = shellSettings()+ let model = ShellHostModel(config: box.config(), picker: FakePicker(url: drive), shellSettings: shell)+ #expect(try detail(model).game.state == .needsGameData)+ await model.pickShellDataNow()+ #expect(shell.dataFolderName == "Switch")+ let orbit = try detail(model)+ #expect(orbit.game.state == .playable && orbit.dataFromShell)+ #expect(orbit.dataSource == "Switch (from Settings)")+ #expect(box.defaults(Fixtures.orbit).data(forKey: "pickedDataBookmark") == nil, "nothing is stored for the game")+ // A folder the player picks for the game takes over+ let own = box.root.appendingPathComponent("Own/Orbit", isDirectory: true)+ try box.write("", to: own.appendingPathComponent("fixture.marker"))+ await ShellHostModel(config: box.config(), picker: FakePicker(url: own), shellSettings: shell).pickGameDataNow(Fixtures.orbit)+ let again = try detail(ShellHostModel(config: box.config(), shellSettings: shell))+ #expect(again.dataSource == "Orbit" && !again.dataFromShell)+ }++ @Test func theShellFolderPickersReportAFailureAndKeepTheOldChoice() async throws {+ let box = try Sandbox()+ let missing = box.root.appendingPathComponent("not-there", isDirectory: true)+ let shell = shellSettings()+ let model = ShellHostModel(config: box.config(), picker: FakePicker(url: missing), shellSettings: shell)+ await model.pickShellDataNow()+ #expect(model.notice != nil && shell.dataFolderName == nil && shell.dataBookmark == nil)+ await ShellHostModel(config: box.config(), picker: FakePicker(url: nil), shellSettings: shell).pickShellCloudNow()+ #expect(shell.cloudSavesFolderName == nil)+ }+@Test func showLogReadsTheGamesLogOrSaysThereIsNone() throws {let box = try Sandbox()let model = ShellHostModel(config: box.config())diff --git a/frontend-ios/Tests/ShellHostTests/ShellSettingsStoreTests.swift b/frontend-ios/Tests/ShellHostTests/ShellSettingsStoreTests.swiftindex 587c2bcf..42c5e92a 100644--- a/frontend-ios/Tests/ShellHostTests/ShellSettingsStoreTests.swift+++ b/frontend-ios/Tests/ShellHostTests/ShellSettingsStoreTests.swift@@ -1,18 +1,42 @@-import XCTest+import Foundation+import Testing@testable import ShellHostimport ShellUI-final class ShellSettingsStoreTests: XCTestCase {- func testGameWinsShellWinsBuiltin() {- let game = UserDefaults(suiteName: "t-game-\(UUID().uuidString)")!- let shell = ShellSettingsStore(defaults: UserDefaults(suiteName: "t-shell-\(UUID().uuidString)")!)- // 无任何设置 → nil(游戏自己的行决定)- XCTAssertNil(ShellSettingsStore.effective(game, shell: shell, key: "hud"))- // 只有壳设置 → 壳的值- shell.storePerformanceHUD(true)- XCTAssertEqual(ShellSettingsStore.effective(game, shell: shell, key: "hud"), true)- // 游戏也设了 → 游戏的值- game.set(false, forKey: "hud")- XCTAssertEqual(ShellSettingsStore.effective(game, shell: shell, key: "hud"), false)+@Suite struct ShellSettingsStoreTests {+ private func shell() -> ShellSettingsStore { ShellSettingsStore(defaults: UserDefaults(suiteName: "t-shell-\(UUID().uuidString)")!) }++ @Test func theOverlayChoiceIsNilUntilThePlayerMakesOne() {+ let store = shell()+ #expect(store.performanceHUD == nil && store.gameDefaults.isEmpty && store.language == "")+ store.storePerformanceHUD(true)+ #expect(store.performanceHUD == true && store.gameDefaults == ["DM_METAL_HUD": "1"])+ store.storePerformanceHUD(false)+ #expect(store.gameDefaults == ["DM_METAL_HUD": "0"])+ }++ @Test func theFolderNamesAndTheLanguageAreKept() {+ let store = shell()+ store.storeDataFolderName("Switch")+ store.storeCloudSavesFolderName("Game Saves")+ store.storeLanguage("zh-Hans")+ #expect(store.dataFolderName == "Switch" && store.cloudSavesFolderName == "Game Saves" && store.language == "zh-Hans")+ }++ @Test func aGameChoiceWinsTheShellDefaultWinsTheBuiltInOne() throws {+ let box = try Sandbox()+ let profile = try LauncherProfile.parse(Data(contentsOf: Fixtures.gamesURL.appendingPathComponent(Fixtures.orbit).appendingPathComponent("launcher.json")))+ let defaults = box.defaults(Fixtures.orbit)+ let shellDefaults = ["DM_SHOW_FPS": "1"]+ var store = GameSettingsStore(profile: profile, defaults: defaults, shell: shellDefaults)+ #expect(store.values()["DM_SHOW_FPS"] == "1", "the shell's value over the built-in default")+ #expect(!store.hasModifiedSettings, "a shell default is not a change the player made in this game")+ store.set("DM_SHOW_FPS", to: "0")+ #expect(store.values()["DM_SHOW_FPS"] == "0", "the game's own choice, though it equals the built-in default")+ #expect(defaults.object(forKey: "launcher.DM_SHOW_FPS") as? String == "0")+ store.set("DM_SHOW_FPS", to: "1")+ #expect(defaults.object(forKey: "launcher.DM_SHOW_FPS") == nil, "a choice equal to the shell's value follows the shell again")+ store = GameSettingsStore(profile: profile, defaults: defaults, shell: ["DM_OPMODE": "7"])+ #expect(store.values()["DM_OPMODE"] == "1", "a value the game does not offer is ignored")}}diff --git a/frontend-ios/Tests/ShellUITests/ShellStringsTests.swift b/frontend-ios/Tests/ShellUITests/ShellStringsTests.swiftnew file mode 100644index 00000000..cde6a799--- /dev/null+++ b/frontend-ios/Tests/ShellUITests/ShellStringsTests.swift@@ -0,0 +1,48 @@+import Foundation+import Testing+@testable import ShellUI++/// Every text of the shell comes in English and in Simplified Chinese, the two languages the interface language can pick.+@Suite struct ShellStringsTests {+ private static let languages = ["en", "zh-Hans"]++ private func table(_ name: String, in folder: String) throws -> [String: Any] {+ let url = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent()+ .appendingPathComponent("Sources/\(folder)/Resources/Localizable.xcstrings")+ let json = try #require(JSONSerialization.jsonObject(with: Data(contentsOf: url)) as? [String: Any])+ return try #require(json["strings"] as? [String: Any])+ }++ @Test(arguments: ["ShellUI", "ShellHost"]) func everyKeyHasEveryLanguage(folder: String) throws {+ let strings = try table("Localizable", in: folder)+ #expect(!strings.isEmpty)+ for (key, entry) in strings {+ let localizations = ((entry as? [String: Any])?["localizations"] as? [String: Any]) ?? [:]+ for language in Self.languages {+ let unit = (localizations[language] as? [String: Any])?["stringUnit"] as? [String: Any]+ let value = unit?["value"] as? String ?? ""+ #expect(!value.isEmpty && unit?["state"] as? String == "translated", "\(folder): \"\(key)\" lacks \(language)")+ }+ }+ }++ @Test func theSettingsPageTextsAreThere() throws {+ let strings = try table("Localizable", in: "ShellUI")+ for key in ["Settings", "Done", "Interface", "Language", "Follow device", "Performance overlay", "Game data", "Cloud saves", "Choose folder…"] {+ #expect(strings[key] != nil, "\(key)")+ }+ }++ @Test func theChosenLanguageSelectsTheStringTable() {+ func text(_ language: String) -> String {+ String(localized: "Done", bundle: ShellLanguage.bundle(ShellStrings.bundle, language: language))+ }+ #expect(ShellLanguage.supported == ["zh-Hans", "en"])+ #expect(text("en") == "Done")+ #expect(text("zh-Hans") != "Done" && !text("zh-Hans").isEmpty)+ #expect(ShellLanguage.bundle(ShellStrings.bundle, language: "") == ShellStrings.bundle, "no choice follows the device")+ #expect(ShellLanguage.bundle(ShellStrings.bundle, language: "fr") == ShellStrings.bundle, "an unknown choice follows the device")+ let count = String(localized: "\(3) of \(5)", bundle: ShellLanguage.bundle(ShellStrings.bundle, language: "zh-Hans"))+ #expect(count != "3 of 5", "an interpolated text is found in the chosen language too")+ }+}