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
iOS shell host: catalogue, settings, game data, cloud saves, log and the launcher seam
v0lumehid42d33e413be
diff --git a/frontend-ios/Demo/ShellDemo.xcodeproj/project.pbxproj b/frontend-ios/Demo/ShellDemo.xcodeproj/project.pbxprojindex 9ab83d81..e9144966 100644--- a/frontend-ios/Demo/ShellDemo.xcodeproj/project.pbxproj+++ b/frontend-ios/Demo/ShellDemo.xcodeproj/project.pbxproj@@ -8,15 +8,19 @@/* Begin PBXBuildFile section */2861C1407044359116FE0A66 /* ShellCaptureTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8694319745E3759D50772855 /* ShellCaptureTests.swift */; };+ 2BF462D88A6CE3993C4AEB9A /* ShellHostUITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = D3902CFEF269CA462AFE8048 /* ShellHostUITests.swift */; };2EEF6A8F9A7D58C09181EAB5 /* RealArt.swift in Sources */ = {isa = PBXBuildFile; fileRef = FF911DEE5C19B0D069418726 /* RealArt.swift */; };3E143B39E0F97A669D2F6EFF /* ShellAdditionalTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = DF3DBBE6BC067DDD34E3560C /* ShellAdditionalTests.swift */; };44E0EBFDB9557A0C8BB741BE /* ShellUI in Frameworks */ = {isa = PBXBuildFile; productRef = 7F6858A53523100F9E10590E /* ShellUI */; };4749F987D74B27CAA0E02480 /* ShellDemoApp.swift in Sources */ = {isa = PBXBuildFile; fileRef = 59E0A7AE45425C5BA9689FE4 /* ShellDemoApp.swift */; };+ 47DB35565D19F0ACFF1E2F7E /* ShellHost in Frameworks */ = {isa = PBXBuildFile; productRef = D80A22588F977AEE019B7CFE /* ShellHost */; };876E4B3FCD4C78C4085BCE30 /* ShellControllers in Frameworks */ = {isa = PBXBuildFile; productRef = D58DB30045BDC25980479EF9 /* ShellControllers */; };+ C12D9CC70DEF69CCB48F44E7 /* Games in Resources */ = {isa = PBXBuildFile; fileRef = 3FAC070A229B08BED4005826 /* Games */; };D94D715334EE4F5E0CCBA788 /* SampleArt.swift in Sources */ = {isa = PBXBuildFile; fileRef = 39DB78D11BCF59879A3712F5 /* SampleArt.swift */; };DF097C40B129901722DD4DF3 /* ShellDemoUITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 916109EC3198FC9C0E9D655B /* ShellDemoUITests.swift */; };E71FEFEAE303CA4343BBDE2E /* SampleData.swift in Sources */ = {isa = PBXBuildFile; fileRef = CBE23919FFDC3D06EF0D3065 /* SampleData.swift */; };F15D381F62331B5172AD6D22 /* Localizable.xcstrings in Resources */ = {isa = PBXBuildFile; fileRef = D1591481D38DDC20A1A9B215 /* Localizable.xcstrings */; };+ FAE394E91FBBBC0FD28A1C39 /* HostDemo.swift in Sources */ = {isa = PBXBuildFile; fileRef = B516EC05EC6F1241E8281A82 /* HostDemo.swift */; };/* End PBXBuildFile section *//* Begin PBXContainerItemProxy section */@@ -31,14 +35,17 @@/* Begin PBXFileReference section */39DB78D11BCF59879A3712F5 /* SampleArt.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SampleArt.swift; sourceTree = "<group>"; };+ 3FAC070A229B08BED4005826 /* Games */ = {isa = PBXFileReference; lastKnownFileType = folder; name = Games; path = ../Tests/ShellHostTests/Fixtures/Games; sourceTree = SOURCE_ROOT; };59E0A7AE45425C5BA9689FE4 /* ShellDemoApp.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ShellDemoApp.swift; sourceTree = "<group>"; };8694319745E3759D50772855 /* ShellCaptureTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ShellCaptureTests.swift; sourceTree = "<group>"; };916109EC3198FC9C0E9D655B /* ShellDemoUITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ShellDemoUITests.swift; sourceTree = "<group>"; };B1D199F3FD9C677BD245559E /* ShellDemoApp.app */ = {isa = PBXFileReference; includeInIndex = 0; lastKnownFileType = wrapper.application; path = ShellDemoApp.app; sourceTree = BUILT_PRODUCTS_DIR; };+ B516EC05EC6F1241E8281A82 /* HostDemo.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HostDemo.swift; sourceTree = "<group>"; };B88394C7E11B302B2B420DF2 /* frontend-ios */ = {isa = PBXFileReference; lastKnownFileType = folder; name = "frontend-ios"; path = ..; sourceTree = SOURCE_ROOT; };CBE23919FFDC3D06EF0D3065 /* SampleData.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SampleData.swift; sourceTree = "<group>"; };CEB77983EFFD9EA46FE3DFDF /* ShellDemoUITests.xctest */ = {isa = PBXFileReference; includeInIndex = 0; lastKnownFileType = wrapper.cfbundle; path = ShellDemoUITests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };D1591481D38DDC20A1A9B215 /* Localizable.xcstrings */ = {isa = PBXFileReference; lastKnownFileType = text.json.xcstrings; path = Localizable.xcstrings; sourceTree = "<group>"; };+ D3902CFEF269CA462AFE8048 /* ShellHostUITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ShellHostUITests.swift; sourceTree = "<group>"; };DF3DBBE6BC067DDD34E3560C /* ShellAdditionalTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ShellAdditionalTests.swift; sourceTree = "<group>"; };FF911DEE5C19B0D069418726 /* RealArt.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RealArt.swift; sourceTree = "<group>"; };/* End PBXFileReference section */@@ -50,6 +57,7 @@files = (44E0EBFDB9557A0C8BB741BE /* ShellUI in Frameworks */,876E4B3FCD4C78C4085BCE30 /* ShellControllers in Frameworks */,+ 47DB35565D19F0ACFF1E2F7E /* ShellHost in Frameworks */,);runOnlyForDeploymentPostprocessing = 0;};@@ -67,6 +75,7 @@5928E24F76B598AD8FD0D1AB /* ShellDemo */ = {isa = PBXGroup;children = (+ B516EC05EC6F1241E8281A82 /* HostDemo.swift */,FF911DEE5C19B0D069418726 /* RealArt.swift */,39DB78D11BCF59879A3712F5 /* SampleArt.swift */,CBE23919FFDC3D06EF0D3065 /* SampleData.swift */,@@ -83,6 +92,7 @@DF3DBBE6BC067DDD34E3560C /* ShellAdditionalTests.swift */,8694319745E3759D50772855 /* ShellCaptureTests.swift */,916109EC3198FC9C0E9D655B /* ShellDemoUITests.swift */,+ D3902CFEF269CA462AFE8048 /* ShellHostUITests.swift */,);name = UITests;path = ../UITests;@@ -108,6 +118,7 @@E65C041019EAFE79D28C3E4E = {isa = PBXGroup;children = (+ 3FAC070A229B08BED4005826 /* Games */,2152F5714F5AA74B9FBBB0F0 /* Packages */,5928E24F76B598AD8FD0D1AB /* ShellDemo */,B149173B288581EEEA22408A /* UITests */,@@ -134,6 +145,7 @@packageProductDependencies = (7F6858A53523100F9E10590E /* ShellUI */,D58DB30045BDC25980479EF9 /* ShellControllers */,+ D80A22588F977AEE019B7CFE /* ShellHost */,);productName = ShellDemoApp;productReference = B1D199F3FD9C677BD245559E /* ShellDemoApp.app */;@@ -199,6 +211,7 @@isa = PBXResourcesBuildPhase;buildActionMask = 2147483647;files = (+ C12D9CC70DEF69CCB48F44E7 /* Games in Resources */,F15D381F62331B5172AD6D22 /* Localizable.xcstrings in Resources */,);runOnlyForDeploymentPostprocessing = 0;@@ -210,6 +223,7 @@isa = PBXSourcesBuildPhase;buildActionMask = 2147483647;files = (+ FAE394E91FBBBC0FD28A1C39 /* HostDemo.swift in Sources */,2EEF6A8F9A7D58C09181EAB5 /* RealArt.swift in Sources */,D94D715334EE4F5E0CCBA788 /* SampleArt.swift in Sources */,E71FEFEAE303CA4343BBDE2E /* SampleData.swift in Sources */,@@ -224,6 +238,7 @@3E143B39E0F97A669D2F6EFF /* ShellAdditionalTests.swift in Sources */,2861C1407044359116FE0A66 /* ShellCaptureTests.swift in Sources */,DF097C40B129901722DD4DF3 /* ShellDemoUITests.swift in Sources */,+ 2BF462D88A6CE3993C4AEB9A /* ShellHostUITests.swift in Sources */,);runOnlyForDeploymentPostprocessing = 0;};@@ -309,6 +324,7 @@buildSettings = {ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;CODE_SIGN_IDENTITY = "iPhone Developer";+ INFOPLIST_FILE = ../Tests/ShellHostTests/Fixtures/Games/0100000000030000/DmGame.framework/Info.plist;LD_RUNPATH_SEARCH_PATHS = ("$(inherited)","@executable_path/Frameworks",@@ -340,6 +356,7 @@buildSettings = {ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;CODE_SIGN_IDENTITY = "iPhone Developer";+ INFOPLIST_FILE = ../Tests/ShellHostTests/Fixtures/Games/0100000000030000/DmGame.framework/Info.plist;LD_RUNPATH_SEARCH_PATHS = ("$(inherited)","@executable_path/Frameworks",@@ -487,6 +504,10 @@isa = XCSwiftPackageProductDependency;productName = ShellControllers;};+ D80A22588F977AEE019B7CFE /* ShellHost */ = {+ isa = XCSwiftPackageProductDependency;+ productName = ShellHost;+ };/* End XCSwiftPackageProductDependency section */};rootObject = D41A7603C6BA5BB604CCFDE4 /* Project object */;diff --git a/frontend-ios/Demo/project.yml b/frontend-ios/Demo/project.ymlindex 62ceb563..263f3d94 100644--- a/frontend-ios/Demo/project.yml+++ b/frontend-ios/Demo/project.yml@@ -25,11 +25,17 @@ targets:platform: iOSsources:- ../Sources/ShellDemo+ # The fixture bundles for --host, copied into the app as its Games folder. No game data, no pictures.+ - path: ../Tests/ShellHostTests/Fixtures/Games+ type: folder+ buildPhase: resourcesdependencies:- package: ShellUIproduct: ShellUI- package: ShellUIproduct: ShellControllers+ - package: ShellUI+ product: ShellHostShellDemoUITests:type: bundle.ui-testingplatform: iOSdiff --git a/frontend-ios/Package.swift b/frontend-ios/Package.swiftindex fe2a1a19..e6e001c2 100644--- a/frontend-ios/Package.swift+++ b/frontend-ios/Package.swift@@ -8,13 +8,17 @@ let package = Package(.library(name: "ShellUI", targets: ["ShellUI"]),// The controller adapter: GameController input turned into ShellInput, kept apart from the views..library(name: "ShellControllers", targets: ["ShellControllers"]),+ // The host layer behind the views: catalogue, settings, game data, cloud saves, log and the launcher seam.+ .library(name: "ShellHost", targets: ["ShellHost"]),.executable(name: "ShellDemo", targets: ["ShellDemo"])],targets: [.target(name: "ShellUI", resources: [.process("Resources")]),.target(name: "ShellControllers", dependencies: ["ShellUI"]),- .executableTarget(name: "ShellDemo", dependencies: ["ShellUI", "ShellControllers"], resources: [.process("Resources")]),+ .target(name: "ShellHost", dependencies: ["ShellUI", "ShellControllers"], resources: [.process("Resources")]),+ .executableTarget(name: "ShellDemo", dependencies: ["ShellUI", "ShellControllers", "ShellHost"], resources: [.process("Resources")]),.testTarget(name: "ShellUITests", dependencies: ["ShellUI"]),+ .testTarget(name: "ShellHostTests", dependencies: ["ShellHost", "ShellUI", "ShellControllers"], resources: [.copy("Fixtures")]),.testTarget(name: "ShellControllersTests", dependencies: ["ShellControllers", "ShellUI"])])diff --git a/frontend-ios/README.md b/frontend-ios/README.mdindex 9113e9dc..832675a6 100644--- a/frontend-ios/README.md+++ b/frontend-ios/README.md@@ -1,6 +1,6 @@# iOS shell views-A Swift 6 package for iOS and iPadOS 26 and later. `ShellUI` is the view layer of the multi-game shell described in Route C (#144). It renders what it is given and reports what the player does. It has no engine dependency, game launching, storage, document picker, networking or game-file access.+A Swift 6 package for iOS and iPadOS 26 and later. `ShellUI` is the view layer of the multi-game shell described in Route C (#144). It renders what it is given and reports what the player does. It has no engine dependency, game launching, storage, document picker, networking or game-file access. `ShellHost` is the layer behind it that does those things.## Run@@ -45,6 +45,41 @@ LibraryView(The caller returns changed values through `games`. The views keep no second copy.+## Host++`ShellHost` is a library for the real shell app and the demo. It turns real files into the view values and acts on `ShellActions`. `ShellUI` stays view-only. Main types: `ShellHostModel` (the `@Observable` model, its `actions` go to `LibraryView`) and `ShellHostView` (`LibraryView` on a model, plus the log sheet and a notice alert).++| Part | What it does | Mirrors |+| --- | --- | --- |+| `GameCatalogue` | Scans `Games/<title ID>/`: `game.manifest.json` (schema 1, `GameManifest`), `launcher.json` (`LauncherProfile`, `docs/launcher.schema.json`, also read from `<framework>/<manifest.launcher>`), the manifest's `.framework` folder, optional `banner.<ext>` and `icon.<ext>`. A bundle that cannot be read stays in the list as broken with a readable reason (manifest missing, damaged or of another schema, framework missing, settings list damaged, folder and title ID disagree). | `docs/launcher-c-plan.md`, Manifest and Discovery |+| `GameStateResolver` | Broken first, then needs app update (the manifest's `chain` differs from `HostEnvironment.chain`, or `min_os` is above the running OS), then needs game data, else playable. | the plan's playable, needsData, needsFramework and broken |+| `DataLocator` | The picked location first, then `Documents/games/<title ID>/`, each accepted only with a non-empty `romfs.img` or the manifest's `romfs_marker` (also under `romfs/`). A picked folder that lost its data falls through to the app folder. | `romfs_locate` in `dm/ios/Sources/main.m`, patch 0003's layout |+| `GameSettingsStore` | One `UserDefaults` suite per game (`dev.nx2apple.shell.game.<title ID>`), keys `launcher.<VAR>` holding strings. Only a value that differs from the tested default is stored, a saved value the game no longer offers reads as the default, and Reset forgets every saved choice. `SettingsPresenter` draws sections in the list's order and hides sub-settings (`needs`). | `dm/ios/Sources/LauncherSettings.swift` |+| `BookmarkStore` | A security-scoped bookmark in the game's suite: `pickedDataBookmark` for game data, `cloudSavesBookmark` for the cloud-save folder. Written with the picker's scope, kept only if it resolves again, scope held once resolved, a stale one reported so the shell asks again, a refreshed one rewritten. No sync logic. | `dm/ios/Sources/DataBookmark.m` |+| `FolderPicker` | `DocumentFolderPicker` is a `UIDocumentPickerViewController` for a folder, opened in place. Tests use a fake. | `DocumentPicker` in `dm/ios/Sources/Launcher.swift` |+| Log | Show log reads the tail (256 KB) of `log.txt` in the game's data folder, else the app's folder, into a read-only sheet. | |+| Update | `ShellHostConfig.updateURL` is opened by Update app. | |+| Controllers | `ShellHostModel.startControllers()` runs `GamepadAdapter` and fills `controllers` (`ControllerInfo`) and `input` (`ShellInput`). | |++```swift+let config = ShellHostConfig(gamesRoot: gamesURL, appDataRoot: ShellHostConfig.defaultAppDataRoot(),+ environment: HostEnvironment(chain: dmshChain))+let model = ShellHostModel(config: config, launcher: StubGameLauncher(), picker: DocumentFolderPicker())+ShellHostView(model: model)+```++### Launching: the `GameLauncher` seam++```swift+public protocol GameLauncher: Sendable { @MainActor func launch(_ game: LaunchableGame) async throws }+```++Play on a playable game builds a `LaunchableGame` (title ID, name, manifest, bundle folder, framework URL, data folder, the app's `Documents/games/<title ID>/`, every `DM_*` value as a dictionary, the picked cloud-save folder) and calls `launch`. A thrown error is shown as the notice. `StubGameLauncher` only logs and throws `GameLaunchError.notAvailable` ("Launching is not available yet."). Route C's M2 (#144) plugs in the real launcher: it sets the environment from `environment` and the folders (`DM_PROFILE`, `DM_ROMFS`, `DM_SAVE`, `DM_TEMP`, `DM_SAVE_SYNC` from `cloudSavesURL`), `dlopen`s `frameworkURL` and starts the host with the manifest's modules. Nothing else in the host changes: pass it as `launcher:`. The engine and `dm/` are not part of this package.++### Host mode of the demo++`--host` runs `ShellHostView` on the fixture bundles in `Tests/ShellHostTests/Fixtures/Games` (the Xcode app carries them as its `Games` folder, the package executable takes `--games-dir <folder>`): playable, needs game data, app update (another chain and a newer OS) and broken (no framework, damaged manifest, manifest without keys, damaged settings list). They hold no game data and no pictures (`.gitignore` keeps images out, the tests draw their own). Marker files in a temporary app-data folder make most of them playable, and launching is the stub. `--select <title ID>` picks the first game.+## LayoutsOnly the available size decides, never the device model, idiom or orientation (`ShellLayout` in `LibraryView.swift`):diff --git a/frontend-ios/Sources/ShellDemo/HostDemo.swift b/frontend-ios/Sources/ShellDemo/HostDemo.swiftnew file mode 100644index 00000000..e859bfd2--- /dev/null+++ b/frontend-ios/Sources/ShellDemo/HostDemo.swift@@ -0,0 +1,53 @@+import SwiftUI+import ShellHost+import ShellUI++/// `--host`: the same views on `ShellHost` instead of the sample values. The games are the fixture bundles from+/// `Tests/ShellHostTests/Fixtures/Games` (in the app's `Games` folder, or `--games-dir <folder>`): valid ones, one built+/// for another chain, one for a newer OS, and broken ones. Each valid game gets an empty marker file in a temporary+/// app-data folder, which makes it playable, except "Quiet Fixture", which stays at "needs game data". Launching is the+/// stub. Choices go to throwaway defaults suites that are cleared at every start.+struct HostDemoScreen: View {+ @State private var model: ShellHostModel++ init() {+ let args = ProcessInfo.processInfo.arguments+ let fm = FileManager.default+ let gamesRoot: URL+ if let i = args.firstIndex(of: "--games-dir"), args.indices.contains(i + 1) {+ gamesRoot = URL(fileURLWithPath: args[i + 1], isDirectory: true)+ } else {+ gamesRoot = Bundle.main.url(forResource: "Games", withExtension: nil)+ ?? (fm.urls(for: .documentDirectory, in: .userDomainMask).first ?? fm.temporaryDirectory).appendingPathComponent("Games")+ }+ let appData = fm.temporaryDirectory.appendingPathComponent("shell-demo-appdata", isDirectory: true)+ try? fm.removeItem(at: appData)+ try? fm.createDirectory(at: appData, withIntermediateDirectories: true)+ let entries = GameCatalogue.scan(root: gamesRoot)+ for entry in entries { UserDefaults().removePersistentDomain(forName: Self.suite + entry.id) }+ for entry in entries where entry.problem == nil && entry.id != "0100000000080000" {+ guard let marker = entry.manifest?.romfsMarker else { continue }+ let file = appData.appendingPathComponent(entry.id).appendingPathComponent("romfs", isDirectory: true).appendingPathComponent(marker)+ try? fm.createDirectory(at: file.deletingLastPathComponent(), withIntermediateDirectories: true)+ fm.createFile(atPath: file.path, contents: Data())+ }+ let suite = Self.suite+ let config = ShellHostConfig(gamesRoot: gamesRoot, appDataRoot: appData,+ environment: HostEnvironment(chain: "b-3f9a2c"),+ updateURL: URL(string: "https://github.com/LNPANDY/NX2Apple/releases"),+ defaults: { UserDefaults(suiteName: suite + $0) ?? .standard })+ #if canImport(UIKit)+ _model = State(initialValue: ShellHostModel(config: config, picker: DocumentFolderPicker()))+ #else+ _model = State(initialValue: ShellHostModel(config: config))+ #endif+ }++ private static let suite = "dev.nx2apple.shell.demo."++ var body: some View {+ ShellHostView(model: model, initialSelection: ProcessInfo.processInfo.arguments.firstIndex(of: "--select")+ .flatMap { ProcessInfo.processInfo.arguments.indices.contains($0 + 1) ? ProcessInfo.processInfo.arguments[$0 + 1] : nil })+ .background(ShellPalette.background)+ }+}diff --git a/frontend-ios/Sources/ShellDemo/ShellDemoApp.swift b/frontend-ios/Sources/ShellDemo/ShellDemoApp.swiftindex d55f499b..e8e7aef4 100644--- a/frontend-ios/Sources/ShellDemo/ShellDemoApp.swift+++ b/frontend-ios/Sources/ShellDemo/ShellDemoApp.swift@@ -3,7 +3,11 @@ import ShellUIimport ShellControllers@main struct ShellDemoApp: App {- var body: some Scene { WindowGroup { DemoScreen() } }+ var body: some Scene {+ WindowGroup {+ if ProcessInfo.processInfo.arguments.contains("--host") { HostDemoScreen() } else { DemoScreen() }+ }+ }}/// The demo owns sample values. None of this state or callback simulation is part of ShellUI.diff --git a/frontend-ios/Sources/ShellHost/BookmarkStore.swift b/frontend-ios/Sources/ShellHost/BookmarkStore.swiftnew file mode 100644index 00000000..49e964f2--- /dev/null+++ b/frontend-ios/Sources/ShellHost/BookmarkStore.swift@@ -0,0 +1,75 @@+import Foundation++public enum BookmarkResolution: Equatable, Sendable {+ case none+ case url(URL)+ /// A bookmark exists but does not resolve (the app is signed differently): ask the player to pick again.+ case stale+}++/// One security-scoped bookmark in a game's defaults, as dm/ios/Sources/DataBookmark.m keeps them: the key+/// `pickedDataBookmark` for the game data and `cloudSavesBookmark` for the cloud-save folder. The bookmark is written+/// with the picker's scope switched on, must resolve again before it is kept, and its scope is held for the session once+/// resolved. A bookmark the system calls stale but still resolves is rewritten.+@MainActor public final class BookmarkStore {+ public static let gameDataKey = "pickedDataBookmark"+ public static let cloudSavesKey = "cloudSavesBookmark"++ private let defaults: UserDefaults+ private let key: String+ private var held: URL?++ public init(defaults: UserDefaults, key: String) {+ self.defaults = defaults+ self.key = key+ }++ #if os(macOS)+ private static let createOptions: URL.BookmarkCreationOptions = [.withSecurityScope]+ private static let resolveOptions: URL.BookmarkResolutionOptions = [.withSecurityScope]+ #else+ private static let createOptions: URL.BookmarkCreationOptions = []+ private static let resolveOptions: URL.BookmarkResolutionOptions = []+ #endif++ public var hasBookmark: Bool { (defaults.data(forKey: key)?.isEmpty ?? true) == false }++ private static func fresh(_ url: URL) -> Data? {+ // The scope the picker granted lasts while it is held, and a bookmark written without it stops resolving+ // from the next launch on.+ let scoped = url.startAccessingSecurityScopedResource()+ defer { if scoped { url.stopAccessingSecurityScopedResource() } }+ return try? url.bookmarkData(options: createOptions, includingResourceValuesForKeys: nil, relativeTo: nil)+ }++ /// Stores a bookmark for a URL the player just picked. False when the system refuses one or it does not resolve back.+ @discardableResult public func store(_ url: URL) -> Bool {+ guard let data = Self.fresh(url) else { return false }+ var stale = false+ guard (try? URL(resolvingBookmarkData: data, options: Self.resolveOptions, relativeTo: nil, bookmarkDataIsStale: &stale)) != nil else { return false }+ releaseScope()+ defaults.set(data, forKey: key)+ return true+ }++ public func resolve() -> BookmarkResolution {+ guard let data = defaults.data(forKey: key), !data.isEmpty else { return .none }+ var stale = false+ guard let url = try? URL(resolvingBookmarkData: data, options: Self.resolveOptions, relativeTo: nil, bookmarkDataIsStale: &stale) else { return .stale }+ if held?.path != url.path { releaseScope() }+ if held == nil { _ = url.startAccessingSecurityScopedResource(); held = url }+ if stale, let again = Self.fresh(url) { defaults.set(again, forKey: key) }+ return .url(url)+ }++ /// Forgets the choice.+ public func clear() {+ releaseScope()+ defaults.removeObject(forKey: key)+ }++ private func releaseScope() {+ held?.stopAccessingSecurityScopedResource()+ held = nil+ }+}diff --git a/frontend-ios/Sources/ShellHost/FolderPicker.swift b/frontend-ios/Sources/ShellHost/FolderPicker.swiftnew file mode 100644index 00000000..f7e30c42--- /dev/null+++ b/frontend-ios/Sources/ShellHost/FolderPicker.swift@@ -0,0 +1,54 @@+import Foundation+#if canImport(UIKit)+import UIKit+import UniformTypeIdentifiers+#endif++/// Asks the player for a folder. The shell's model only knows this protocol, so tests answer without UI.+public protocol FolderPicker: Sendable {+ /// The picked folder with the picker's security scope, or nil when the player cancelled.+ @MainActor func pickFolder() async -> URL?+}++/// No picker: always cancelled. The default on platforms without UIKit.+public struct NoFolderPicker: FolderPicker {+ public init() {}+ public func pickFolder() async -> URL? { nil }+}++#if canImport(UIKit)+/// `UIDocumentPickerViewController` for a folder, opened in place (not copied) as the per-game app does, so the+/// bookmark keeps pointing at the player's drive or iCloud Drive folder.+public struct DocumentFolderPicker: FolderPicker {+ public init() {}++ @MainActor public func pickFolder() async -> URL? {+ guard let presenter = Self.topViewController() else { return nil }+ return await withCheckedContinuation { continuation in+ let picker = UIDocumentPickerViewController(forOpeningContentTypes: [.folder], asCopy: false)+ picker.allowsMultipleSelection = false+ let delegate = Delegate(continuation: continuation)+ picker.delegate = delegate+ // The picker holds its delegate weakly: keep it for as long as the picker lives.+ objc_setAssociatedObject(picker, &Delegate.key, delegate, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)+ presenter.present(picker, animated: true)+ }+ }++ @MainActor private static func topViewController() -> UIViewController? {+ let scene = UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }.first { $0.activationState == .foregroundActive }+ var top = scene?.keyWindow?.rootViewController+ while let next = top?.presentedViewController { top = next }+ return top+ }++ private final class Delegate: NSObject, UIDocumentPickerDelegate {+ nonisolated(unsafe) static var key = 0+ private var continuation: CheckedContinuation<URL?, Never>?+ init(continuation: CheckedContinuation<URL?, Never>) { self.continuation = continuation }+ private func finish(_ url: URL?) { continuation?.resume(returning: url); continuation = nil }+ func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) { finish(urls.first) }+ func documentPickerWasCancelled(_ controller: UIDocumentPickerViewController) { finish(nil) }+ }+}+#endifdiff --git a/frontend-ios/Sources/ShellHost/GameCatalogue.swift b/frontend-ios/Sources/ShellHost/GameCatalogue.swiftnew file mode 100644index 00000000..3c0cdc5e--- /dev/null+++ b/frontend-ios/Sources/ShellHost/GameCatalogue.swift@@ -0,0 +1,149 @@+import Foundation+import ShellUI++/// What the shell and the app it runs in are, for the checks that need an app version: the shader chain it was built+/// with and the OS it runs on. A nil chain skips the chain check (the demo has no engine).+public struct HostEnvironment: Equatable, Sendable {+ public var chain: String?+ public var osVersion: OperatingSystemVersion+ public init(chain: String? = nil, osVersion: OperatingSystemVersion = ProcessInfo.processInfo.operatingSystemVersion) {+ self.chain = chain+ self.osVersion = osVersion+ }+ public static func == (a: Self, b: Self) -> Bool {+ a.chain == b.chain && a.osVersion.majorVersion == b.osVersion.majorVersion+ && a.osVersion.minorVersion == b.osVersion.minorVersion && a.osVersion.patchVersion == b.osVersion.patchVersion+ }+}++/// One folder under `Games/`, read: what its files say, or why they could not be read.+public struct CatalogueEntry: Equatable, Sendable, Identifiable {+ public var id: String+ public var directory: URL+ public var manifest: GameManifest?+ public var profile: LauncherProfile?+ public var bannerURL: URL?+ public var iconURL: URL?+ /// Set when the bundle cannot run at all, whatever the app or the data: the broken state.+ public var problem: GameProblem?++ public var title: String { manifest?.name ?? id }+ public var frameworkURL: URL? { manifest.map { directory.appendingPathComponent($0.framework, isDirectory: true) } }+}++/// Discovers games from a folder of bundles: `Games/<title ID>/` with `game.manifest.json`, `launcher.json`, the+/// manifest's `<name>.framework` and optional `banner.<ext>` and `icon.<ext>` pictures. Pure reads, no state.+public enum GameCatalogue {+ public static let imageExtensions = ["png", "jpg", "jpeg", "heic", "webp"]++ public static func scan(root: URL, fileManager fm: FileManager = .default) -> [CatalogueEntry] {+ let names = ((try? fm.contentsOfDirectory(atPath: root.path)) ?? []).filter { !$0.hasPrefix(".") }.sorted()+ var entries: [CatalogueEntry] = []+ for name in names {+ let dir = root.appendingPathComponent(name, isDirectory: true)+ var isDir: ObjCBool = false+ guard fm.fileExists(atPath: dir.path, isDirectory: &isDir), isDir.boolValue else { continue }+ entries.append(read(directory: dir, fileManager: fm))+ }+ return entries.sorted { ($0.manifest?.name ?? "\u{10FFFF}\($0.id)").localizedCaseInsensitiveCompare($1.manifest?.name ?? "\u{10FFFF}\($1.id)") == .orderedAscending }+ }++ public static func read(directory dir: URL, fileManager fm: FileManager = .default) -> CatalogueEntry {+ let id = dir.lastPathComponent+ var entry = CatalogueEntry(id: id, directory: dir, bannerURL: image(named: "banner", in: dir, fm), iconURL: image(named: "icon", in: dir, fm))+ do {+ guard let data = fm.contents(atPath: dir.appendingPathComponent("game.manifest.json").path) else {+ throw GameProblem(reason: hostText("Game manifest missing"), detail: hostText("This game's folder has no game.manifest.json."))+ }+ let manifest = try GameManifest.parse(data)+ entry.manifest = manifest+ guard manifest.titleID == id else {+ throw GameProblem(reason: hostText("Game files damaged"), detail: hostText("The folder is named \(id) but the manifest says \(manifest.titleID)."))+ }+ var isDir: ObjCBool = false+ guard fm.fileExists(atPath: dir.appendingPathComponent(manifest.framework).path, isDirectory: &isDir), isDir.boolValue else {+ throw GameProblem(reason: hostText("Game code missing"), detail: hostText("\(manifest.framework) is not in this game's folder. Install the game again."))+ }+ let direct = dir.appendingPathComponent("launcher.json")+ let inFramework = dir.appendingPathComponent(manifest.framework).appendingPathComponent(manifest.launcher)+ guard let launcherData = fm.contents(atPath: direct.path) ?? fm.contents(atPath: inFramework.path) else {+ throw GameProblem(reason: hostText("Settings list missing"), detail: hostText("This game has no launcher.json."))+ }+ let profile = try LauncherProfile.parse(launcherData)+ guard profile.game == manifest.titleID else {+ throw GameProblem(reason: hostText("Game files damaged"), detail: hostText("launcher.json is for \(profile.game), the manifest for \(manifest.titleID)."))+ }+ entry.profile = profile+ } catch let problem as GameProblem {+ entry.problem = problem+ } catch {+ entry.problem = GameProblem(reason: hostText("Game files damaged"), detail: error.localizedDescription)+ }+ return entry+ }++ private static func image(named base: String, in dir: URL, _ fm: FileManager) -> URL? {+ imageExtensions.map { dir.appendingPathComponent("\(base).\($0)") }.first { fm.fileExists(atPath: $0.path) }+ }+}++/// Where a game's data was found.+public enum DataSource: Equatable, Sendable {+ /// The app's own `Documents/games/<title ID>/`.+ case app+ /// A folder the player picked, through a bookmark.+ case picked+}++public struct DataResolution: Equatable, Sendable {+ /// The folder holding `romfs.img` or `romfs/<marker>`, or a picked `romfs.img`'s folder.+ public var url: URL?+ public var source: DataSource?+ /// A bookmark exists but no longer resolves (the app is signed differently now).+ public var pickedIsStale: Bool+ public var found: Bool { url != nil }+ public static let missing = DataResolution(url: nil, source: nil, pickedIsStale: false)+}++/// The same order as the per-game app's `romfs_locate` (dm/ios/Sources/main.m): the picked location first, then the+/// app's `Documents/games/<title ID>/`, each accepted only when it holds the game's image or marker.+public enum DataLocator {+ public static func locate(manifest: GameManifest, picked: BookmarkResolution, appFolder: URL, fileManager fm: FileManager = .default) -> DataResolution {+ var result = DataResolution.missing+ switch picked {+ case .stale: result.pickedIsStale = true+ case .url(let url):+ if let dir = holder(of: url, manifest: manifest, fm) { result.url = dir; result.source = .picked; return result }+ case .none: break+ }+ if let dir = holder(of: appFolder, manifest: manifest, fm) { result.url = dir; result.source = .app }+ return result+ }++ /// The folder in `url` (or `url` itself) that holds the game: an image, or a tree with the marker.+ static func holder(of url: URL, manifest: GameManifest, _ fm: FileManager) -> URL? {+ var isDir: ObjCBool = false+ guard fm.fileExists(atPath: url.path, isDirectory: &isDir) else { return nil }+ if !isDir.boolValue { return url.pathExtension == "img" && isNonEmpty(url, fm) ? url.deletingLastPathComponent() : nil }+ if isNonEmpty(url.appendingPathComponent("romfs.img"), fm) { return url }+ for tree in [url, url.appendingPathComponent("romfs", isDirectory: true)]+ where fm.fileExists(atPath: tree.appendingPathComponent(manifest.romfsMarker).path) { return url }+ return nil+ }++ private static func isNonEmpty(_ url: URL, _ fm: FileManager) -> Bool {+ ((try? fm.attributesOfItem(atPath: url.path)[.size]) as? NSNumber)?.intValue ?? 0 > 0+ }+}++/// Derives the state a tile shows from what is present: a bundle that cannot run is broken with its reason, a game+/// built for another chain or a newer OS needs an app update, a game without reachable data needs game data.+public enum GameStateResolver {+ public static func state(for entry: CatalogueEntry, data: DataResolution, environment: HostEnvironment) -> GameState {+ if let problem = entry.problem { return .broken(reason: problem.reason, detail: problem.detail) }+ guard let manifest = entry.manifest else { return .broken(reason: hostText("Game manifest missing")) }+ if let chain = environment.chain, chain != manifest.chain { return .needsAppUpdate }+ if let min = manifest.minOSVersion, !isVersion(environment.osVersion, atLeast: min) { return .needsAppUpdate }+ return data.found ? .playable : .needsGameData+ }+}diff --git a/frontend-ios/Sources/ShellHost/GameLauncher.swift b/frontend-ios/Sources/ShellHost/GameLauncher.swiftnew file mode 100644index 00000000..279a663d--- /dev/null+++ b/frontend-ios/Sources/ShellHost/GameLauncher.swift@@ -0,0 +1,49 @@+import Foundation+import os++/// Everything the engine needs to start one game, resolved by the host. The real launcher (Route C, M2: `DmShell.app`+/// dlopens the game's `DmGame.framework`, #144) turns it into the environment and `dm_main` arguments.+public struct LaunchableGame: Equatable, Sendable {+ public var titleID: String+ public var name: String+ public var manifest: GameManifest+ /// The game's bundle folder: manifest, launcher.json, framework.+ public var directory: URL+ public var frameworkURL: URL+ /// The folder with the game's data (romfs.img or romfs/), picked or the app's own.+ public var dataURL: URL+ /// The app's `Documents/games/<title ID>/`: save, temp, log.txt.+ public var appFolder: URL+ /// Every `DM_*` switch with the player's value or the tested default, as `launcher.<VAR>` would set it.+ public var environment: [String: String]+ /// The picked cloud-save folder, when cloud saves are on.+ public var cloudSavesURL: URL?+}++/// The seam between the shell and the engine. The shell calls `launch` when the player presses Play on a playable game.+/// It returns when the game has started (or never, if the process becomes the game), and throws a localized error the+/// shell shows.+public protocol GameLauncher: Sendable {+ @MainActor func launch(_ game: LaunchableGame) async throws+}++public enum GameLaunchError: LocalizedError, Equatable, Sendable {+ case notAvailable+ public var errorDescription: String? {+ switch self {+ case .notAvailable: hostText("Launching is not available yet.")+ }+ }+}++/// Only logs and reports that launching is not available yet. The real implementation arrives with M2.+public struct StubGameLauncher: GameLauncher {+ private let log: @Sendable (String) -> Void+ public init(log: @escaping @Sendable (String) -> Void = { Logger(subsystem: "dev.nx2apple.shell", category: "launch").info("\($0, privacy: .public)") }) {+ self.log = log+ }+ public func launch(_ game: LaunchableGame) async throws {+ log("launch requested for \(game.titleID) (\(game.name)), data at \(game.dataURL.path), \(game.environment.count) settings. The stub does not start it.")+ throw GameLaunchError.notAvailable+ }+}diff --git a/frontend-ios/Sources/ShellHost/GameManifest.swift b/frontend-ios/Sources/ShellHost/GameManifest.swiftnew file mode 100644index 00000000..c96f234d--- /dev/null+++ b/frontend-ios/Sources/ShellHost/GameManifest.swift@@ -0,0 +1,104 @@+import Foundation++/// `game.manifest.json`, schema 1, as the Route C plan defines it (docs/launcher-c-plan.md, "Manifest"). Written at+/// build time, read by the shell. A reader ignores keys it does not know.+public struct GameManifest: Decodable, Equatable, Sendable {+ public var schema: Int+ public var titleID: String+ public var name: String+ public var displayVersion: String+ public var packageVersion: String+ public var modules: [String]+ public var nroCount: Int+ /// `b-<hex>`: the shader translation chain the game was built with. The shell refuses a different one.+ public var chain: String+ /// `FR` or `FH`.+ public var loader: String+ public var framework: String+ public var frameworkExecutable: String+ public var imageMarker: String+ public var profile: String+ public var shaderMap: String+ public var launcher: String+ /// A path inside a RomFS folder that only this game's data has.+ public var romfsMarker: String+ public var romfsIdentity: String+ public var minOS: String+ public var icon: String?+ public var builtBy: String?+ public var builtAt: String?+ public var bytes: Int?++ public static let supportedSchema = 1++ enum CodingKeys: String, CodingKey {+ case schema, name, modules, chain, loader, framework, profile, launcher, icon, bytes+ case titleID = "title_id", displayVersion = "display_version", packageVersion = "package_version"+ case nroCount = "nro_count", frameworkExecutable = "framework_executable", imageMarker = "image_marker"+ case shaderMap = "shader_map", romfsMarker = "romfs_marker", romfsIdentity = "romfs_identity", minOS = "min_os"+ case builtBy = "built_by", builtAt = "built_at"+ }++ /// Decodes and validates. A problem carries a readable reason for the broken state.+ public static func parse(_ data: Data) throws(GameProblem) -> GameManifest {+ let manifest: GameManifest+ do { manifest = try JSONDecoder().decode(GameManifest.self, from: data) }+ catch { throw describe(error, file: "game.manifest.json", what: hostText("The game's manifest")) }+ guard manifest.schema == supportedSchema else {+ throw GameProblem(reason: hostText("Manifest not supported"),+ detail: hostText("game.manifest.json has schema \(manifest.schema), this app reads schema \(supportedSchema)."))+ }+ guard isTitleID(manifest.titleID) else {+ throw GameProblem(reason: hostText("Manifest damaged"), detail: hostText("title_id \"\(manifest.titleID)\" is not 16 hex digits."))+ }+ guard !manifest.modules.isEmpty else {+ throw GameProblem(reason: hostText("Manifest damaged"), detail: hostText("The manifest lists no modules."))+ }+ guard manifest.chain.hasPrefix("b-"), manifest.chain.count > 2, manifest.chain.dropFirst(2).allSatisfy(\.isHexDigit) else {+ throw GameProblem(reason: hostText("Manifest damaged"), detail: hostText("chain \"\(manifest.chain)\" is not of the form b-<hex>."))+ }+ guard ["FR", "FH"].contains(manifest.loader) else {+ throw GameProblem(reason: hostText("Manifest damaged"), detail: hostText("loader \"\(manifest.loader)\" is neither FR nor FH."))+ }+ guard manifest.framework.hasSuffix(".framework"), !manifest.framework.contains("/") else {+ throw GameProblem(reason: hostText("Manifest damaged"), detail: hostText("framework \"\(manifest.framework)\" is not a .framework name."))+ }+ return manifest+ }++ /// The minimum OS as a version, nil when it is not numeric.+ var minOSVersion: OperatingSystemVersion? { parseVersion(minOS) }+}++func isTitleID(_ text: String) -> Bool {+ text.count == 16 && text.allSatisfy { $0.isNumber || ("A"..."F").contains($0) }+}++func parseVersion(_ text: String) -> OperatingSystemVersion? {+ let parts = text.split(separator: ".").map { Int($0) }+ guard !parts.isEmpty, parts.count <= 3, !parts.contains(nil) else { return nil }+ let n = parts.compactMap { $0 }+ return OperatingSystemVersion(majorVersion: n[0], minorVersion: n.count > 1 ? n[1] : 0, patchVersion: n.count > 2 ? n[2] : 0)+}++func isVersion(_ a: OperatingSystemVersion, atLeast b: OperatingSystemVersion) -> Bool {+ (a.majorVersion, a.minorVersion, a.patchVersion) >= (b.majorVersion, b.minorVersion, b.patchVersion)+}++/// A decoding error as one readable sentence.+func describe(_ error: Error, file: String, what: String) -> GameProblem {+ let short = hostText("Game files damaged")+ guard let e = error as? DecodingError else { return GameProblem(reason: short, detail: "\(file): \(error.localizedDescription)") }+ func path(_ c: [CodingKey]) -> String { c.map { $0.stringValue }.joined(separator: ".") }+ switch e {+ case .keyNotFound(let key, let c):+ let at = c.codingPath.isEmpty ? "" : " (in \(path(c.codingPath)))"+ return GameProblem(reason: short, detail: hostText("\(file) has no \"\(key.stringValue)\"\(at)."))+ case .typeMismatch(_, let c), .valueNotFound(_, let c):+ return GameProblem(reason: short, detail: hostText("\(file) has a wrong or missing value at \"\(path(c.codingPath))\"."))+ case .dataCorrupted:+ return GameProblem(reason: short, detail: hostText("\(file) is not valid JSON."))+ @unknown default:+ return GameProblem(reason: short, detail: file)+ }+}diff --git a/frontend-ios/Sources/ShellHost/GameSettingsStore.swift b/frontend-ios/Sources/ShellHost/GameSettingsStore.swiftnew file mode 100644index 00000000..558efaa0--- /dev/null+++ b/frontend-ios/Sources/ShellHost/GameSettingsStore.swift@@ -0,0 +1,80 @@+import Foundation+import ShellUI++/// Per-game defaults, one suite per title ID. A suite keeps two games' choices apart without prefixes, and the keys+/// inside are the ones the per-game app uses in its standard defaults: `launcher.<VAR>`, `pickedDataBookmark`,+/// `cloudSavesBookmark`, so the engine can read the same names later.+public enum GameDefaults {+ public static let suitePrefix = "dev.nx2apple.shell.game."+ public static func suite(for titleID: String) -> UserDefaults {+ UserDefaults(suiteName: suitePrefix + titleID) ?? .standard+ }+}++/// 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.+public struct GameSettingsStore {+ public let profile: LauncherProfile+ private let defaults: UserDefaults++ public init(profile: LauncherProfile, defaults: UserDefaults) {+ self.profile = profile+ self.defaults = defaults+ }++ /// 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+ }++ 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.+ @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) }+ return true+ }++ /// Back to the profile's tested defaults.+ public func reset() {+ for setting in profile.settings { defaults.removeObject(forKey: setting.defaultsKey) }+ }++ public var hasModifiedSettings: Bool {+ profile.settings.contains { !$0.isDefault(value(of: $0)) }+ }+}++/// The profile and its values as the views' sections.+public enum SettingsPresenter {+ /// A row with `needs` (`<VAR>=<value>`) is drawn only while the row that sets that variable has that value. A row+ /// naming a variable the list does not have stays drawn. Sections come in the list's order.+ public static func sections(profile: LauncherProfile, values: [String: String]) -> [SettingSection] {+ func visible(_ s: LauncherSetting) -> Bool {+ guard let needs = s.needs, let eq = needs.firstIndex(of: "=") else { return true }+ guard let v = values[String(needs[..<eq])] else { return true }+ return v == String(needs[needs.index(after: eq)...])+ }+ var titles: [String] = []+ for s in profile.settings where !titles.contains(s.sectionTitle) { titles.append(s.sectionTitle) }+ return titles.compactMap { title in+ let rows = profile.settings.filter { $0.sectionTitle == title && visible($0) }.map { row($0, value: values[$0.env] ?? $0.def) }+ return rows.isEmpty ? nil : SettingSection(id: title, title: title, rows: rows)+ }+ }++ static func row(_ s: LauncherSetting, value: String) -> SettingRow {+ let kind: SettingKind+ switch s.kind {+ case "toggle": kind = .toggle(on: s.onValue, off: s.offValue)+ case "range": kind = .range(min: s.min ?? 0, max: s.max ?? 1, step: s.step ?? 0.1, unit: s.env.hasSuffix("SCALE") ? "×" : "")+ default: kind = .choice((s.options ?? []).map { SettingOption($0[0], $0[1]) })+ }+ return SettingRow(id: s.env, label: s.label, note: s.note, kind: kind, value: value)+ }+}diff --git a/frontend-ios/Sources/ShellHost/HostText.swift b/frontend-ios/Sources/ShellHost/HostText.swiftnew file mode 100644index 00000000..d66c2943--- /dev/null+++ b/frontend-ios/Sources/ShellHost/HostText.swift@@ -0,0 +1,15 @@+import Foundation++/// 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)+}++/// Why a game cannot be shown as playable: `reason` is the short line under the title, `detail` the sentence for the+/// How to fix sheet. Both are already localized.+public struct GameProblem: Error, Equatable, Sendable, LocalizedError {+ public var reason: String+ public var detail: String+ public init(reason: String, detail: String = "") { self.reason = reason; self.detail = detail }+ public var errorDescription: String? { detail.isEmpty ? reason : "\(reason): \(detail)" }+}diff --git a/frontend-ios/Sources/ShellHost/LauncherProfile.swift b/frontend-ios/Sources/ShellHost/LauncherProfile.swiftnew file mode 100644index 00000000..0db494f4--- /dev/null+++ b/frontend-ios/Sources/ShellHost/LauncherProfile.swift@@ -0,0 +1,89 @@+import Foundation++/// One row of `launcher.json` (docs/launcher.schema.json). The same fields, rules and defaults as the per-game app's+/// `Setting` in dm/ios/Sources/LauncherSettings.swift, so a value saved here means the same there.+public struct LauncherSetting: Decodable, Equatable, Sendable, Identifiable {+ public var env: String+ public var kind: String+ public var section: String?+ public var label: String+ public var note: String+ public var def: String+ public var needs: String?+ public var level: String?+ public var options: [[String]]?+ public var min: Double?+ public var max: Double?+ public var step: Double?+ public var on: String?+ public var off: String?+ public var id: String { env }+ public var sectionTitle: String { section ?? "Game" }+ public var onValue: String { on ?? "1" }+ public var offValue: String { off ?? "0" }++ enum CodingKeys: String, CodingKey { case env, kind, label, note, def = "default", section, needs, level, options, min, max, step, on, off }++ /// A range compares as numbers: a slider writes 1.00 for 1.0.+ public func isDefault(_ v: String) -> Bool {+ kind == "range" ? abs((Double(v) ?? .nan) - (Double(def) ?? .nan)) < 1e-6 : v == def+ }++ /// A saved value the game still offers.+ public func accepts(_ v: String) -> Bool {+ switch kind {+ case "choice": return options?.contains { $0.first == v } ?? false+ case "range":+ guard !v.contains(where: { $0 == "x" || $0 == "X" }), let n = Double(v), n.isFinite, let lo = min, let hi = max else { return false }+ return n >= lo && n <= hi+ case "toggle": return v == onValue || v == offValue+ default: return true+ }+ }++ /// The UserDefaults key the engine's launcher reads: `launcher.<VAR>`.+ public var defaultsKey: String { "launcher." + env }+}++/// `launcher.json`, schema 1.+public struct LauncherProfile: Decodable, Equatable, Sendable {+ public var schema: Int?+ public var game: String+ public var settings: [LauncherSetting]++ public static func parse(_ data: Data) throws(GameProblem) -> LauncherProfile {+ let profile: LauncherProfile+ do { profile = try JSONDecoder().decode(LauncherProfile.self, from: data) }+ catch { throw describe(error, file: "launcher.json", what: hostText("The settings list")) }+ let reason = hostText("Settings list damaged")+ if let schema = profile.schema, schema != 1 {+ throw GameProblem(reason: hostText("Settings list not supported"), detail: hostText("launcher.json has schema \(schema), this app reads schema 1."))+ }+ guard isTitleID(profile.game) else {+ throw GameProblem(reason: reason, detail: hostText("game \"\(profile.game)\" in launcher.json is not 16 hex digits."))+ }+ var seen = Set<String>()+ for s in profile.settings {+ guard s.env.hasPrefix("DM_"), s.env.dropFirst(3).allSatisfy({ $0.isUppercase || $0.isNumber || $0 == "_" }), s.env.count > 3 else {+ throw GameProblem(reason: reason, detail: hostText("\"\(s.env)\" is not a DM_ switch."))+ }+ guard seen.insert(s.env).inserted else {+ throw GameProblem(reason: reason, detail: hostText("\(s.env) appears twice in launcher.json."))+ }+ switch s.kind {+ case "choice":+ guard let o = s.options, !o.isEmpty, o.allSatisfy({ $0.count == 2 }) else {+ throw GameProblem(reason: reason, detail: hostText("\(s.env) is a choice without [value, label] options."))+ }+ case "range":+ guard s.min != nil, s.max != nil, let step = s.step, step > 0 else {+ throw GameProblem(reason: reason, detail: hostText("\(s.env) is a range without min, max and step."))+ }+ case "toggle": break+ default:+ throw GameProblem(reason: reason, detail: hostText("\(s.env) has the unknown kind \"\(s.kind)\"."))+ }+ }+ return profile+ }+}diff --git a/frontend-ios/Sources/ShellHost/LogReader.swift b/frontend-ios/Sources/ShellHost/LogReader.swiftnew file mode 100644index 00000000..aba6fea3--- /dev/null+++ b/frontend-ios/Sources/ShellHost/LogReader.swift@@ -0,0 +1,27 @@+import Foundation++/// A game's `log.txt` for the read-only log view.+public struct LogPresentation: Identifiable, Equatable, Sendable {+ public var id: String { gameID }+ public var gameID: String+ public var title: String+ /// Nil when the game has no log yet.+ public var text: String?+ /// True when only the end of a long log is shown.+ public var truncated: Bool+}++public enum LogReader {+ public static let maxBytes = 256 * 1024++ /// The tail of `<folder>/log.txt`, nil when there is none. The file is read in one piece: logs stay small, and a+ /// very long one shows its last `maxBytes`.+ public static func read(_ url: URL, maxBytes: Int = LogReader.maxBytes) -> (text: String, truncated: Bool)? {+ guard let handle = try? FileHandle(forReadingFrom: url) else { return nil }+ defer { try? handle.close() }+ guard let size = try? handle.seekToEnd() else { return nil }+ let start = size > UInt64(maxBytes) ? size - UInt64(maxBytes) : 0+ guard (try? handle.seek(toOffset: start)) != nil, let data = try? handle.readToEnd() else { return nil }+ return (String(decoding: data, as: UTF8.self), start > 0)+ }+}diff --git a/frontend-ios/Sources/ShellHost/Resources/Localizable.xcstrings b/frontend-ios/Sources/ShellHost/Resources/Localizable.xcstringsnew file mode 100644index 00000000..b6231b79--- /dev/null+++ b/frontend-ios/Sources/ShellHost/Resources/Localizable.xcstrings@@ -0,0 +1,506 @@+{+ "sourceLanguage": "en",+ "strings": {+ "\"%@\" is not a DM_ switch.": {+ "localizations": {+ "en": {+ "stringUnit": {+ "state": "translated",+ "value": "\"%@\" is not a DM_ switch."+ }+ }+ }+ },+ "%@ appears twice in launcher.json.": {+ "localizations": {+ "en": {+ "stringUnit": {+ "state": "translated",+ "value": "%@ appears twice in launcher.json."+ }+ }+ }+ },+ "%@ has a wrong or missing value at \"%@\".": {+ "localizations": {+ "en": {+ "stringUnit": {+ "state": "translated",+ "value": "%@ has a wrong or missing value at \"%@\"."+ }+ }+ }+ },+ "%@ has no \"%@\"%@.": {+ "localizations": {+ "en": {+ "stringUnit": {+ "state": "translated",+ "value": "%@ has no \"%@\"%@."+ }+ }+ }+ },+ "%@ has the unknown kind \"%@\".": {+ "localizations": {+ "en": {+ "stringUnit": {+ "state": "translated",+ "value": "%@ has the unknown kind \"%@\"."+ }+ }+ }+ },+ "%@ is a choice without [value, label] options.": {+ "localizations": {+ "en": {+ "stringUnit": {+ "state": "translated",+ "value": "%@ is a choice without [value, label] options."+ }+ }+ }+ },+ "%@ is a range without min, max and step.": {+ "localizations": {+ "en": {+ "stringUnit": {+ "state": "translated",+ "value": "%@ is a range without min, max and step."+ }+ }+ }+ },+ "%@ is not in this game's folder. Install the game again.": {+ "localizations": {+ "en": {+ "stringUnit": {+ "state": "translated",+ "value": "%@ is not in this game's folder. Install the game again."+ }+ }+ }+ },+ "%@ is not valid JSON.": {+ "localizations": {+ "en": {+ "stringUnit": {+ "state": "translated",+ "value": "%@ is not valid JSON."+ }+ }+ }+ },+ "%lld additional content packs": {+ "localizations": {+ "en": {+ "stringUnit": {+ "state": "translated",+ "value": "%lld additional content packs"+ }+ }+ }+ },+ "1 additional content pack": {+ "localizations": {+ "en": {+ "stringUnit": {+ "state": "translated",+ "value": "1 additional content pack"+ }+ }+ }+ },+ "Choose a RomFS folder or romfs.img on this device, an external drive, or iCloud Drive.": {+ "localizations": {+ "en": {+ "stringUnit": {+ "state": "translated",+ "value": "Choose a RomFS folder or romfs.img on this device, an external drive, or iCloud Drive."+ }+ }+ }+ },+ "Done": {+ "localizations": {+ "en": {+ "stringUnit": {+ "state": "translated",+ "value": "Done"+ }+ }+ }+ },+ "Game code missing": {+ "localizations": {+ "en": {+ "stringUnit": {+ "state": "translated",+ "value": "Game code missing"+ }+ }+ }+ },+ "Game files damaged": {+ "localizations": {+ "en": {+ "stringUnit": {+ "state": "translated",+ "value": "Game files damaged"+ }+ }+ }+ },+ "Game manifest missing": {+ "localizations": {+ "en": {+ "stringUnit": {+ "state": "translated",+ "value": "Game manifest missing"+ }+ }+ }+ },+ "Launching is not available yet.": {+ "localizations": {+ "en": {+ "stringUnit": {+ "state": "translated",+ "value": "Launching is not available yet."+ }+ }+ }+ },+ "Manifest damaged": {+ "localizations": {+ "en": {+ "stringUnit": {+ "state": "translated",+ "value": "Manifest damaged"+ }+ }+ }+ },+ "Manifest not supported": {+ "localizations": {+ "en": {+ "stringUnit": {+ "state": "translated",+ "value": "Manifest not supported"+ }+ }+ }+ },+ "No additional content": {+ "localizations": {+ "en": {+ "stringUnit": {+ "state": "translated",+ "value": "No additional content"+ }+ }+ }+ },+ "No game data for %@ was found in that folder.": {+ "localizations": {+ "en": {+ "stringUnit": {+ "state": "translated",+ "value": "No game data for %@ was found in that folder."+ }+ }+ }+ },+ "No update address is set up for this app.": {+ "localizations": {+ "en": {+ "stringUnit": {+ "state": "translated",+ "value": "No update address is set up for this app."+ }+ }+ }+ },+ "OK": {+ "localizations": {+ "en": {+ "stringUnit": {+ "state": "translated",+ "value": "OK"+ }+ }+ }+ },+ "Only the end of the log is shown.": {+ "localizations": {+ "en": {+ "stringUnit": {+ "state": "translated",+ "value": "Only the end of the log is shown."+ }+ }+ }+ },+ "Player %@": {+ "localizations": {+ "en": {+ "stringUnit": {+ "state": "translated",+ "value": "Player %@"+ }+ }+ }+ },+ "Settings list damaged": {+ "localizations": {+ "en": {+ "stringUnit": {+ "state": "translated",+ "value": "Settings list damaged"+ }+ }+ }+ },+ "Settings list missing": {+ "localizations": {+ "en": {+ "stringUnit": {+ "state": "translated",+ "value": "Settings list missing"+ }+ }+ }+ },+ "Settings list not supported": {+ "localizations": {+ "en": {+ "stringUnit": {+ "state": "translated",+ "value": "Settings list not supported"+ }+ }+ }+ },+ "Shell": {+ "localizations": {+ "en": {+ "stringUnit": {+ "state": "translated",+ "value": "Shell"+ }+ }+ }+ },+ "That folder could not be remembered. Try a different one.": {+ "localizations": {+ "en": {+ "stringUnit": {+ "state": "translated",+ "value": "That folder could not be remembered. Try a different one."+ }+ }+ }+ },+ "That location could not be remembered. Try a different one.": {+ "localizations": {+ "en": {+ "stringUnit": {+ "state": "translated",+ "value": "That location could not be remembered. Try a different one."+ }+ }+ }+ },+ "The folder is named %@ but the manifest says %@.": {+ "localizations": {+ "en": {+ "stringUnit": {+ "state": "translated",+ "value": "The folder is named %@ but the manifest says %@."+ }+ }+ }+ },+ "The folder you chose before is no longer readable. Please choose it again.": {+ "localizations": {+ "en": {+ "stringUnit": {+ "state": "translated",+ "value": "The folder you chose before is no longer readable. Please choose it again."+ }+ }+ }+ },+ "The game's manifest": {+ "localizations": {+ "en": {+ "stringUnit": {+ "state": "translated",+ "value": "The game's manifest"+ }+ }+ }+ },+ "The location you picked before is no longer readable (the app was signed differently). Please choose it again.": {+ "localizations": {+ "en": {+ "stringUnit": {+ "state": "translated",+ "value": "The location you picked before is no longer readable (the app was signed differently). Please choose it again."+ }+ }+ }+ },+ "The manifest lists no modules.": {+ "localizations": {+ "en": {+ "stringUnit": {+ "state": "translated",+ "value": "The manifest lists no modules."+ }+ }+ }+ },+ "The settings list": {+ "localizations": {+ "en": {+ "stringUnit": {+ "state": "translated",+ "value": "The settings list"+ }+ }+ }+ },+ "This app's folder": {+ "localizations": {+ "en": {+ "stringUnit": {+ "state": "translated",+ "value": "This app's folder"+ }+ }+ }+ },+ "This app's folder has no data for this game yet. Copy it to games/%@ in this app's folder in Files.": {+ "localizations": {+ "en": {+ "stringUnit": {+ "state": "translated",+ "value": "This app's folder has no data for this game yet. Copy it to games/%@ in this app's folder in Files."+ }+ }+ }+ },+ "This game has no launcher.json.": {+ "localizations": {+ "en": {+ "stringUnit": {+ "state": "translated",+ "value": "This game has no launcher.json."+ }+ }+ }+ },+ "This game has no log yet. It appears after the game has run.": {+ "localizations": {+ "en": {+ "stringUnit": {+ "state": "translated",+ "value": "This game has no log yet. It appears after the game has run."+ }+ }+ }+ },+ "This game's folder has no game.manifest.json.": {+ "localizations": {+ "en": {+ "stringUnit": {+ "state": "translated",+ "value": "This game's folder has no game.manifest.json."+ }+ }+ }+ },+ "chain \"%@\" is not of the form b-<hex>.": {+ "localizations": {+ "en": {+ "stringUnit": {+ "state": "translated",+ "value": "chain \"%@\" is not of the form b-<hex>."+ }+ }+ }+ },+ "framework \"%@\" is not a .framework name.": {+ "localizations": {+ "en": {+ "stringUnit": {+ "state": "translated",+ "value": "framework \"%@\" is not a .framework name."+ }+ }+ }+ },+ "game \"%@\" in launcher.json is not 16 hex digits.": {+ "localizations": {+ "en": {+ "stringUnit": {+ "state": "translated",+ "value": "game \"%@\" in launcher.json is not 16 hex digits."+ }+ }+ }+ },+ "game.manifest.json has schema %lld, this app reads schema %lld.": {+ "localizations": {+ "en": {+ "stringUnit": {+ "state": "translated",+ "value": "game.manifest.json has schema %lld, this app reads schema %lld."+ }+ }+ }+ },+ "launcher.json has schema %lld, this app reads schema 1.": {+ "localizations": {+ "en": {+ "stringUnit": {+ "state": "translated",+ "value": "launcher.json has schema %lld, this app reads schema 1."+ }+ }+ }+ },+ "launcher.json is for %@, the manifest for %@.": {+ "localizations": {+ "en": {+ "stringUnit": {+ "state": "translated",+ "value": "launcher.json is for %@, the manifest for %@."+ }+ }+ }+ },+ "loader \"%@\" is neither FR nor FH.": {+ "localizations": {+ "en": {+ "stringUnit": {+ "state": "translated",+ "value": "loader \"%@\" is neither FR nor FH."+ }+ }+ }+ },+ "title_id \"%@\" is not 16 hex digits.": {+ "localizations": {+ "en": {+ "stringUnit": {+ "state": "translated",+ "value": "title_id \"%@\" is not 16 hex digits."+ }+ }+ }+ }+ },+ "version": "1.0"+}\ No newline at end of filediff --git a/frontend-ios/Sources/ShellHost/ShellHostModel.swift b/frontend-ios/Sources/ShellHost/ShellHostModel.swiftnew file mode 100644index 00000000..609bcd8d--- /dev/null+++ b/frontend-ios/Sources/ShellHost/ShellHostModel.swift@@ -0,0 +1,276 @@+import Foundation+import Observation+import ShellControllers+import ShellUI+#if canImport(UIKit)+import UIKit+#endif++/// Where the host finds things. Everything the model touches outside itself is here, so tests point it at a temporary folder.+public struct ShellHostConfig: Sendable {+ /// `Games/`: one `<title ID>/` bundle folder per game.+ public var gamesRoot: URL+ /// The app's `Documents/games/`: `<title ID>/` holds a game's data, save, temp and log.txt (patch 0003's layout).+ public var appDataRoot: URL+ public var environment: HostEnvironment+ /// Opened by "Update app". Nil: the shell says no address is configured.+ public var updateURL: URL?+ public var defaults: @Sendable (String) -> UserDefaults+ public var openURL: @MainActor @Sendable (URL) -> Void++ public init(gamesRoot: URL, appDataRoot: URL, environment: HostEnvironment = HostEnvironment(), updateURL: URL? = nil,+ defaults: @escaping @Sendable (String) -> UserDefaults = GameDefaults.suite(for:),+ openURL: @escaping @MainActor @Sendable (URL) -> Void = ShellHostConfig.systemOpen) {+ self.gamesRoot = gamesRoot+ self.appDataRoot = appDataRoot+ self.environment = environment+ self.updateURL = updateURL+ self.defaults = defaults+ self.openURL = openURL+ }++ @MainActor public static func systemOpen(_ url: URL) {+ #if canImport(UIKit)+ UIApplication.shared.open(url)+ #endif+ }++ /// The app's `Documents/games/`.+ public static func defaultAppDataRoot() -> URL {+ (FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first ?? FileManager.default.temporaryDirectory)+ .appendingPathComponent("games", isDirectory: true)+ }+}++/// The host behind the views: turns the catalogue, the saved settings, the picked folders and the controllers into+/// `GameDetail` values, and acts on `ShellActions`. `ShellUI` stays view-only, every file is read here.+@MainActor @Observable public final class ShellHostModel {+ public private(set) var details: [GameDetail] = []+ public private(set) var entries: [CatalogueEntry] = []+ public private(set) var controllers: [ControllerInfo] = []+ public private(set) var input: ShellInput?+ /// A short message the host view shows as an alert.+ public var notice: String?+ /// The log the host view shows in a read-only sheet.+ public var log: LogPresentation?++ @ObservationIgnored private let config: ShellHostConfig+ @ObservationIgnored private let launcher: any GameLauncher+ @ObservationIgnored private let picker: any FolderPicker+ @ObservationIgnored private let adapter = GamepadAdapter()+ @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()) {+ self.config = config+ self.launcher = launcher+ self.picker = picker+ reload()+ }++ // MARK: Catalogue++ /// Reads the games folder again.+ public func reload() {+ entries = GameCatalogue.scan(root: config.gamesRoot)+ details = entries.map(detail(for:))+ }++ private func refresh(_ id: String) {+ guard let e = entries.firstIndex(where: { $0.id == id }), let d = details.firstIndex(where: { $0.id == id }) else { return }+ details[d] = detail(for: entries[e])+ }++ private func entry(_ id: String) -> CatalogueEntry? { entries.first { $0.id == id } }++ public func appFolder(for id: String) -> URL { config.appDataRoot.appendingPathComponent(id, isDirectory: true) }++ private func dataStore(_ id: String) -> BookmarkStore {+ if let s = dataStores[id] { return s }+ let s = BookmarkStore(defaults: config.defaults(id), key: BookmarkStore.gameDataKey)+ dataStores[id] = s+ return s+ }++ private func cloudStore(_ id: String) -> BookmarkStore {+ if let s = cloudStores[id] { return s }+ let s = BookmarkStore(defaults: config.defaults(id), key: BookmarkStore.cloudSavesKey)+ cloudStores[id] = s+ return s+ }++ 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))+ }++ private func image(_ url: URL?) -> Artwork? {+ guard let url else { return nil }+ if let a = artwork[url] { return a }+ guard let bytes = try? Data(contentsOf: url), let a = Artwork(id: url.path, data: bytes) else { return nil }+ artwork[url] = a+ return a+ }++ private func detail(for entry: CatalogueEntry) -> GameDetail {+ let data = data(for: entry)+ let state = GameStateResolver.state(for: entry, data: data, environment: config.environment)+ let tile = GameTile(id: entry.id, title: entry.title, subtitle: entry.manifest?.displayVersion ?? "",+ banner: image(entry.bannerURL), icon: image(entry.iconURL), state: state)+ 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))+ var cloud: String?+ var cloudNote = ""+ switch cloudStore(entry.id).resolve() {+ case .url(let url): cloud = url.lastPathComponent+ case .stale: cloudNote = hostText("The folder you chose before is no longer readable. Please choose it again.")+ case .none: break+ }+ 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)+ }++ private func dataSource(_ data: DataResolution) -> String {+ switch data.source {+ case .app: hostText("This app's folder")+ case .picked: data.url?.lastPathComponent ?? ""+ case nil: ""+ }+ }++ private func dataNote(_ data: DataResolution, found: Bool) -> String {+ if data.pickedIsStale && !found { return hostText("The location you picked before is no longer readable (the app was signed differently). Please choose it again.") }+ return found ? "" : hostText("Choose a RomFS folder or romfs.img on this device, an external drive, or iCloud Drive.")+ }++ private func dlc(_ data: DataResolution) -> String {+ guard let url = data.url else { return hostText("No additional content") }+ let names = (try? FileManager.default.contentsOfDirectory(atPath: url.appendingPathComponent("aoc").path))?.filter { !$0.hasPrefix(".") } ?? []+ switch names.count {+ case 0: return hostText("No additional content")+ case 1: return hostText("1 additional content pack")+ default: return hostText("\(names.count) additional content packs")+ }+ }++ // MARK: Actions++ /// The closures for `LibraryView`.+ public var actions: ShellActions {+ ShellActions(+ onPlay: { [weak self] id in self?.play(id) },+ onChange: { [weak self] id, setting, value in self?.change(id, setting: setting, value: value) },+ onPickGameData: { [weak self] id in self?.pickGameData(id) },+ onUseAppData: { [weak self] id in self?.useAppData(id) },+ onPickCloudSaves: { [weak self] id in self?.pickCloudSaves(id) },+ 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() })+ }++ 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)+ refresh(id)+ }++ public func resetDefaults(_ id: String) {+ guard let profile = entry(id)?.profile else { return }+ GameSettingsStore(profile: profile, defaults: config.defaults(id)).reset()+ refresh(id)+ }++ public func pickGameData(_ id: String) {+ Task { await pickGameDataNow(id) }+ }++ func pickGameDataNow(_ id: String) async {+ guard let url = await picker.pickFolder() else { return }+ guard dataStore(id).store(url) else {+ notice = hostText("That location could not be remembered. Try a different one.")+ return+ }+ refresh(id)+ if let game = details.first(where: { $0.id == id })?.game, game.state == .needsGameData {+ notice = hostText("No game data for \(game.title) was found in that folder.")+ }+ }++ public func useAppData(_ id: String) {+ dataStore(id).clear()+ refresh(id)+ if details.first(where: { $0.id == id })?.game.state == .needsGameData {+ notice = hostText("This app's folder has no data for this game yet. Copy it to games/\(id) in this app's folder in Files.")+ }+ }++ public func pickCloudSaves(_ id: String) {+ Task { await pickCloudSavesNow(id) }+ }++ func pickCloudSavesNow(_ id: String) async {+ guard let url = await picker.pickFolder() else { return }+ if !cloudStore(id).store(url) { notice = hostText("That folder could not be remembered. Try a different one.") }+ refresh(id)+ }++ public func disableCloudSaves(_ id: String) {+ cloudStore(id).clear()+ refresh(id)+ }++ public func showLog(_ id: String) {+ guard let entry = entry(id) else { return }+ let app = appFolder(for: id)+ let folders = [data(for: entry).url, app].compactMap { $0 }+ let found = folders.lazy.compactMap { LogReader.read($0.appendingPathComponent("log.txt")) }.first+ log = LogPresentation(gameID: id, title: entry.title, text: found?.text, truncated: found?.truncated ?? false)+ }++ public func appUpdate() {+ guard let url = config.updateURL else { notice = hostText("No update address is set up for this app."); return }+ config.openURL(url)+ }++ public func play(_ id: String) {+ Task { await playNow(id) }+ }++ func playNow(_ id: String) async {+ 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 }+ 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)+ do { try await launcher.launch(game) }+ catch { notice = error.localizedDescription }+ }++ // MARK: Controllers++ /// Starts reading GameController: the connected controllers become `controllers`, their buttons `input`.+ public func startControllers() {+ adapter.onInput = { [weak self] action, device in+ guard let self else { return }+ self.input = ShellInput(sequence: (self.input?.sequence ?? 0) + 1, action: action, device: device)+ }+ adapter.onControllersChange = { [weak self] connected in+ self?.controllers = connected.map(Self.info(for:))+ }+ adapter.start()+ }++ public func stopControllers() { adapter.stop() }++ static func info(for c: ConnectedController) -> ControllerInfo {+ ControllerInfo(id: c.id, name: c.name, player: hostText("Player \(c.player)"), batteryPercent: c.batteryPercent, charging: c.charging)+ }+}diff --git a/frontend-ios/Sources/ShellHost/ShellHostView.swift b/frontend-ios/Sources/ShellHost/ShellHostView.swiftnew file mode 100644index 00000000..26399e6e--- /dev/null+++ b/frontend-ios/Sources/ShellHost/ShellHostView.swift@@ -0,0 +1,54 @@+import SwiftUI+import ShellUI++/// `LibraryView` on a `ShellHostModel`: the real shell screen, plus the read-only log sheet and the notice alert. The+/// launch arguments of the demo (initial selection and so on) are not part of it.+public struct ShellHostView: View {+ @Bindable private var model: ShellHostModel+ private let initialSelection: String?++ public init(model: ShellHostModel, initialSelection: String? = nil) {+ self.model = model+ self.initialSelection = initialSelection+ }++ public var body: some View {+ LibraryView(games: model.details, controllers: model.controllers, actions: model.actions, input: model.input,+ initialSelection: initialSelection)+ .sheet(item: $model.log) { LogView(log: $0) }+ .alert(Text(verbatim: hostText("Shell")), isPresented: Binding(get: { model.notice != nil }, set: { if !$0 { model.notice = nil } })) {+ Button(hostText("OK")) { model.notice = nil }+ } message: { Text(model.notice ?? "") }+ .onAppear { model.startControllers() }+ .onDisappear { model.stopControllers() }+ }+}++/// A game's log, read-only.+struct LogView: View {+ let log: LogPresentation+ @Environment(\.dismiss) private var dismiss++ var body: some View {+ NavigationStack {+ ScrollView {+ VStack(alignment: .leading, spacing: 8) {+ if log.truncated { Text(hostText("Only the end of the log is shown.")).font(.footnote).foregroundStyle(.secondary) }+ Text(verbatim: log.text ?? hostText("This game has no log yet. It appears after the game has run."))+ .font(.system(.footnote, design: .monospaced))+ .foregroundStyle(log.text == nil ? .secondary : .primary)+ .textSelection(.enabled)+ .frame(maxWidth: .infinity, alignment: .leading)+ }+ .padding()+ }+ .navigationTitle(log.title)+ #if os(iOS)+ .navigationBarTitleDisplayMode(.inline)+ #endif+ .toolbar { ToolbarItem(placement: .confirmationAction) { Button(hostText("Done")) { dismiss() }.accessibilityIdentifier("log.close") } }+ }+ .preferredColorScheme(.dark)+ .accessibilityIdentifier("log.sheet")+ }+}diff --git a/frontend-ios/Tests/ShellHostTests/BookmarkStoreTests.swift b/frontend-ios/Tests/ShellHostTests/BookmarkStoreTests.swiftnew file mode 100644index 00000000..076b611b--- /dev/null+++ b/frontend-ios/Tests/ShellHostTests/BookmarkStoreTests.swift@@ -0,0 +1,72 @@+import Foundation+import Testing+@testable import ShellHost++@MainActor @Suite struct BookmarkStoreTests {+ private func makeStore(_ box: Sandbox, key: String = BookmarkStore.gameDataKey) -> BookmarkStore {+ BookmarkStore(defaults: box.defaults(Fixtures.orbit), key: key)+ }++ @Test func nothingStoredResolvesToNone() throws {+ let box = try Sandbox()+ let store = makeStore(box)+ #expect(store.resolve() == .none)+ #expect(!store.hasBookmark)+ }++ @Test func storesResolvesAndClears() throws {+ let box = try Sandbox()+ let folder = box.root.appendingPathComponent("Drive/Data", isDirectory: true)+ try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)+ let store = makeStore(box)+ #expect(store.store(folder))+ #expect(store.hasBookmark)+ guard case .url(let url) = store.resolve() else { Issue.record("did not resolve"); return }+ #expect(url.resolvingSymlinksInPath().path == folder.resolvingSymlinksInPath().path)+ // A second store over the same suite (a relaunch) resolves it too.+ guard case .url = makeStore(box).resolve() else { Issue.record("did not resolve after relaunch"); return }+ store.clear()+ #expect(store.resolve() == .none)+ #expect(!store.hasBookmark)+ }++ @Test func aMissingFolderIsNotBookmarked() throws {+ let box = try Sandbox()+ let store = makeStore(box)+ #expect(!store.store(box.root.appendingPathComponent("not-there")))+ #expect(!store.hasBookmark)+ }++ @Test func aBookmarkThatDoesNotResolveIsStale() throws {+ let box = try Sandbox()+ box.defaults(Fixtures.orbit).set(Data("not a bookmark".utf8), forKey: BookmarkStore.gameDataKey)+ let store = makeStore(box)+ #expect(store.resolve() == .stale)+ #expect(store.hasBookmark, "the data stays, the player may install the same signature again")+ }++ @Test func dataAndCloudKeepSeparateBookmarks() throws {+ let box = try Sandbox()+ let a = box.root.appendingPathComponent("A", isDirectory: true), b = box.root.appendingPathComponent("B", isDirectory: true)+ for d in [a, b] { try FileManager.default.createDirectory(at: d, withIntermediateDirectories: true) }+ let data = makeStore(box), cloud = makeStore(box, key: BookmarkStore.cloudSavesKey)+ #expect(data.store(a) && cloud.store(b))+ data.clear()+ #expect(data.resolve() == .none)+ guard case .url(let url) = cloud.resolve() else { Issue.record("cloud lost"); return }+ #expect(url.lastPathComponent == "B")+ #expect(BookmarkStore.gameDataKey == "pickedDataBookmark" && BookmarkStore.cloudSavesKey == "cloudSavesBookmark")+ }++ @Test func aRelocatedFolderStillResolvesToItsNewPlace() throws {+ let box = try Sandbox()+ let a = box.root.appendingPathComponent("Old", isDirectory: true)+ try FileManager.default.createDirectory(at: a, withIntermediateDirectories: true)+ let store = makeStore(box)+ #expect(store.store(a))+ let moved = box.root.appendingPathComponent("New", isDirectory: true)+ try FileManager.default.moveItem(at: a, to: moved)+ guard case .url(let url) = store.resolve() else { Issue.record("did not follow the move"); return }+ #expect(url.lastPathComponent == "New")+ }+}diff --git a/frontend-ios/Tests/ShellHostTests/CatalogueStateTests.swift b/frontend-ios/Tests/ShellHostTests/CatalogueStateTests.swiftnew file mode 100644index 00000000..c145c9dc--- /dev/null+++ b/frontend-ios/Tests/ShellHostTests/CatalogueStateTests.swift@@ -0,0 +1,134 @@+import Foundation+import Testing+import ShellUI+@testable import ShellHost++@Suite struct CatalogueStateTests {+ @Test func scansEveryBundleAndKeepsTheBrokenOnes() throws {+ let entries = GameCatalogue.scan(root: Fixtures.gamesURL)+ #expect(entries.count == 8)+ let byID = Dictionary(uniqueKeysWithValues: entries.map { ($0.id, $0) })+ #expect(byID[Fixtures.orbit]?.problem == nil)+ #expect(byID[Fixtures.orbit]?.title == "Orbit Fixture")+ #expect(byID[Fixtures.noFramework]?.problem?.reason == "Game code missing")+ #expect(byID[Fixtures.badManifest]?.problem?.detail.contains("not valid JSON") == true)+ #expect(byID[Fixtures.missingKey]?.problem != nil)+ #expect(byID[Fixtures.badSettings]?.problem?.detail.contains("DM_X") == true)+ #expect(byID[Fixtures.badManifest]?.title == Fixtures.badManifest, "a broken manifest leaves the folder name as the title")+ #expect(entries.suffix(2).allSatisfy { $0.manifest == nil }, "games whose manifest cannot be read sort last")+ }++ @Test func missingFilesAreBrokenWithAReason() throws {+ let box = try Sandbox()+ let fm = FileManager.default+ let dir = box.games.appendingPathComponent(Fixtures.orbit)+ try fm.removeItem(at: dir.appendingPathComponent("game.manifest.json"))+ #expect(GameCatalogue.read(directory: dir).problem?.reason == "Game manifest missing")+ try fm.removeItem(at: box.games.appendingPathComponent(Fixtures.chain).appendingPathComponent("launcher.json"))+ #expect(GameCatalogue.read(directory: box.games.appendingPathComponent(Fixtures.chain)).problem?.reason == "Settings list missing")+ }++ @Test func launcherJSONInsideTheFrameworkIsFound() throws {+ let box = try Sandbox()+ let dir = box.games.appendingPathComponent(Fixtures.orbit)+ let fm = FileManager.default+ try fm.createDirectory(at: dir.appendingPathComponent("DmGame.framework/dm"), withIntermediateDirectories: true)+ try fm.moveItem(at: dir.appendingPathComponent("launcher.json"), to: dir.appendingPathComponent("DmGame.framework/dm/launcher.json"))+ #expect(GameCatalogue.read(directory: dir).problem == nil)+ }++ @Test func titleIDMismatchIsBroken() throws {+ let box = try Sandbox()+ let from = box.games.appendingPathComponent(Fixtures.orbit)+ let to = box.games.appendingPathComponent("0100000000990000")+ try FileManager.default.moveItem(at: from, to: to)+ #expect(GameCatalogue.read(directory: to).problem?.detail.contains("0100000000990000") == true)+ }++ @Test func findsBannerAndIcon() throws {+ let box = try Sandbox()+ let dir = box.games.appendingPathComponent(Fixtures.orbit)+ #expect(GameCatalogue.read(directory: dir).bannerURL == nil)+ try pngData(width: 160, height: 90).write(to: dir.appendingPathComponent("banner.png"))+ try pngData(width: 64, height: 64).write(to: dir.appendingPathComponent("icon.png"))+ let entry = GameCatalogue.read(directory: dir)+ #expect(entry.bannerURL?.lastPathComponent == "banner.png")+ #expect(entry.iconURL?.lastPathComponent == "icon.png")+ }++ // MARK: State++ private func entry(_ id: String) -> CatalogueEntry { GameCatalogue.read(directory: Fixtures.gamesURL.appendingPathComponent(id)) }+ private let env = HostEnvironment(chain: "b-3f9a2c", osVersion: OperatingSystemVersion(majorVersion: 26, minorVersion: 0, patchVersion: 0))+ private let found = DataResolution(url: URL(fileURLWithPath: "/tmp/x"), source: .app, pickedIsStale: false)++ @Test func stateFollowsWhatIsPresent() {+ #expect(GameStateResolver.state(for: entry(Fixtures.orbit), data: found, environment: env) == .playable)+ #expect(GameStateResolver.state(for: entry(Fixtures.orbit), data: .missing, environment: env) == .needsGameData)+ #expect(GameStateResolver.state(for: entry(Fixtures.chain), data: found, environment: env) == .needsAppUpdate)+ #expect(GameStateResolver.state(for: entry(Fixtures.newerOS), data: found, environment: env) == .needsAppUpdate)+ // An app update comes before game data: the player cannot fix the data on an app that cannot run the game.+ #expect(GameStateResolver.state(for: entry(Fixtures.chain), data: .missing, environment: env) == .needsAppUpdate)+ // A host without an engine (the demo) skips the chain check.+ #expect(GameStateResolver.state(for: entry(Fixtures.chain), data: found, environment: HostEnvironment(chain: nil, osVersion: env.osVersion)) == .playable)+ }++ @Test func brokenBundlesAreBrokenWhateverElseIsPresent() {+ for id in [Fixtures.noFramework, Fixtures.badManifest, Fixtures.missingKey, Fixtures.badSettings] {+ guard case .broken(let reason, let detail) = GameStateResolver.state(for: entry(id), data: found, environment: env) else {+ Issue.record("\(id) is not broken"); continue+ }+ #expect(!reason.isEmpty && !detail.isEmpty)+ }+ }++ // MARK: Data++ private func manifest() throws -> GameManifest { try #require(entry(Fixtures.orbit).manifest) }++ @Test func dataInTheAppFolder() throws {+ let box = try Sandbox()+ let m = try manifest()+ let app = box.appData.appendingPathComponent(Fixtures.orbit)+ #expect(!DataLocator.locate(manifest: m, picked: .none, appFolder: app).found)+ try box.giveAppData()+ let r = DataLocator.locate(manifest: m, picked: .none, appFolder: app)+ #expect(r.found && r.source == .app && r.url == app)+ }++ @Test func imageCountsOnlyWhenItHasContent() throws {+ let box = try Sandbox()+ let m = try manifest()+ let app = box.appData.appendingPathComponent(Fixtures.orbit)+ try box.write("", to: app.appendingPathComponent("romfs.img"))+ #expect(!DataLocator.locate(manifest: m, picked: .none, appFolder: app).found)+ try box.write("x", to: app.appendingPathComponent("romfs.img"))+ #expect(DataLocator.locate(manifest: m, picked: .none, appFolder: app).found)+ }++ @Test func pickedLocationComesFirstAndFallsThrough() throws {+ let box = try Sandbox()+ let m = try manifest()+ let app = box.appData.appendingPathComponent(Fixtures.orbit)+ let picked = box.root.appendingPathComponent("Drive/MyGame")+ try box.write("", to: picked.appendingPathComponent("fixture.marker"))+ var r = DataLocator.locate(manifest: m, picked: .url(picked), appFolder: app)+ #expect(r.source == .picked && r.url == picked)+ // The picked folder lost its data: the app's own folder answers, when it has any.+ try FileManager.default.removeItem(at: picked)+ #expect(!DataLocator.locate(manifest: m, picked: .url(picked), appFolder: app).found)+ try box.giveAppData()+ r = DataLocator.locate(manifest: m, picked: .url(picked), appFolder: app)+ #expect(r.source == .app)+ // A picked romfs.img file counts through its folder.+ let img = box.root.appendingPathComponent("Drive2/romfs.img")+ try box.write("x", to: img)+ #expect(DataLocator.locate(manifest: m, picked: .url(img), appFolder: app).url == img.deletingLastPathComponent())+ }++ @Test func staleBookmarkIsReported() throws {+ let box = try Sandbox()+ let r = DataLocator.locate(manifest: try manifest(), picked: .stale, appFolder: box.appData.appendingPathComponent(Fixtures.orbit))+ #expect(!r.found && r.pickedIsStale)+ }+}diff --git a/frontend-ios/Tests/ShellHostTests/Fixtures/Games/0100000000010000/DmGame.framework/Info.plist b/frontend-ios/Tests/ShellHostTests/Fixtures/Games/0100000000010000/DmGame.framework/Info.plistnew file mode 100644index 00000000..3cc3e8ea--- /dev/null+++ b/frontend-ios/Tests/ShellHostTests/Fixtures/Games/0100000000010000/DmGame.framework/Info.plist@@ -0,0 +1,2 @@+<?xml version="1.0" encoding="UTF-8"?>+<plist version="1.0"><dict><key>CFBundleExecutable</key><string>DmGame</string></dict></plist>diff --git a/frontend-ios/Tests/ShellHostTests/Fixtures/Games/0100000000010000/game.manifest.json b/frontend-ios/Tests/ShellHostTests/Fixtures/Games/0100000000010000/game.manifest.jsonnew file mode 100644index 00000000..0068b3fc--- /dev/null+++ b/frontend-ios/Tests/ShellHostTests/Fixtures/Games/0100000000010000/game.manifest.json@@ -0,0 +1,23 @@+{+ "schema": 1,+ "title_id": "0100000000010000",+ "name": "Orbit Fixture",+ "display_version": "1.0.0",+ "package_version": "65536",+ "modules": [+ "main",+ "sdk"+ ],+ "nro_count": 0,+ "chain": "b-3f9a2c",+ "loader": "FR",+ "framework": "DmGame.framework",+ "framework_executable": "DmGame",+ "image_marker": "dmgame_image_marker",+ "profile": "profile.tsv",+ "shader_map": "dm/shader_map.tsv",+ "launcher": "dm/launcher.json",+ "romfs_marker": "fixture.marker",+ "romfs_identity": "DMROMFSID1 fixture",+ "min_os": "26.0"+}diff --git a/frontend-ios/Tests/ShellHostTests/Fixtures/Games/0100000000010000/launcher.json b/frontend-ios/Tests/ShellHostTests/Fixtures/Games/0100000000010000/launcher.jsonnew file mode 100644index 00000000..5d5007a6--- /dev/null+++ b/frontend-ios/Tests/ShellHostTests/Fixtures/Games/0100000000010000/launcher.json@@ -0,0 +1,76 @@+{+ "schema": 1,+ "game": "0100000000010000",+ "settings": [+ {+ "env": "DM_OPMODE",+ "kind": "choice",+ "section": "Game",+ "label": "Play mode",+ "note": "Docked or handheld.",+ "default": "1",+ "options": [+ [+ "1",+ "Docked"+ ],+ [+ "0",+ "Handheld"+ ]+ ],+ "level": "basic"+ },+ {+ "env": "DM_SHOW_FPS",+ "kind": "toggle",+ "section": "Game",+ "label": "Show frame rate",+ "note": "",+ "default": "0",+ "on": "1",+ "off": "0"+ },+ {+ "env": "DM_UPSCALER",+ "kind": "choice",+ "section": "Performance",+ "label": "Upscaler",+ "note": "",+ "default": "off",+ "options": [+ [+ "off",+ "Off"+ ],+ [+ "fsr",+ "FSR"+ ]+ ]+ },+ {+ "env": "DM_UPSCALER_SHARPNESS",+ "kind": "range",+ "section": "Performance",+ "label": "Sharpness",+ "note": "",+ "default": "0.5",+ "min": 0,+ "max": 1,+ "step": 0.1,+ "needs": "DM_UPSCALER=fsr"+ },+ {+ "env": "DM_RENDER_SCALE",+ "kind": "range",+ "section": "Performance",+ "label": "Render scale",+ "note": "",+ "default": "1.0",+ "min": 0.5,+ "max": 1.5,+ "step": 0.05+ }+ ]+}diff --git a/frontend-ios/Tests/ShellHostTests/Fixtures/Games/0100000000020000/DmGame.framework/Info.plist b/frontend-ios/Tests/ShellHostTests/Fixtures/Games/0100000000020000/DmGame.framework/Info.plistnew file mode 100644index 00000000..3cc3e8ea--- /dev/null+++ b/frontend-ios/Tests/ShellHostTests/Fixtures/Games/0100000000020000/DmGame.framework/Info.plist@@ -0,0 +1,2 @@+<?xml version="1.0" encoding="UTF-8"?>+<plist version="1.0"><dict><key>CFBundleExecutable</key><string>DmGame</string></dict></plist>diff --git a/frontend-ios/Tests/ShellHostTests/Fixtures/Games/0100000000020000/game.manifest.json b/frontend-ios/Tests/ShellHostTests/Fixtures/Games/0100000000020000/game.manifest.jsonnew file mode 100644index 00000000..48fc2eb7--- /dev/null+++ b/frontend-ios/Tests/ShellHostTests/Fixtures/Games/0100000000020000/game.manifest.json@@ -0,0 +1,23 @@+{+ "schema": 1,+ "title_id": "0100000000020000",+ "name": "Chain Fixture",+ "display_version": "1.0.0",+ "package_version": "65536",+ "modules": [+ "main",+ "sdk"+ ],+ "nro_count": 0,+ "chain": "b-0000ff",+ "loader": "FR",+ "framework": "DmGame.framework",+ "framework_executable": "DmGame",+ "image_marker": "dmgame_image_marker",+ "profile": "profile.tsv",+ "shader_map": "dm/shader_map.tsv",+ "launcher": "dm/launcher.json",+ "romfs_marker": "fixture.marker",+ "romfs_identity": "DMROMFSID1 fixture",+ "min_os": "26.0"+}diff --git a/frontend-ios/Tests/ShellHostTests/Fixtures/Games/0100000000020000/launcher.json b/frontend-ios/Tests/ShellHostTests/Fixtures/Games/0100000000020000/launcher.jsonnew file mode 100644index 00000000..a99d34c3--- /dev/null+++ b/frontend-ios/Tests/ShellHostTests/Fixtures/Games/0100000000020000/launcher.json@@ -0,0 +1,76 @@+{+ "schema": 1,+ "game": "0100000000020000",+ "settings": [+ {+ "env": "DM_OPMODE",+ "kind": "choice",+ "section": "Game",+ "label": "Play mode",+ "note": "Docked or handheld.",+ "default": "1",+ "options": [+ [+ "1",+ "Docked"+ ],+ [+ "0",+ "Handheld"+ ]+ ],+ "level": "basic"+ },+ {+ "env": "DM_SHOW_FPS",+ "kind": "toggle",+ "section": "Game",+ "label": "Show frame rate",+ "note": "",+ "default": "0",+ "on": "1",+ "off": "0"+ },+ {+ "env": "DM_UPSCALER",+ "kind": "choice",+ "section": "Performance",+ "label": "Upscaler",+ "note": "",+ "default": "off",+ "options": [+ [+ "off",+ "Off"+ ],+ [+ "fsr",+ "FSR"+ ]+ ]+ },+ {+ "env": "DM_UPSCALER_SHARPNESS",+ "kind": "range",+ "section": "Performance",+ "label": "Sharpness",+ "note": "",+ "default": "0.5",+ "min": 0,+ "max": 1,+ "step": 0.1,+ "needs": "DM_UPSCALER=fsr"+ },+ {+ "env": "DM_RENDER_SCALE",+ "kind": "range",+ "section": "Performance",+ "label": "Render scale",+ "note": "",+ "default": "1.0",+ "min": 0.5,+ "max": 1.5,+ "step": 0.05+ }+ ]+}diff --git a/frontend-ios/Tests/ShellHostTests/Fixtures/Games/0100000000030000/DmGame.framework/Info.plist b/frontend-ios/Tests/ShellHostTests/Fixtures/Games/0100000000030000/DmGame.framework/Info.plistnew file mode 100644index 00000000..3cc3e8ea--- /dev/null+++ b/frontend-ios/Tests/ShellHostTests/Fixtures/Games/0100000000030000/DmGame.framework/Info.plist@@ -0,0 +1,2 @@+<?xml version="1.0" encoding="UTF-8"?>+<plist version="1.0"><dict><key>CFBundleExecutable</key><string>DmGame</string></dict></plist>diff --git a/frontend-ios/Tests/ShellHostTests/Fixtures/Games/0100000000030000/game.manifest.json b/frontend-ios/Tests/ShellHostTests/Fixtures/Games/0100000000030000/game.manifest.jsonnew file mode 100644index 00000000..0b8ffb10--- /dev/null+++ b/frontend-ios/Tests/ShellHostTests/Fixtures/Games/0100000000030000/game.manifest.json@@ -0,0 +1,23 @@+{+ "schema": 1,+ "title_id": "0100000000030000",+ "name": "Newer OS Fixture",+ "display_version": "1.0.0",+ "package_version": "65536",+ "modules": [+ "main",+ "sdk"+ ],+ "nro_count": 0,+ "chain": "b-3f9a2c",+ "loader": "FR",+ "framework": "DmGame.framework",+ "framework_executable": "DmGame",+ "image_marker": "dmgame_image_marker",+ "profile": "profile.tsv",+ "shader_map": "dm/shader_map.tsv",+ "launcher": "dm/launcher.json",+ "romfs_marker": "fixture.marker",+ "romfs_identity": "DMROMFSID1 fixture",+ "min_os": "99.0"+}diff --git a/frontend-ios/Tests/ShellHostTests/Fixtures/Games/0100000000030000/launcher.json b/frontend-ios/Tests/ShellHostTests/Fixtures/Games/0100000000030000/launcher.jsonnew file mode 100644index 00000000..fe5ee68d--- /dev/null+++ b/frontend-ios/Tests/ShellHostTests/Fixtures/Games/0100000000030000/launcher.json@@ -0,0 +1,76 @@+{+ "schema": 1,+ "game": "0100000000030000",+ "settings": [+ {+ "env": "DM_OPMODE",+ "kind": "choice",+ "section": "Game",+ "label": "Play mode",+ "note": "Docked or handheld.",+ "default": "1",+ "options": [+ [+ "1",+ "Docked"+ ],+ [+ "0",+ "Handheld"+ ]+ ],+ "level": "basic"+ },+ {+ "env": "DM_SHOW_FPS",+ "kind": "toggle",+ "section": "Game",+ "label": "Show frame rate",+ "note": "",+ "default": "0",+ "on": "1",+ "off": "0"+ },+ {+ "env": "DM_UPSCALER",+ "kind": "choice",+ "section": "Performance",+ "label": "Upscaler",+ "note": "",+ "default": "off",+ "options": [+ [+ "off",+ "Off"+ ],+ [+ "fsr",+ "FSR"+ ]+ ]+ },+ {+ "env": "DM_UPSCALER_SHARPNESS",+ "kind": "range",+ "section": "Performance",+ "label": "Sharpness",+ "note": "",+ "default": "0.5",+ "min": 0,+ "max": 1,+ "step": 0.1,+ "needs": "DM_UPSCALER=fsr"+ },+ {+ "env": "DM_RENDER_SCALE",+ "kind": "range",+ "section": "Performance",+ "label": "Render scale",+ "note": "",+ "default": "1.0",+ "min": 0.5,+ "max": 1.5,+ "step": 0.05+ }+ ]+}diff --git a/frontend-ios/Tests/ShellHostTests/Fixtures/Games/0100000000040000/game.manifest.json b/frontend-ios/Tests/ShellHostTests/Fixtures/Games/0100000000040000/game.manifest.jsonnew file mode 100644index 00000000..bdee1f89--- /dev/null+++ b/frontend-ios/Tests/ShellHostTests/Fixtures/Games/0100000000040000/game.manifest.json@@ -0,0 +1,23 @@+{+ "schema": 1,+ "title_id": "0100000000040000",+ "name": "No Framework Fixture",+ "display_version": "1.0.0",+ "package_version": "65536",+ "modules": [+ "main",+ "sdk"+ ],+ "nro_count": 0,+ "chain": "b-3f9a2c",+ "loader": "FR",+ "framework": "DmGame.framework",+ "framework_executable": "DmGame",+ "image_marker": "dmgame_image_marker",+ "profile": "profile.tsv",+ "shader_map": "dm/shader_map.tsv",+ "launcher": "dm/launcher.json",+ "romfs_marker": "fixture.marker",+ "romfs_identity": "DMROMFSID1 fixture",+ "min_os": "26.0"+}diff --git a/frontend-ios/Tests/ShellHostTests/Fixtures/Games/0100000000040000/launcher.json b/frontend-ios/Tests/ShellHostTests/Fixtures/Games/0100000000040000/launcher.jsonnew file mode 100644index 00000000..4b6a48d8--- /dev/null+++ b/frontend-ios/Tests/ShellHostTests/Fixtures/Games/0100000000040000/launcher.json@@ -0,0 +1,76 @@+{+ "schema": 1,+ "game": "0100000000040000",+ "settings": [+ {+ "env": "DM_OPMODE",+ "kind": "choice",+ "section": "Game",+ "label": "Play mode",+ "note": "Docked or handheld.",+ "default": "1",+ "options": [+ [+ "1",+ "Docked"+ ],+ [+ "0",+ "Handheld"+ ]+ ],+ "level": "basic"+ },+ {+ "env": "DM_SHOW_FPS",+ "kind": "toggle",+ "section": "Game",+ "label": "Show frame rate",+ "note": "",+ "default": "0",+ "on": "1",+ "off": "0"+ },+ {+ "env": "DM_UPSCALER",+ "kind": "choice",+ "section": "Performance",+ "label": "Upscaler",+ "note": "",+ "default": "off",+ "options": [+ [+ "off",+ "Off"+ ],+ [+ "fsr",+ "FSR"+ ]+ ]+ },+ {+ "env": "DM_UPSCALER_SHARPNESS",+ "kind": "range",+ "section": "Performance",+ "label": "Sharpness",+ "note": "",+ "default": "0.5",+ "min": 0,+ "max": 1,+ "step": 0.1,+ "needs": "DM_UPSCALER=fsr"+ },+ {+ "env": "DM_RENDER_SCALE",+ "kind": "range",+ "section": "Performance",+ "label": "Render scale",+ "note": "",+ "default": "1.0",+ "min": 0.5,+ "max": 1.5,+ "step": 0.05+ }+ ]+}diff --git a/frontend-ios/Tests/ShellHostTests/Fixtures/Games/0100000000050000/DmGame.framework/Info.plist b/frontend-ios/Tests/ShellHostTests/Fixtures/Games/0100000000050000/DmGame.framework/Info.plistnew file mode 100644index 00000000..3cc3e8ea--- /dev/null+++ b/frontend-ios/Tests/ShellHostTests/Fixtures/Games/0100000000050000/DmGame.framework/Info.plist@@ -0,0 +1,2 @@+<?xml version="1.0" encoding="UTF-8"?>+<plist version="1.0"><dict><key>CFBundleExecutable</key><string>DmGame</string></dict></plist>diff --git a/frontend-ios/Tests/ShellHostTests/Fixtures/Games/0100000000050000/game.manifest.json b/frontend-ios/Tests/ShellHostTests/Fixtures/Games/0100000000050000/game.manifest.jsonnew file mode 100644index 00000000..2ffab7a8--- /dev/null+++ b/frontend-ios/Tests/ShellHostTests/Fixtures/Games/0100000000050000/game.manifest.json@@ -0,0 +1 @@+{"schema": 1, "title_id": "0100000000050000", "name":\ No newline at end of filediff --git a/frontend-ios/Tests/ShellHostTests/Fixtures/Games/0100000000050000/launcher.json b/frontend-ios/Tests/ShellHostTests/Fixtures/Games/0100000000050000/launcher.jsonnew file mode 100644index 00000000..866a2d37--- /dev/null+++ b/frontend-ios/Tests/ShellHostTests/Fixtures/Games/0100000000050000/launcher.json@@ -0,0 +1,76 @@+{+ "schema": 1,+ "game": "0100000000050000",+ "settings": [+ {+ "env": "DM_OPMODE",+ "kind": "choice",+ "section": "Game",+ "label": "Play mode",+ "note": "Docked or handheld.",+ "default": "1",+ "options": [+ [+ "1",+ "Docked"+ ],+ [+ "0",+ "Handheld"+ ]+ ],+ "level": "basic"+ },+ {+ "env": "DM_SHOW_FPS",+ "kind": "toggle",+ "section": "Game",+ "label": "Show frame rate",+ "note": "",+ "default": "0",+ "on": "1",+ "off": "0"+ },+ {+ "env": "DM_UPSCALER",+ "kind": "choice",+ "section": "Performance",+ "label": "Upscaler",+ "note": "",+ "default": "off",+ "options": [+ [+ "off",+ "Off"+ ],+ [+ "fsr",+ "FSR"+ ]+ ]+ },+ {+ "env": "DM_UPSCALER_SHARPNESS",+ "kind": "range",+ "section": "Performance",+ "label": "Sharpness",+ "note": "",+ "default": "0.5",+ "min": 0,+ "max": 1,+ "step": 0.1,+ "needs": "DM_UPSCALER=fsr"+ },+ {+ "env": "DM_RENDER_SCALE",+ "kind": "range",+ "section": "Performance",+ "label": "Render scale",+ "note": "",+ "default": "1.0",+ "min": 0.5,+ "max": 1.5,+ "step": 0.05+ }+ ]+}diff --git a/frontend-ios/Tests/ShellHostTests/Fixtures/Games/0100000000060000/DmGame.framework/Info.plist b/frontend-ios/Tests/ShellHostTests/Fixtures/Games/0100000000060000/DmGame.framework/Info.plistnew file mode 100644index 00000000..3cc3e8ea--- /dev/null+++ b/frontend-ios/Tests/ShellHostTests/Fixtures/Games/0100000000060000/DmGame.framework/Info.plist@@ -0,0 +1,2 @@+<?xml version="1.0" encoding="UTF-8"?>+<plist version="1.0"><dict><key>CFBundleExecutable</key><string>DmGame</string></dict></plist>diff --git a/frontend-ios/Tests/ShellHostTests/Fixtures/Games/0100000000060000/game.manifest.json b/frontend-ios/Tests/ShellHostTests/Fixtures/Games/0100000000060000/game.manifest.jsonnew file mode 100644index 00000000..08a9c931--- /dev/null+++ b/frontend-ios/Tests/ShellHostTests/Fixtures/Games/0100000000060000/game.manifest.json@@ -0,0 +1 @@+{"schema": 1, "title_id": "0100000000060000", "name": "Missing Key Fixture"}\ No newline at end of filediff --git a/frontend-ios/Tests/ShellHostTests/Fixtures/Games/0100000000060000/launcher.json b/frontend-ios/Tests/ShellHostTests/Fixtures/Games/0100000000060000/launcher.jsonnew file mode 100644index 00000000..a3a15276--- /dev/null+++ b/frontend-ios/Tests/ShellHostTests/Fixtures/Games/0100000000060000/launcher.json@@ -0,0 +1,76 @@+{+ "schema": 1,+ "game": "0100000000060000",+ "settings": [+ {+ "env": "DM_OPMODE",+ "kind": "choice",+ "section": "Game",+ "label": "Play mode",+ "note": "Docked or handheld.",+ "default": "1",+ "options": [+ [+ "1",+ "Docked"+ ],+ [+ "0",+ "Handheld"+ ]+ ],+ "level": "basic"+ },+ {+ "env": "DM_SHOW_FPS",+ "kind": "toggle",+ "section": "Game",+ "label": "Show frame rate",+ "note": "",+ "default": "0",+ "on": "1",+ "off": "0"+ },+ {+ "env": "DM_UPSCALER",+ "kind": "choice",+ "section": "Performance",+ "label": "Upscaler",+ "note": "",+ "default": "off",+ "options": [+ [+ "off",+ "Off"+ ],+ [+ "fsr",+ "FSR"+ ]+ ]+ },+ {+ "env": "DM_UPSCALER_SHARPNESS",+ "kind": "range",+ "section": "Performance",+ "label": "Sharpness",+ "note": "",+ "default": "0.5",+ "min": 0,+ "max": 1,+ "step": 0.1,+ "needs": "DM_UPSCALER=fsr"+ },+ {+ "env": "DM_RENDER_SCALE",+ "kind": "range",+ "section": "Performance",+ "label": "Render scale",+ "note": "",+ "default": "1.0",+ "min": 0.5,+ "max": 1.5,+ "step": 0.05+ }+ ]+}diff --git a/frontend-ios/Tests/ShellHostTests/Fixtures/Games/0100000000070000/DmGame.framework/Info.plist b/frontend-ios/Tests/ShellHostTests/Fixtures/Games/0100000000070000/DmGame.framework/Info.plistnew file mode 100644index 00000000..3cc3e8ea--- /dev/null+++ b/frontend-ios/Tests/ShellHostTests/Fixtures/Games/0100000000070000/DmGame.framework/Info.plist@@ -0,0 +1,2 @@+<?xml version="1.0" encoding="UTF-8"?>+<plist version="1.0"><dict><key>CFBundleExecutable</key><string>DmGame</string></dict></plist>diff --git a/frontend-ios/Tests/ShellHostTests/Fixtures/Games/0100000000070000/game.manifest.json b/frontend-ios/Tests/ShellHostTests/Fixtures/Games/0100000000070000/game.manifest.jsonnew file mode 100644index 00000000..638d9b6a--- /dev/null+++ b/frontend-ios/Tests/ShellHostTests/Fixtures/Games/0100000000070000/game.manifest.json@@ -0,0 +1,23 @@+{+ "schema": 1,+ "title_id": "0100000000070000",+ "name": "Bad Settings Fixture",+ "display_version": "1.0.0",+ "package_version": "65536",+ "modules": [+ "main",+ "sdk"+ ],+ "nro_count": 0,+ "chain": "b-3f9a2c",+ "loader": "FR",+ "framework": "DmGame.framework",+ "framework_executable": "DmGame",+ "image_marker": "dmgame_image_marker",+ "profile": "profile.tsv",+ "shader_map": "dm/shader_map.tsv",+ "launcher": "dm/launcher.json",+ "romfs_marker": "fixture.marker",+ "romfs_identity": "DMROMFSID1 fixture",+ "min_os": "26.0"+}diff --git a/frontend-ios/Tests/ShellHostTests/Fixtures/Games/0100000000070000/launcher.json b/frontend-ios/Tests/ShellHostTests/Fixtures/Games/0100000000070000/launcher.jsonnew file mode 100644index 00000000..7c23ccc6--- /dev/null+++ b/frontend-ios/Tests/ShellHostTests/Fixtures/Games/0100000000070000/launcher.json@@ -0,0 +1 @@+{"game":"0100000000070000","settings":[{"env":"DM_X","kind":"choice","section":"Game","label":"X","note":"","default":"a"}]}\ No newline at end of filediff --git a/frontend-ios/Tests/ShellHostTests/Fixtures/Games/0100000000080000/DmGame.framework/Info.plist b/frontend-ios/Tests/ShellHostTests/Fixtures/Games/0100000000080000/DmGame.framework/Info.plistnew file mode 100644index 00000000..3cc3e8ea--- /dev/null+++ b/frontend-ios/Tests/ShellHostTests/Fixtures/Games/0100000000080000/DmGame.framework/Info.plist@@ -0,0 +1,2 @@+<?xml version="1.0" encoding="UTF-8"?>+<plist version="1.0"><dict><key>CFBundleExecutable</key><string>DmGame</string></dict></plist>diff --git a/frontend-ios/Tests/ShellHostTests/Fixtures/Games/0100000000080000/game.manifest.json b/frontend-ios/Tests/ShellHostTests/Fixtures/Games/0100000000080000/game.manifest.jsonnew file mode 100644index 00000000..9f8bf98a--- /dev/null+++ b/frontend-ios/Tests/ShellHostTests/Fixtures/Games/0100000000080000/game.manifest.json@@ -0,0 +1,23 @@+{+ "schema": 1,+ "title_id": "0100000000080000",+ "name": "Quiet Fixture",+ "display_version": "1.0.0",+ "package_version": "65536",+ "modules": [+ "main",+ "sdk"+ ],+ "nro_count": 0,+ "chain": "b-3f9a2c",+ "loader": "FR",+ "framework": "DmGame.framework",+ "framework_executable": "DmGame",+ "image_marker": "dmgame_image_marker",+ "profile": "profile.tsv",+ "shader_map": "dm/shader_map.tsv",+ "launcher": "dm/launcher.json",+ "romfs_marker": "fixture.marker",+ "romfs_identity": "DMROMFSID1 fixture",+ "min_os": "26.0"+}diff --git a/frontend-ios/Tests/ShellHostTests/Fixtures/Games/0100000000080000/launcher.json b/frontend-ios/Tests/ShellHostTests/Fixtures/Games/0100000000080000/launcher.jsonnew file mode 100644index 00000000..f4f19a6f--- /dev/null+++ b/frontend-ios/Tests/ShellHostTests/Fixtures/Games/0100000000080000/launcher.json@@ -0,0 +1,76 @@+{+ "schema": 1,+ "game": "0100000000080000",+ "settings": [+ {+ "env": "DM_OPMODE",+ "kind": "choice",+ "section": "Game",+ "label": "Play mode",+ "note": "Docked or handheld.",+ "default": "1",+ "options": [+ [+ "1",+ "Docked"+ ],+ [+ "0",+ "Handheld"+ ]+ ],+ "level": "basic"+ },+ {+ "env": "DM_SHOW_FPS",+ "kind": "toggle",+ "section": "Game",+ "label": "Show frame rate",+ "note": "",+ "default": "0",+ "on": "1",+ "off": "0"+ },+ {+ "env": "DM_UPSCALER",+ "kind": "choice",+ "section": "Performance",+ "label": "Upscaler",+ "note": "",+ "default": "off",+ "options": [+ [+ "off",+ "Off"+ ],+ [+ "fsr",+ "FSR"+ ]+ ]+ },+ {+ "env": "DM_UPSCALER_SHARPNESS",+ "kind": "range",+ "section": "Performance",+ "label": "Sharpness",+ "note": "",+ "default": "0.5",+ "min": 0,+ "max": 1,+ "step": 0.1,+ "needs": "DM_UPSCALER=fsr"+ },+ {+ "env": "DM_RENDER_SCALE",+ "kind": "range",+ "section": "Performance",+ "label": "Render scale",+ "note": "",+ "default": "1.0",+ "min": 0.5,+ "max": 1.5,+ "step": 0.05+ }+ ]+}diff --git a/frontend-ios/Tests/ShellHostTests/LauncherTests.swift b/frontend-ios/Tests/ShellHostTests/LauncherTests.swiftnew file mode 100644index 00000000..de06fa03--- /dev/null+++ b/frontend-ios/Tests/ShellHostTests/LauncherTests.swift@@ -0,0 +1,30 @@+import Foundation+import Testing+@testable import ShellHost++/// Collects what the stub logs.+final class LogBox: @unchecked Sendable {+ private let lock = NSLock()+ private var lines: [String] = []+ func add(_ line: String) { lock.lock(); lines.append(line); lock.unlock() }+ var all: [String] { lock.lock(); defer { lock.unlock() }; return lines }+}++func sampleGame() throws -> LaunchableGame {+ let entry = GameCatalogue.read(directory: Fixtures.gamesURL.appendingPathComponent(Fixtures.orbit))+ return LaunchableGame(titleID: entry.id, name: entry.title, manifest: try #require(entry.manifest), directory: entry.directory,+ frameworkURL: try #require(entry.frameworkURL), dataURL: URL(fileURLWithPath: "/tmp/data"),+ appFolder: URL(fileURLWithPath: "/tmp/app"), environment: ["DM_OPMODE": "1"], cloudSavesURL: nil)+}++@MainActor @Suite struct LauncherTests {+ @Test func theStubLogsAndSaysItCannotLaunch() async throws {+ let box = LogBox()+ let launcher = StubGameLauncher(log: { box.add($0) })+ let game = try sampleGame()+ await #expect(throws: GameLaunchError.notAvailable) { try await launcher.launch(game) }+ #expect(box.all.count == 1)+ #expect(box.all[0].contains(Fixtures.orbit) && box.all[0].contains("does not start it"))+ #expect(GameLaunchError.notAvailable.localizedDescription == "Launching is not available yet.")+ }+}diff --git a/frontend-ios/Tests/ShellHostTests/ParsingTests.swift b/frontend-ios/Tests/ShellHostTests/ParsingTests.swiftnew file mode 100644index 00000000..95266f3e--- /dev/null+++ b/frontend-ios/Tests/ShellHostTests/ParsingTests.swift@@ -0,0 +1,94 @@+import Foundation+import Testing+@testable import ShellHost++@Suite struct ParsingTests {+ private func fixture(_ id: String, _ file: String) throws -> Data {+ try Data(contentsOf: Fixtures.gamesURL.appendingPathComponent(id).appendingPathComponent(file))+ }++ @Test func parsesTheManifest() throws {+ let m = try GameManifest.parse(fixture(Fixtures.orbit, "game.manifest.json"))+ #expect(m.titleID == Fixtures.orbit)+ #expect(m.name == "Orbit Fixture")+ #expect(m.chain == "b-3f9a2c")+ #expect(m.modules == ["main", "sdk"])+ #expect(m.framework == "DmGame.framework")+ #expect(m.romfsMarker == "fixture.marker")+ #expect(m.icon == nil)+ }++ @Test func malformedManifestsGiveReadableReasons() throws {+ func problem(_ text: String) -> GameProblem? {+ do { _ = try GameManifest.parse(Data(text.utf8)); return nil } catch { return error }+ }+ let truncated = try #require(problem(String(decoding: fixture(Fixtures.badManifest, "game.manifest.json"), as: UTF8.self)))+ #expect(truncated.detail.contains("not valid JSON"))+ let missing = try #require(problem(String(decoding: fixture(Fixtures.missingKey, "game.manifest.json"), as: UTF8.self)))+ #expect(missing.detail.contains("display_version") || missing.detail.contains("\"") )+ #expect(missing.reason == "Game files damaged")+ #expect(problem("[]") != nil)+ #expect(problem("")?.detail.contains("game.manifest.json") == true)+ }++ @Test func manifestValidation() throws {+ let good = String(decoding: try fixture(Fixtures.orbit, "game.manifest.json"), as: UTF8.self)+ func broken(_ from: String, _ to: String) -> GameProblem? {+ do { _ = try GameManifest.parse(Data(good.replacingOccurrences(of: from, with: to).utf8)); return nil } catch { return error }+ }+ #expect(broken("\"schema\": 1", "\"schema\": 2")?.reason == "Manifest not supported")+ #expect(broken("\"title_id\": \"0100000000010000\"", "\"title_id\": \"zz\"")?.detail.contains("16 hex") == true)+ #expect(broken("\"b-3f9a2c\"", "\"3f9a2c\"")?.detail.contains("b-<hex>") == true)+ #expect(broken("\"FR\"", "\"XX\"")?.detail.contains("loader") == true)+ #expect(broken("\"DmGame.framework\"", "\"../x\"")?.detail.contains(".framework") == true)+ #expect(broken("\"main\",\n \"sdk\"", "")?.detail.contains("no modules") == true)+ }++ @Test func parsesTheLauncherProfile() throws {+ let p = try LauncherProfile.parse(fixture(Fixtures.orbit, "launcher.json"))+ #expect(p.game == Fixtures.orbit)+ #expect(p.settings.map(\.env) == ["DM_OPMODE", "DM_SHOW_FPS", "DM_UPSCALER", "DM_UPSCALER_SHARPNESS", "DM_RENDER_SCALE"])+ #expect(p.settings[0].level == "basic")+ #expect(p.settings[3].needs == "DM_UPSCALER=fsr")+ }++ @Test func malformedLauncherJSONGivesReadableReasons() throws {+ func problem(_ text: String) -> GameProblem? {+ do { _ = try LauncherProfile.parse(Data(text.utf8)); return nil } catch { return error }+ }+ let noOptions = String(decoding: try fixture(Fixtures.badSettings, "launcher.json"), as: UTF8.self)+ #expect(problem(noOptions)?.detail.contains("DM_X is a choice without") == true)+ #expect(problem("{")?.detail.contains("not valid JSON") == true)+ #expect(problem("{\"game\":\"0100000000010000\"}")?.detail.contains("settings") == true)+ #expect(problem("{\"game\":\"1\",\"settings\":[]}")?.detail.contains("16 hex") == true)+ #expect(problem("{\"schema\":2,\"game\":\"0100000000010000\",\"settings\":[]}")?.reason == "Settings list not supported")+ let row = "{\"env\":\"DM_A\",\"kind\":\"toggle\",\"section\":\"Game\",\"label\":\"A\",\"note\":\"\",\"default\":\"0\"}"+ #expect(problem("{\"game\":\"0100000000010000\",\"settings\":[\(row),\(row)]}")?.detail.contains("twice") == true)+ #expect(problem("{\"game\":\"0100000000010000\",\"settings\":[\(row.replacingOccurrences(of: "DM_A", with: "path"))]}")?.detail.contains("not a DM_ switch") == true)+ #expect(problem("{\"game\":\"0100000000010000\",\"settings\":[\(row.replacingOccurrences(of: "toggle", with: "dial"))]}")?.detail.contains("unknown kind") == true)+ let range = "{\"env\":\"DM_R\",\"kind\":\"range\",\"section\":\"Game\",\"label\":\"R\",\"note\":\"\",\"default\":\"1\",\"min\":0,\"max\":2}"+ #expect(problem("{\"game\":\"0100000000010000\",\"settings\":[\(range)]}")?.detail.contains("min, max and step") == true)+ #expect(problem("{\"game\":\"0100000000010000\",\"settings\":[]}") == nil)+ }++ @Test func settingRules() throws {+ let p = try LauncherProfile.parse(fixture(Fixtures.orbit, "launcher.json"))+ let scale = try #require(p.settings.first { $0.env == "DM_RENDER_SCALE" })+ #expect(scale.isDefault("1.00") && !scale.isDefault("1.05"))+ #expect(scale.accepts("0.5") && !scale.accepts("2") && !scale.accepts("0x1") && !scale.accepts("x"))+ let mode = p.settings[0]+ #expect(mode.accepts("0") && !mode.accepts("2"))+ let fps = p.settings[1]+ #expect(fps.accepts("1") && fps.accepts("0") && !fps.accepts("yes"))+ #expect(fps.defaultsKey == "launcher.DM_SHOW_FPS")+ }++ @Test func versionHelpers() {+ #expect(parseVersion("26.0")?.majorVersion == 26)+ #expect(parseVersion("26.1.2")?.patchVersion == 2)+ #expect(parseVersion("x") == nil)+ let v26 = OperatingSystemVersion(majorVersion: 26, minorVersion: 0, patchVersion: 0)+ #expect(isVersion(OperatingSystemVersion(majorVersion: 26, minorVersion: 1, patchVersion: 0), atLeast: v26))+ #expect(!isVersion(OperatingSystemVersion(majorVersion: 18, minorVersion: 9, patchVersion: 0), atLeast: v26))+ }+}diff --git a/frontend-ios/Tests/ShellHostTests/SettingsTests.swift b/frontend-ios/Tests/ShellHostTests/SettingsTests.swiftnew file mode 100644index 00000000..5660d68f--- /dev/null+++ b/frontend-ios/Tests/ShellHostTests/SettingsTests.swift@@ -0,0 +1,99 @@+import Foundation+import Testing+import ShellUI+@testable import ShellHost++@Suite struct SettingsTests {+ private func profile(_ id: String = Fixtures.orbit) throws -> LauncherProfile {+ try LauncherProfile.parse(Data(contentsOf: Fixtures.gamesURL.appendingPathComponent(id).appendingPathComponent("launcher.json")))+ }++ @Test func defaultsComeFromTheProfile() throws {+ let box = try Sandbox()+ let store = GameSettingsStore(profile: try profile(), defaults: box.defaults(Fixtures.orbit))+ #expect(store.values() == ["DM_OPMODE": "1", "DM_SHOW_FPS": "0", "DM_UPSCALER": "off", "DM_UPSCALER_SHARPNESS": "0.5", "DM_RENDER_SCALE": "1.0"])+ #expect(!store.hasModifiedSettings)+ }++ @Test func aChangeIsKeptUnderTheLauncherKey() throws {+ let box = try Sandbox()+ let defaults = box.defaults(Fixtures.orbit)+ let store = GameSettingsStore(profile: try profile(), defaults: defaults)+ #expect(store.set("DM_SHOW_FPS", to: "1"))+ #expect(defaults.object(forKey: "launcher.DM_SHOW_FPS") as? String == "1")+ #expect(store.values()["DM_SHOW_FPS"] == "1")+ #expect(store.hasModifiedSettings)+ // A new store over the same suite, as after a relaunch.+ #expect(GameSettingsStore(profile: try profile(), defaults: box.defaults(Fixtures.orbit)).values()["DM_SHOW_FPS"] == "1")+ }++ @Test func onlyAChoiceThatDiffersFromTheDefaultIsStored() throws {+ let box = try Sandbox()+ let defaults = box.defaults(Fixtures.orbit)+ let store = GameSettingsStore(profile: try profile(), defaults: defaults)+ store.set("DM_RENDER_SCALE", to: "1.25")+ #expect(defaults.object(forKey: "launcher.DM_RENDER_SCALE") as? String == "1.25")+ store.set("DM_RENDER_SCALE", to: "1.00") // a slider writes 1.00 for 1.0+ #expect(defaults.object(forKey: "launcher.DM_RENDER_SCALE") == nil)+ #expect(!store.hasModifiedSettings)+ }++ @Test func invalidValuesAreRefused() throws {+ let box = try Sandbox()+ let defaults = box.defaults(Fixtures.orbit)+ let store = GameSettingsStore(profile: try profile(), defaults: defaults)+ #expect(!store.set("DM_OPMODE", to: "7"))+ #expect(!store.set("DM_RENDER_SCALE", to: "9"))+ #expect(!store.set("DM_NOT_THERE", to: "1"))+ #expect(defaults.object(forKey: "launcher.DM_OPMODE") == nil)+ }++ @Test func aSavedValueTheGameNoLongerOffersReadsAsTheDefault() throws {+ let box = try Sandbox()+ let defaults = box.defaults(Fixtures.orbit)+ defaults.set("handheld-old", forKey: "launcher.DM_OPMODE")+ defaults.set(3, forKey: "launcher.DM_SHOW_FPS") // not a string: ignored, as launcher.c would+ let store = GameSettingsStore(profile: try profile(), defaults: defaults)+ #expect(store.values()["DM_OPMODE"] == "1")+ #expect(store.values()["DM_SHOW_FPS"] == "0")+ }++ @Test func resetRestoresTheTestedDefaults() throws {+ let box = try Sandbox()+ let defaults = box.defaults(Fixtures.orbit)+ let store = GameSettingsStore(profile: try profile(), defaults: defaults)+ store.set("DM_OPMODE", to: "0"); store.set("DM_SHOW_FPS", to: "1"); store.set("DM_RENDER_SCALE", to: "0.75")+ #expect(store.hasModifiedSettings)+ store.reset()+ #expect(!store.hasModifiedSettings)+ #expect(store.values()["DM_OPMODE"] == "1")+ for s in try profile().settings { #expect(defaults.object(forKey: s.defaultsKey) == nil) }+ }++ @Test func gamesKeepTheirOwnChoices() throws {+ let box = try Sandbox()+ let a = GameSettingsStore(profile: try profile(Fixtures.orbit), defaults: box.defaults(Fixtures.orbit))+ let b = GameSettingsStore(profile: try profile(Fixtures.chain), defaults: box.defaults(Fixtures.chain))+ a.set("DM_SHOW_FPS", to: "1")+ #expect(b.values()["DM_SHOW_FPS"] == "0")+ b.reset()+ #expect(a.values()["DM_SHOW_FPS"] == "1")+ #expect(GameDefaults.suite(for: Fixtures.orbit) !== GameDefaults.suite(for: Fixtures.chain))+ }++ @Test func sectionsFollowTheListAndHideSubSettings() throws {+ let p = try profile()+ var values = GameSettingsStore(profile: p, defaults: try Sandbox().defaults("x")).values()+ var sections = SettingsPresenter.sections(profile: p, values: values)+ #expect(sections.map(\.title) == ["Game", "Performance"])+ #expect(sections[1].rows.map(\.id) == ["DM_UPSCALER", "DM_RENDER_SCALE"], "sharpness needs the upscaler on")+ values["DM_UPSCALER"] = "fsr"+ sections = SettingsPresenter.sections(profile: p, values: values)+ #expect(sections[1].rows.map(\.id) == ["DM_UPSCALER", "DM_UPSCALER_SHARPNESS", "DM_RENDER_SCALE"])+ let mode = sections[0].rows[0]+ #expect(mode.kind == .choice([SettingOption("1", "Docked"), SettingOption("0", "Handheld")]))+ #expect(sections[0].rows[1].kind == .toggle(on: "1", off: "0"))+ #expect(sections[1].rows[2].kind == .range(min: 0.5, max: 1.5, step: 0.05, unit: "×"))+ #expect(sections[1].rows[2].value == "1.0")+ }+}diff --git a/frontend-ios/Tests/ShellHostTests/ShellHostModelTests.swift b/frontend-ios/Tests/ShellHostTests/ShellHostModelTests.swiftnew file mode 100644index 00000000..7224312c--- /dev/null+++ b/frontend-ios/Tests/ShellHostTests/ShellHostModelTests.swift@@ -0,0 +1,242 @@+import Foundation+import Testing+import ShellUI+@testable import ShellControllers+@testable import ShellHost++struct FakePicker: FolderPicker {+ var url: URL?+ func pickFolder() async -> URL? { url }+}++/// Records launches and can fail them.+final class RecordingLauncher: GameLauncher, @unchecked Sendable {+ private(set) var launched: [LaunchableGame] = []+ var error: (any Error)?+ @MainActor func launch(_ game: LaunchableGame) async throws {+ launched.append(game)+ if let error { throw error }+ }+}++@MainActor @Suite struct ShellHostModelTests {+ private func detail(_ model: ShellHostModel, _ id: String = Fixtures.orbit) throws -> GameDetail {+ try #require(model.details.first { $0.id == id })+ }+ private func value(_ model: ShellHostModel, _ setting: String, game: String = Fixtures.orbit) throws -> String? {+ try detail(model, game).sections.flatMap(\.rows).first { $0.id == setting }?.value+ }++ @Test func buildsTilesAndDetailsFromTheBundles() throws {+ let box = try Sandbox()+ let model = ShellHostModel(config: box.config())+ #expect(model.details.count == 8)+ let orbit = try detail(model)+ #expect(orbit.game.title == "Orbit Fixture" && orbit.game.subtitle == "1.0.0")+ #expect(orbit.game.state == .needsGameData)+ #expect(orbit.sections.map(\.title) == ["Game", "Performance"])+ #expect(orbit.dataSource == "" && !orbit.dataNote.isEmpty)+ #expect(orbit.cloudSaves == nil && orbit.dlc == "No additional content")+ #expect(try detail(model, Fixtures.chain).game.state == .needsAppUpdate)+ #expect(try detail(model, Fixtures.noFramework).game.state == .broken(reason: "Game code missing", detail: "DmGame.framework is not in this game's folder. Install the game again."))+ #expect(try detail(model, Fixtures.badManifest).sections.isEmpty)+ }++ @Test func bannerAndIconBecomeArtwork() throws {+ let box = try Sandbox()+ let dir = box.games.appendingPathComponent(Fixtures.orbit)+ try pngData(width: 160, height: 90).write(to: dir.appendingPathComponent("banner.png"))+ try pngData(width: 64, height: 64).write(to: dir.appendingPathComponent("icon.png"))+ try Data("not an image".utf8).write(to: box.games.appendingPathComponent(Fixtures.chain).appendingPathComponent("banner.png"))+ let model = ShellHostModel(config: box.config())+ #expect(try detail(model).game.banner != nil && detail(model).game.icon != nil)+ #expect(try detail(model, Fixtures.chain).game.banner == nil, "an unreadable picture is left out, not an error")+ }++ @Test func appDataMakesTheGamePlayable() throws {+ let box = try Sandbox()+ try box.giveAppData()+ try box.write("", to: box.appData.appendingPathComponent(Fixtures.orbit).appendingPathComponent("aoc/0.img"))+ let model = ShellHostModel(config: box.config())+ let orbit = try detail(model)+ #expect(orbit.game.state == .playable)+ #expect(orbit.dataSource == "This app's folder" && orbit.dataNote == "")+ #expect(orbit.dlc == "1 additional content pack")+ }++ @Test func changesPersistAndResetRestoresDefaults() throws {+ let box = try Sandbox()+ let model = ShellHostModel(config: box.config())+ model.actions.onChange(Fixtures.orbit, "DM_SHOW_FPS", "1")+ #expect(try value(model, "DM_SHOW_FPS") == "1")+ #expect(try detail(model).hasModifiedSettings)+ #expect(box.defaults(Fixtures.orbit).object(forKey: "launcher.DM_SHOW_FPS") as? String == "1")+ // Another model over the same defaults, as after a relaunch.+ #expect(try value(ShellHostModel(config: box.config()), "DM_SHOW_FPS") == "1")+ model.actions.onChange(Fixtures.orbit, "DM_UPSCALER", "fsr")+ #expect(try detail(model).sections[1].rows.map(\.id).contains("DM_UPSCALER_SHARPNESS"))+ model.actions.onResetDefaults(Fixtures.orbit)+ #expect(try value(model, "DM_SHOW_FPS") == "0")+ #expect(try value(model, "DM_UPSCALER") == "off")+ #expect(try !detail(model).hasModifiedSettings)+ #expect(try detail(model).sections[1].rows.map(\.id) == ["DM_UPSCALER", "DM_RENDER_SCALE"])+ }++ @Test func aRefusedValueChangesNothing() throws {+ let box = try Sandbox()+ let model = ShellHostModel(config: box.config())+ model.change(Fixtures.orbit, setting: "DM_OPMODE", value: "7")+ model.change("0100000000999999", setting: "DM_OPMODE", value: "0")+ #expect(try value(model, "DM_OPMODE") == "1")+ }++ @Test func pickingGameDataStoresABookmarkAndMarksTheGameReady() async throws {+ let box = try Sandbox()+ let drive = box.root.appendingPathComponent("Drive/Orbit", isDirectory: true)+ try box.write("", to: drive.appendingPathComponent("fixture.marker"))+ let model = ShellHostModel(config: box.config(), picker: FakePicker(url: drive))+ #expect(try detail(model).game.state == .needsGameData)+ await model.pickGameDataNow(Fixtures.orbit)+ let orbit = try detail(model)+ #expect(orbit.game.state == .playable)+ #expect(orbit.dataSource == "Orbit")+ #expect(box.defaults(Fixtures.orbit).data(forKey: "pickedDataBookmark") != nil)+ // It survives a relaunch.+ #expect(try detail(ShellHostModel(config: box.config())).game.state == .playable)+ // Back to the app's own folder, which has nothing yet.+ model.actions.onUseAppData(Fixtures.orbit)+ #expect(try detail(model).game.state == .needsGameData)+ #expect(model.notice?.contains("games/\(Fixtures.orbit)") == true)+ #expect(box.defaults(Fixtures.orbit).data(forKey: "pickedDataBookmark") == nil)+ }++ @Test func aPickedFolderWithoutTheGameIsSaidSo() async throws {+ let box = try Sandbox()+ let empty = box.root.appendingPathComponent("Empty", isDirectory: true)+ try FileManager.default.createDirectory(at: empty, withIntermediateDirectories: true)+ let model = ShellHostModel(config: box.config(), picker: FakePicker(url: empty))+ await model.pickGameDataNow(Fixtures.orbit)+ #expect(try detail(model).game.state == .needsGameData)+ #expect(model.notice?.contains("No game data for Orbit Fixture") == true)+ }++ @Test func aCancelledPickChangesNothing() async throws {+ let box = try Sandbox()+ let model = ShellHostModel(config: box.config(), picker: FakePicker(url: nil))+ await model.pickGameDataNow(Fixtures.orbit)+ await model.pickCloudSavesNow(Fixtures.orbit)+ #expect(model.notice == nil)+ #expect(try detail(model).cloudSaves == nil)+ }++ @Test func useAppDataWithDataPresentIsPlayable() throws {+ let box = try Sandbox()+ try box.giveAppData()+ let model = ShellHostModel(config: box.config())+ model.useAppData(Fixtures.orbit)+ #expect(try detail(model).game.state == .playable)+ #expect(model.notice == nil)+ }++ @Test func cloudSavesAreChosenPerGameAndTurnedOff() async throws {+ let box = try Sandbox()+ let folder = box.root.appendingPathComponent("iCloud/Game Saves", isDirectory: true)+ try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)+ let model = ShellHostModel(config: box.config(), picker: FakePicker(url: folder))+ await model.pickCloudSavesNow(Fixtures.orbit)+ #expect(try detail(model).cloudSaves == "Game Saves")+ #expect(try detail(model, Fixtures.chain).cloudSaves == nil)+ #expect(box.defaults(Fixtures.orbit).data(forKey: "cloudSavesBookmark") != nil)+ #expect(try detail(ShellHostModel(config: box.config())).cloudSaves == "Game Saves")+ model.actions.onDisableCloudSaves(Fixtures.orbit)+ #expect(try detail(model).cloudSaves == nil)+ #expect(box.defaults(Fixtures.orbit).data(forKey: "cloudSavesBookmark") == nil)+ }++ @Test func aStaleCloudFolderAsksForANewChoice() throws {+ let box = try Sandbox()+ box.defaults(Fixtures.orbit).set(Data("junk".utf8), forKey: "cloudSavesBookmark")+ box.defaults(Fixtures.orbit).set(Data("junk".utf8), forKey: "pickedDataBookmark")+ let orbit = try detail(ShellHostModel(config: box.config()))+ #expect(orbit.cloudSaves == nil && orbit.cloudNote.contains("choose it again"))+ #expect(orbit.dataNote.contains("no longer readable"))+ }++ @Test func showLogReadsTheGamesLogOrSaysThereIsNone() throws {+ let box = try Sandbox()+ let model = ShellHostModel(config: box.config())+ model.actions.onShowLog(Fixtures.orbit)+ #expect(model.log?.title == "Orbit Fixture" && model.log?.text == nil)+ try box.write("boot ok\nframe 1\n", to: box.appData.appendingPathComponent(Fixtures.orbit).appendingPathComponent("log.txt"))+ model.actions.onShowLog(Fixtures.orbit)+ #expect(model.log?.text == "boot ok\nframe 1\n" && model.log?.truncated == false)+ }++ @Test func aLongLogShowsItsEnd() throws {+ let box = try Sandbox()+ let url = box.appData.appendingPathComponent("log.txt")+ try box.write(String(repeating: "a", count: 100) + "END", to: url)+ let read = try #require(LogReader.read(url, maxBytes: 10))+ #expect(read.text == "aaaaaaaEND" && read.truncated)+ #expect(LogReader.read(box.root.appendingPathComponent("nope.txt")) == nil)+ }++ @Test func appUpdateOpensTheConfiguredURL() throws {+ let box = try Sandbox()+ let opened = LogBox()+ let url = URL(string: "https://example.invalid/update")!+ let model = ShellHostModel(config: box.config(updateURL: url, open: { opened.add($0.absoluteString) }))+ model.actions.onAppUpdate()+ #expect(opened.all == ["https://example.invalid/update"])+ let none = ShellHostModel(config: box.config())+ none.actions.onAppUpdate()+ #expect(none.notice != nil)+ }++ @Test func playHandsAPlayableGameToTheLauncher() async throws {+ let box = try Sandbox()+ try box.giveAppData()+ box.defaults(Fixtures.orbit).set("0", forKey: "launcher.DM_OPMODE")+ let launcher = RecordingLauncher()+ let model = ShellHostModel(config: box.config(), launcher: launcher)+ await model.playNow(Fixtures.orbit)+ let game = try #require(launcher.launched.first)+ #expect(game.titleID == Fixtures.orbit && game.environment["DM_OPMODE"] == "0" && game.environment["DM_SHOW_FPS"] == "0")+ #expect(game.dataURL.lastPathComponent == Fixtures.orbit && game.frameworkURL.lastPathComponent == "DmGame.framework")+ #expect(game.cloudSavesURL == nil && model.notice == nil)+ }++ @Test func theStubShowsThatLaunchingIsNotAvailable() async throws {+ let box = try Sandbox()+ try box.giveAppData()+ let model = ShellHostModel(config: box.config(), launcher: StubGameLauncher(log: { _ in }))+ await model.playNow(Fixtures.orbit)+ #expect(model.notice == "Launching is not available yet.")+ }++ @Test func playIgnoresGamesThatCannotStart() async throws {+ let box = try Sandbox()+ try box.giveAppData()+ let launcher = RecordingLauncher()+ let model = ShellHostModel(config: box.config(), launcher: launcher)+ for id in [Fixtures.chain, Fixtures.noFramework, Fixtures.badManifest, "0100000000999999"] { await model.playNow(id) }+ let needsData = ShellHostModel(config: try Sandbox().config(), launcher: launcher)+ await needsData.playNow(Fixtures.orbit)+ #expect(launcher.launched.isEmpty)+ }++ @Test func aFailingLauncherShowsItsError() async throws {+ let box = try Sandbox()+ try box.giveAppData()+ let launcher = RecordingLauncher()+ launcher.error = GameProblem(reason: "Out of memory")+ let model = ShellHostModel(config: box.config(), launcher: launcher)+ await model.playNow(Fixtures.orbit)+ #expect(model.notice == "Out of memory")+ }++ @Test func connectedControllersBecomeControllerInfo() {+ let c = ConnectedController(id: "a", name: "Pro Controller", player: 2, family: .nintendo, batteryPercent: 40, charging: true)+ #expect(ShellHostModel.info(for: c) == ControllerInfo(id: "a", name: "Pro Controller", player: "Player 2", batteryPercent: 40, charging: true))+ }+}diff --git a/frontend-ios/Tests/ShellHostTests/TestSupport.swift b/frontend-ios/Tests/ShellHostTests/TestSupport.swiftnew file mode 100644index 00000000..af2e921d--- /dev/null+++ b/frontend-ios/Tests/ShellHostTests/TestSupport.swift@@ -0,0 +1,64 @@+import CoreGraphics+import Foundation+import ImageIO+import UniformTypeIdentifiers+@testable import ShellHost++enum Fixtures {+ static var gamesURL: URL { Bundle.module.url(forResource: "Fixtures", withExtension: nil)!.appendingPathComponent("Games") }+ static let orbit = "0100000000010000", chain = "0100000000020000", newerOS = "0100000000030000", noFramework = "0100000000040000"+ static let badManifest = "0100000000050000", missingKey = "0100000000060000", badSettings = "0100000000070000"+}++/// A temporary folder with a copy of the fixture bundles and an empty app data root, removed with the object.+final class Sandbox: @unchecked Sendable {+ let root = FileManager.default.temporaryDirectory.appendingPathComponent("shellhost-\(UUID().uuidString)", isDirectory: true)+ var games: URL { root.appendingPathComponent("Games", isDirectory: true) }+ var appData: URL { root.appendingPathComponent("Documents/games", isDirectory: true) }+ let suite = "shellhost.tests.\(UUID().uuidString)."++ init() throws {+ try FileManager.default.createDirectory(at: appData, withIntermediateDirectories: true)+ try FileManager.default.copyItem(at: Fixtures.gamesURL, to: games)+ }+ deinit {+ try? FileManager.default.removeItem(at: root)+ for id in ["0100000000010000", "0100000000020000", "0100000000030000"] { UserDefaults().removePersistentDomain(forName: suite + id) }+ }++ func defaults(_ id: String) -> UserDefaults { UserDefaults(suiteName: suite + id)! }++ func config(chain: String? = "b-3f9a2c", os: OperatingSystemVersion = OperatingSystemVersion(majorVersion: 26, minorVersion: 0, patchVersion: 0),+ updateURL: URL? = nil, open: @escaping @MainActor @Sendable (URL) -> Void = { _ in }) -> ShellHostConfig {+ let suite = suite+ return ShellHostConfig(gamesRoot: games, appDataRoot: appData, environment: HostEnvironment(chain: chain, osVersion: os),+ updateURL: updateURL, defaults: { UserDefaults(suiteName: suite + $0)! }, openURL: open)+ }++ /// The game's app data folder with the marker file the orbit fixture's manifest names (not game data: an empty file).+ @discardableResult func giveAppData(_ id: String = Fixtures.orbit) throws -> URL {+ let dir = appData.appendingPathComponent(id, isDirectory: true)+ let tree = dir.appendingPathComponent("romfs", isDirectory: true)+ try FileManager.default.createDirectory(at: tree, withIntermediateDirectories: true)+ try Data().write(to: tree.appendingPathComponent("fixture.marker"))+ return dir+ }++ func write(_ text: String, to url: URL) throws {+ try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)+ try Data(text.utf8).write(to: url)+ }+}++func pngData(width: Int, height: Int) -> Data {+ let space = CGColorSpace(name: CGColorSpace.sRGB)!+ let context = CGContext(data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: 0, space: space,+ bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)!+ context.setFillColor(CGColor(red: 0.2, green: 0.4, blue: 0.5, alpha: 1))+ context.fill(CGRect(x: 0, y: 0, width: width, height: height))+ let out = NSMutableData()+ let destination = CGImageDestinationCreateWithData(out, UTType.png.identifier as CFString, 1, nil)!+ CGImageDestinationAddImage(destination, context.makeImage()!, nil)+ CGImageDestinationFinalize(destination)+ return out as Data+}diff --git a/frontend-ios/UITests/ShellHostUITests.swift b/frontend-ios/UITests/ShellHostUITests.swiftnew file mode 100644index 00000000..96b1c380--- /dev/null+++ b/frontend-ios/UITests/ShellHostUITests.swift@@ -0,0 +1,41 @@+import XCTest++/// `--host`: the views on the real host layer, with the fixture bundles in the app's Games folder.+@MainActor final class ShellHostUITests: XCTestCase {+ private let app = XCUIApplication()+ override func setUpWithError() throws { continueAfterFailure = false }++ private func launch(select id: String) {+ XCUIDevice.shared.orientation = .portrait+ app.launchArguments = ["--host", "--select", id]+ app.launch()+ XCTAssertTrue(app.buttons["tile.\(id)"].waitForExistence(timeout: 10))+ }++ func testPlayableFixtureSaysLaunchingIsNotAvailable() {+ launch(select: "0100000000010000")+ XCTAssertEqual(app.staticTexts["hero.title"].label, "Orbit Fixture")+ let primary = app.buttons.matching(identifier: "state.action").allElementsBoundByIndex.first { $0.isHittable }+ XCTAssertNotNil(primary)+ primary?.tap()+ XCTAssertTrue(app.alerts["Shell"].waitForExistence(timeout: 5))+ XCTAssertTrue(app.alerts.staticTexts["Launching is not available yet."].exists)+ app.alerts.buttons["OK"].tap()+ }++ func testBrokenFixtureShowsItsReason() {+ launch(select: "0100000000040000")+ XCTAssertEqual(app.staticTexts["hero.title"].label, "No Framework Fixture")+ XCTAssertTrue(app.staticTexts.matching(NSPredicate(format: "label CONTAINS[c] 'Game code missing'")).firstMatch.waitForExistence(timeout: 5))+ }++ func testSettingChangeSurvivesReopeningSettings() {+ launch(select: "0100000000010000")+ let settings = app.buttons["settings.open"]+ if settings.exists { settings.tap() }+ let frameRate = app.switches["setting.DM_SHOW_FPS"]+ XCTAssertTrue(frameRate.waitForExistence(timeout: 5))+ frameRate.tap()+ XCTAssertEqual(frameRate.value as? String, "1")+ }+}