Skip to content

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

iOS shell host: games from the embedded frameworks, and the engine's launch plan

v0lumehia0858b4f75f9
diff --git a/frontend-ios/Sources/ShellHost/EngineLaunchPlan.swift b/frontend-ios/Sources/ShellHost/EngineLaunchPlan.swift
new file mode 100644
index 00000000..b2373889
--- /dev/null
+++ b/frontend-ios/Sources/ShellHost/EngineLaunchPlan.swift
@@ -0,0 +1,99 @@
+import Foundation
+
+/// What the shell app's real launcher applies to start one game's engine: the environment (set with overwrite, before
+/// the engine reads anything), the `dm_main` arguments and the framework to load. Computed from a `LaunchableGame` and
+/// the app's locations, mirroring `boot_env()` in `dm/ios/Sources/main.m` and the table in `docs/launcher-c-plan.md`
+/// ("Environment at game start"). Pure: the only side effect is `createFolders()`, called explicitly.
+public struct EngineLaunchPlan: Equatable, Sendable {
+ /// Set with overwrite, before the engine reads anything.
+ public var environment: [String: String]
+ /// `dm_main` argv: `["dmhost", "<framework>/dm", <manifest modules...>]`.
+ public var arguments: [String]
+ /// `<framework>/<manifest.framework_executable>`.
+ public var frameworkExecutable: URL
+ /// `manifest.image_marker`: the symbol or section that tells the loader which image is the game's.
+ public var imageMarker: String
+ /// `Documents/log.txt`, the engine log the per-game app also writes.
+ public var logURL: URL
+ /// `Documents`.
+ public var workingDirectory: URL
+ /// The save and temp folders.
+ public var foldersToCreate: [URL]
+
+ public static func make(game: LaunchableGame, appResources: URL, documents: URL, envFileText: String?,
+ fileManager fm: FileManager = .default) -> EngineLaunchPlan {
+ let manifest = game.manifest, fw = game.frameworkURL, gdir = game.appFolder
+ func isDirectory(_ url: URL) -> Bool {
+ var isDir: ObjCBool = false
+ return fm.fileExists(atPath: url.path, isDirectory: &isDir) && isDir.boolValue
+ }
+ var env: [String: String] = [:]
+
+ let perGameProfile = gdir.appendingPathComponent("profile.tsv")
+ env["DM_PROFILE"] = (fm.fileExists(atPath: perGameProfile.path) ? perGameProfile : fw.appendingPathComponent(manifest.profile)).path
+ if let romfs = romfs(in: game.dataURL, manifest: manifest, fm, isDirectory) { env["DM_ROMFS"] = romfs.path }
+ let save = gdir.appendingPathComponent("save", isDirectory: true), temp = gdir.appendingPathComponent("temp", isDirectory: true)
+ env["DM_SAVE"] = save.path
+ env["DM_TEMP"] = temp.path
+ env["DM_NVN_SHMAP"] = fw.appendingPathComponent(manifest.shaderMap).path
+ let ownMSL = gdir.appendingPathComponent("msl", isDirectory: true)
+ env["DM_MSL_DIR"] = (isDirectory(ownMSL) ? ownMSL : fw.appendingPathComponent("msl", isDirectory: true)).path
+ let ownPSO = gdir.appendingPathComponent("pso", isDirectory: true), fwPSO = fw.appendingPathComponent("pso", isDirectory: true)
+ if isDirectory(ownPSO) { env["DM_PSO_BUNDLE"] = ownPSO.path } else if isDirectory(fwPSO) { env["DM_PSO_BUNDLE"] = fwPSO.path }
+ let dataAOC = game.dataURL.appendingPathComponent("aoc", isDirectory: true), ownAOC = gdir.appendingPathComponent("aoc", isDirectory: true)
+ if isDirectory(dataAOC) { env["DM_AOC_DIR"] = dataAOC.path } else if isDirectory(ownAOC) { env["DM_AOC_DIR"] = ownAOC.path }
+ env["DM_CHEATS"] = gdir.appendingPathComponent("cheats", isDirectory: true).path
+ env["DM_FONT_DIR"] = appResources.appendingPathComponent("dm/font", isDirectory: true).path
+ if let cloud = game.cloudSavesURL { env["DM_SAVE_SYNC"] = cloud.path }
+ // The shell already showed its own settings, the per-game launcher screen stays out of the way.
+ env["DM_LAUNCHER"] = "0"
+ for (key, value) in game.environment { env[key] = value }
+
+ var fromFile: [String] = []
+ for (key, value) in parseEnvFile(envFileText ?? "") where env[key] == nil {
+ env[key] = value
+ fromFile.append(key)
+ }
+ env["DM_ENV_FILE_KEYS"] = fromFile.joined(separator: " ")
+
+ return EngineLaunchPlan(
+ environment: env,
+ arguments: ["dmhost", fw.appendingPathComponent("dm", isDirectory: true).path] + manifest.modules,
+ frameworkExecutable: fw.appendingPathComponent(manifest.frameworkExecutable),
+ imageMarker: manifest.imageMarker,
+ logURL: documents.appendingPathComponent("log.txt"),
+ workingDirectory: documents,
+ foldersToCreate: [save, temp])
+ }
+
+ /// Creates the save and temp folders (and their parents) when they are missing.
+ public func createFolders(fileManager fm: FileManager = .default) throws {
+ for url in foldersToCreate { try fm.createDirectory(at: url, withIntermediateDirectories: true) }
+ }
+
+ /// `KEY=VALUE` lines in order: `#` starts a comment line, blank lines and lines without `=` or with an empty key
+ /// are skipped, whitespace around a line is trimmed (as `boot_env` reads `env.txt`).
+ public static func parseEnvFile(_ text: String) -> [(key: String, value: String)] {
+ var result: [(key: String, value: String)] = []
+ for raw in text.components(separatedBy: .newlines) {
+ let line = raw.trimmingCharacters(in: .whitespaces)
+ guard !line.isEmpty, !line.hasPrefix("#"), let eq = line.firstIndex(of: "="), eq != line.startIndex else { continue }
+ result.append((key: String(line[..<eq]), value: String(line[line.index(after: eq)...])))
+ }
+ return result
+ }
+
+ /// `DM_ROMFS`: a non-empty `romfs.img` (any case, the exact name first, like `romfs_document_images`), else a
+ /// `romfs/` tree or the folder itself, each only when it holds the manifest's marker.
+ private static func romfs(in data: URL, manifest: GameManifest, _ fm: FileManager, _ isDirectory: (URL) -> Bool) -> URL? {
+ let marker = manifest.romfsMarker
+ let names = ((try? fm.contentsOfDirectory(atPath: data.path)) ?? []).filter { $0.lowercased() == "romfs.img" }
+ for name in names.sorted(by: { ($0 == "romfs.img" ? 0 : 1, $0) < ($1 == "romfs.img" ? 0 : 1, $1) }) {
+ let url = data.appendingPathComponent(name)
+ if DataLocator.isComplete(url, manifest: manifest, fm) { return url } // a partial copy is not the game's image
+ }
+ for tree in [data.appendingPathComponent("romfs", isDirectory: true), data]
+ where isDirectory(tree) && fm.fileExists(atPath: tree.appendingPathComponent(marker).path) { return tree }
+ return nil
+ }
+}
diff --git a/frontend-ios/Sources/ShellHost/GameCatalogue.swift b/frontend-ios/Sources/ShellHost/GameCatalogue.swift
index 3db0d5cf..1f3094ed 100644
--- a/frontend-ios/Sources/ShellHost/GameCatalogue.swift
+++ b/frontend-ios/Sources/ShellHost/GameCatalogue.swift
@@ -35,11 +35,14 @@ public struct CatalogueEntry: Equatable, Sendable, Identifiable {
/// Never the bare title ID: an unreadable bundle is "Unknown game". The ID is shown only in the How to fix sheet.
public var title: String { manifest?.name ?? readableName ?? hostText("Unknown game") }
- public var frameworkURL: URL? { manifest.map { directory.appendingPathComponent($0.framework, isDirectory: true) } }
+ /// The game's framework folder: inside `directory` for a `Games/<title ID>/` bundle, `directory` itself for an
+ /// embedded `<Name>.framework`. Nil while the manifest could not be read.
+ public var frameworkURL: URL?
}
/// 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.
+/// manifest's `<name>.framework` and optional `banner.<ext>` and `icon.<ext>` pictures, or, in the shell app, the
+/// embedded `<Name>.framework` folders that hold the manifest and everything else themselves. Pure reads, no state.
public enum GameCatalogue {
public static let imageExtensions = ["png", "jpg", "jpeg", "heic", "webp"]
@@ -50,7 +53,17 @@ public enum GameCatalogue {
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))
+ if name.hasSuffix(".framework") {
+ // Other frameworks (the Swift runtime, say) can sit next to the games: not a game, not listed.
+ guard fm.fileExists(atPath: dir.appendingPathComponent("game.manifest.json").path) else { continue }
+ var entry = readFramework(at: dir, fileManager: fm)
+ if let first = entries.first(where: { $0.frameworkURL != nil && $0.directory.pathExtension == "framework" && $0.id == entry.id }) {
+ entry = brokenDuplicate(of: first, entry)
+ }
+ entries.append(entry)
+ } else {
+ 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 }
}
@@ -65,6 +78,7 @@ public enum GameCatalogue {
}
let manifest = try GameManifest.parse(data)
entry.manifest = manifest
+ entry.frameworkURL = dir.appendingPathComponent(manifest.framework, isDirectory: true)
guard manifest.titleID == id else {
throw GameProblem(cause: .filesDamaged, reason: hostText("Game files damaged"), detail: hostText("The folder is named \(id) but the manifest says \(manifest.titleID)."))
}
@@ -94,6 +108,54 @@ public enum GameCatalogue {
return entry
}
+ /// An embedded `<Name>.framework`: manifest, launcher.json, pictures and the rest all inside the folder itself.
+ public static func readFramework(at fw: URL, fileManager fm: FileManager = .default) -> CatalogueEntry {
+ let folder = fw.lastPathComponent
+ let fallbackID = String(folder.dropLast(".framework".count))
+ let manifestURL = fw.appendingPathComponent("game.manifest.json")
+ var entry = CatalogueEntry(id: fallbackID, directory: fw, bannerURL: image(named: "banner", in: fw, fm), iconURL: image(named: "icon", in: fw, fm))
+ entry.readableName = lenientName(in: manifestURL, fm)
+ do {
+ guard let data = fm.contents(atPath: manifestURL.path) else {
+ throw GameProblem(cause: .manifestMissing, reason: hostText("Game manifest missing"), detail: hostText("\(folder) has no game.manifest.json."))
+ }
+ let manifest = try GameManifest.parse(data)
+ entry.manifest = manifest
+ entry.id = manifest.titleID
+ entry.frameworkURL = fw
+ guard manifest.framework == folder else {
+ throw GameProblem(cause: .filesDamaged, reason: hostText("Game files damaged"), detail: hostText("The folder is named \(folder) but the manifest says \(manifest.framework)."))
+ }
+ let launcherData = fm.contents(atPath: fw.appendingPathComponent(manifest.launcher).path) ?? fm.contents(atPath: fw.appendingPathComponent("launcher.json").path)
+ guard let launcherData else {
+ throw GameProblem(cause: .settingsMissing, 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(cause: .filesDamaged, 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(cause: .filesDamaged, reason: hostText("Game files damaged"), detail: error.localizedDescription)
+ }
+ if let problem = entry.problem {
+ logger.error("\(folder, privacy: .public): \(problem.reason, privacy: .public): \(problem.detail, privacy: .public)")
+ }
+ return entry
+ }
+
+ /// The second framework with a title ID: broken, naming the one that was kept.
+ private static func brokenDuplicate(of first: CatalogueEntry, _ second: CatalogueEntry) -> CatalogueEntry {
+ var entry = second
+ // A distinct ID keeps both tiles apart (the list and the model look games up by ID).
+ entry.id = String(second.directory.lastPathComponent.dropLast(".framework".count))
+ entry.problem = GameProblem(cause: .filesDamaged, reason: hostText("Game files damaged"),
+ detail: hostText("\(second.directory.lastPathComponent) has the same title ID \(second.manifest?.titleID ?? "") as \(first.directory.lastPathComponent), which is used instead."))
+ return entry
+ }
+
/// The `name` of a manifest that fails validation, when the file is still JSON with a name in it.
private static func lenientName(in url: URL, _ fm: FileManager) -> String? {
guard let data = fm.contents(atPath: url.path),
@@ -144,13 +206,26 @@ public enum DataLocator {
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 }
+ if !isDir.boolValue { return url.pathExtension == "img" && isComplete(url, manifest: manifest, fm) ? url.deletingLastPathComponent() : nil }
+ if isComplete(url.appendingPathComponent("romfs.img"), manifest: manifest, 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
}
+ /// A non-empty image, and when the manifest names the image it was built for (`romfs_identity`, `size=<bytes>`), exactly that
+ /// size: a copy cut off partway (the device locked or was unplugged during the Mac launcher's copy) is not game data yet.
+ static func isComplete(_ url: URL, manifest: GameManifest, _ fm: FileManager) -> Bool {
+ guard isNonEmpty(url, fm) else { return false }
+ guard let want = expectedImageSize(manifest) else { return true }
+ return ((try? fm.attributesOfItem(atPath: url.path)[.size]) as? NSNumber)?.int64Value == want
+ }
+
+ /// `size=<bytes>` of the manifest's `romfs_identity` line (`DMROMFSID1 title=… size=… index=…`), nil without one.
+ static func expectedImageSize(_ manifest: GameManifest) -> Int64? {
+ manifest.romfsIdentity.split(separator: " ").first { $0.hasPrefix("size=") }.flatMap { Int64($0.dropFirst(5)) }
+ }
+
private static func isNonEmpty(_ url: URL, _ fm: FileManager) -> Bool {
((try? fm.attributesOfItem(atPath: url.path)[.size]) as? NSNumber)?.intValue ?? 0 > 0
}
diff --git a/frontend-ios/Tests/ShellHostTests/EngineLaunchPlanTests.swift b/frontend-ios/Tests/ShellHostTests/EngineLaunchPlanTests.swift
new file mode 100644
index 00000000..022f9c78
--- /dev/null
+++ b/frontend-ios/Tests/ShellHostTests/EngineLaunchPlanTests.swift
@@ -0,0 +1,135 @@
+import Foundation
+import Testing
+@testable import ShellHost
+
+@Suite struct EngineLaunchPlanTests {
+ /// A game over a temporary framework and app folders. Nothing in `gdir` or the data folder exists until a test adds it.
+ struct Rig {
+ let box: FrameworkBox
+ let fw: URL
+ let gdir: URL
+ let data: URL
+ var game: LaunchableGame
+
+ init(environment: [String: String] = [:], cloud: URL? = nil) throws {
+ box = try FrameworkBox()
+ fw = try box.makeFramework()
+ gdir = box.documents.appendingPathComponent("games/\(Fixtures.orbit)", isDirectory: true)
+ data = box.root.appendingPathComponent("data", isDirectory: true)
+ try box.makeFolder(data)
+ let entry = try #require(GameCatalogue.scan(root: box.frameworks).first)
+ game = LaunchableGame(titleID: entry.id, name: entry.title, manifest: try #require(entry.manifest), directory: fw, frameworkURL: fw,
+ dataURL: data, appFolder: gdir, environment: environment, cloudSavesURL: cloud)
+ }
+ func plan(envFile: String? = nil) -> EngineLaunchPlan {
+ EngineLaunchPlan.make(game: game, appResources: box.resources, documents: box.documents, envFileText: envFile)
+ }
+ }
+
+ @Test func defaultsPointIntoTheFramework() throws {
+ let rig = try Rig()
+ let env = rig.plan().environment
+ #expect(env["DM_PROFILE"] == rig.fw.path + "/profile.tsv")
+ #expect(env["DM_NVN_SHMAP"] == rig.fw.path + "/dm/shader_map.tsv")
+ #expect(env["DM_MSL_DIR"] == rig.fw.path + "/msl")
+ #expect(env["DM_PSO_BUNDLE"] == nil && env["DM_AOC_DIR"] == nil && env["DM_ROMFS"] == nil && env["DM_SAVE_SYNC"] == nil)
+ #expect(env["DM_SAVE"] == rig.gdir.path + "/save" && env["DM_TEMP"] == rig.gdir.path + "/temp")
+ #expect(env["DM_CHEATS"] == rig.gdir.path + "/cheats")
+ #expect(env["DM_FONT_DIR"] == rig.box.resources.path + "/dm/font")
+ #expect(env["DM_LAUNCHER"] == "0")
+ #expect(env["DM_ENV_FILE_KEYS"] == "")
+ }
+
+ @Test func perGameFilesWinWhenPresent() throws {
+ let rig = try Rig()
+ try rig.box.write("x", to: rig.gdir.appendingPathComponent("profile.tsv"))
+ try rig.box.makeFolder(rig.gdir.appendingPathComponent("msl"))
+ try rig.box.makeFolder(rig.gdir.appendingPathComponent("pso"))
+ try rig.box.makeFolder(rig.fw.appendingPathComponent("pso"))
+ let env = rig.plan().environment
+ #expect(env["DM_PROFILE"] == rig.gdir.path + "/profile.tsv")
+ #expect(env["DM_MSL_DIR"] == rig.gdir.path + "/msl")
+ #expect(env["DM_PSO_BUNDLE"] == rig.gdir.path + "/pso")
+ }
+
+ @Test func psoFallsBackToTheFramework() throws {
+ let rig = try Rig()
+ try rig.box.makeFolder(rig.fw.appendingPathComponent("pso"))
+ #expect(rig.plan().environment["DM_PSO_BUNDLE"] == rig.fw.path + "/pso")
+ }
+
+ @Test func romfsImageIsMatchedCaseInsensitively() throws {
+ let rig = try Rig()
+ try rig.box.write("x", to: rig.data.appendingPathComponent("Romfs.IMG"))
+ try rig.box.write("", to: rig.data.appendingPathComponent("fixture.marker"))
+ let found = try #require(rig.plan().environment["DM_ROMFS"])
+ #expect(found.lowercased() == rig.data.path.lowercased() + "/romfs.img", "the image wins over the marker in the same folder")
+ }
+
+ @Test func emptyImageFallsThroughToTheTree() throws {
+ let rig = try Rig()
+ try rig.box.write("", to: rig.data.appendingPathComponent("romfs.img"))
+ try rig.box.write("", to: rig.data.appendingPathComponent("romfs/fixture.marker"))
+ #expect(rig.plan().environment["DM_ROMFS"] == rig.data.path + "/romfs")
+ }
+
+ @Test func dataFolderItselfWithTheMarker() throws {
+ let rig = try Rig()
+ #expect(rig.plan().environment["DM_ROMFS"] == nil)
+ try rig.box.write("", to: rig.data.appendingPathComponent("fixture.marker"))
+ #expect(rig.plan().environment["DM_ROMFS"] == rig.data.path)
+ }
+
+ @Test func aocFromDataThenFromTheAppFolder() throws {
+ let rig = try Rig()
+ try rig.box.makeFolder(rig.gdir.appendingPathComponent("aoc"))
+ #expect(rig.plan().environment["DM_AOC_DIR"] == rig.gdir.path + "/aoc")
+ try rig.box.makeFolder(rig.data.appendingPathComponent("aoc"))
+ #expect(rig.plan().environment["DM_AOC_DIR"] == rig.data.path + "/aoc")
+ }
+
+ @Test func settingsAndCloudFolderAreSet() throws {
+ let cloud = URL(fileURLWithPath: "/tmp/cloud-saves/", isDirectory: true)
+ let rig = try Rig(environment: ["DM_LANG": "de", "DM_SHOW_FPS": "1"], cloud: cloud)
+ let env = rig.plan().environment
+ #expect(env["DM_LANG"] == "de" && env["DM_SHOW_FPS"] == "1")
+ #expect(env["DM_SAVE_SYNC"] == "/tmp/cloud-saves")
+ }
+
+ @Test func envFileParsing() {
+ let text = "# comment\n\n DM_A=1 \nnoequals\n=novalue\nDM_B=x=y\r\n # indented comment\nDM_C=\n"
+ let pairs = EngineLaunchPlan.parseEnvFile(text)
+ #expect(pairs.map(\.key) == ["DM_A", "DM_B", "DM_C"])
+ #expect(pairs.map(\.value) == ["1", "x=y", ""])
+ #expect(EngineLaunchPlan.parseEnvFile("").isEmpty)
+ }
+
+ @Test func envFileNeverOverridesAndListsItsKeys() throws {
+ let rig = try Rig(environment: ["DM_LANG": "de"])
+ let env = rig.plan(envFile: "DM_LANG=fr\nDM_SAVE=/elsewhere\nDM_LAUNCHER=1\nDM_TRACE=2\nDM_OTHER=3\n").environment
+ #expect(env["DM_LANG"] == "de" && env["DM_SAVE"] == rig.gdir.path + "/save" && env["DM_LAUNCHER"] == "0")
+ #expect(env["DM_TRACE"] == "2" && env["DM_OTHER"] == "3")
+ #expect(env["DM_ENV_FILE_KEYS"] == "DM_TRACE DM_OTHER")
+ }
+
+ @Test func argumentsExecutableAndLocations() throws {
+ let rig = try Rig()
+ let plan = rig.plan()
+ #expect(plan.arguments == ["dmhost", rig.fw.path + "/dm", "main", "sdk"])
+ #expect(plan.frameworkExecutable.path == rig.fw.path + "/DmGame")
+ #expect(plan.imageMarker == "dmgame_image_marker")
+ #expect(plan.logURL.path == rig.box.documents.path + "/log.txt")
+ #expect(plan.workingDirectory.path == rig.box.documents.path)
+ #expect(plan.foldersToCreate.map(\.path) == [rig.gdir.path + "/save", rig.gdir.path + "/temp"])
+ }
+
+ @Test func makingThePlanCreatesNothingButCreateFoldersDoes() throws {
+ let rig = try Rig()
+ let plan = rig.plan()
+ #expect(!FileManager.default.fileExists(atPath: rig.gdir.path))
+ try plan.createFolders()
+ for url in plan.foldersToCreate { #expect(FileManager.default.fileExists(atPath: url.path)) }
+ #expect(!FileManager.default.fileExists(atPath: rig.gdir.path + "/cheats"))
+ try plan.createFolders()
+ }
+}
diff --git a/frontend-ios/Tests/ShellHostTests/FrameworkCatalogueTests.swift b/frontend-ios/Tests/ShellHostTests/FrameworkCatalogueTests.swift
new file mode 100644
index 00000000..d9ddac11
--- /dev/null
+++ b/frontend-ios/Tests/ShellHostTests/FrameworkCatalogueTests.swift
@@ -0,0 +1,74 @@
+import Foundation
+import Testing
+@testable import ShellHost
+
+@Suite struct FrameworkCatalogueTests {
+ @Test func listsAGameFrameworkWithItsManifestName() throws {
+ let box = try FrameworkBox()
+ let fw = try box.makeFramework()
+ let entries = GameCatalogue.scan(root: box.frameworks)
+ #expect(entries.count == 1)
+ let entry = try #require(entries.first)
+ #expect(entry.id == Fixtures.orbit && entry.title == "Orbit Fixture")
+ #expect(entry.problem == nil && entry.profile != nil)
+ #expect(entry.directory.path == fw.path && entry.frameworkURL?.path == fw.path)
+ }
+
+ @Test func skipsFrameworksWithoutAManifest() throws {
+ let box = try FrameworkBox()
+ try box.makeFolder(box.frameworks.appendingPathComponent("libswiftCore.framework"))
+ try box.makeFramework()
+ #expect(GameCatalogue.scan(root: box.frameworks).map(\.id) == [Fixtures.orbit])
+ }
+
+ @Test func aDamagedManifestStaysListedWithTheFolderName() throws {
+ let box = try FrameworkBox()
+ try box.write("{", to: box.frameworks.appendingPathComponent("Broken.framework/game.manifest.json"))
+ let entry = try #require(GameCatalogue.scan(root: box.frameworks).first)
+ #expect(entry.id == "Broken" && entry.problem != nil && entry.frameworkURL == nil)
+ }
+
+ @Test func aNameMismatchIsBroken() throws {
+ let box = try FrameworkBox()
+ try box.makeFramework(folder: "Renamed.framework", manifestFramework: "DmGame.framework")
+ let entry = try #require(GameCatalogue.scan(root: box.frameworks).first)
+ #expect(entry.problem?.reason == "Game files damaged")
+ #expect(entry.problem?.detail.contains("Renamed.framework") == true && entry.problem?.detail.contains("DmGame.framework") == true)
+ }
+
+ @Test func theSecondFrameworkWithATitleIDIsBroken() throws {
+ let box = try FrameworkBox()
+ try box.makeFramework(folder: "A.framework")
+ try box.makeFramework(folder: "B.framework")
+ let entries = GameCatalogue.scan(root: box.frameworks)
+ #expect(entries.count == 2)
+ let a = try #require(entries.first { $0.directory.lastPathComponent == "A.framework" })
+ let b = try #require(entries.first { $0.directory.lastPathComponent == "B.framework" })
+ #expect(a.problem == nil && a.id == Fixtures.orbit)
+ #expect(b.problem?.reason == "Game files damaged" && b.problem?.detail.contains("A.framework") == true)
+ #expect(a.id != b.id)
+ }
+
+ @Test func launcherFileFallbackAndPicturesAreFoundInsideTheFramework() throws {
+ let box = try FrameworkBox()
+ let fw = try box.makeFramework(launcherAt: "launcher.json")
+ try box.write("x", to: fw.appendingPathComponent("icon.png"))
+ try box.write("x", to: fw.appendingPathComponent("banner.jpg"))
+ let entry = try #require(GameCatalogue.scan(root: box.frameworks).first)
+ #expect(entry.problem == nil)
+ #expect(entry.iconURL?.lastPathComponent == "icon.png" && entry.bannerURL?.lastPathComponent == "banner.jpg")
+ #expect(entry.iconURL?.deletingLastPathComponent().path == fw.path)
+ }
+
+ @Test func launcherJSONInsideDmIsFound() throws {
+ let box = try FrameworkBox()
+ try box.makeFramework(launcherAt: "dm/launcher.json")
+ #expect(GameCatalogue.scan(root: box.frameworks).first?.problem == nil)
+ }
+
+ @Test func theGamesFolderLayoutStillSetsTheFrameworkURL() throws {
+ let entry = GameCatalogue.read(directory: Fixtures.gamesURL.appendingPathComponent(Fixtures.orbit))
+ #expect(entry.frameworkURL?.lastPathComponent == "DmGame.framework")
+ #expect(entry.frameworkURL?.deletingLastPathComponent().lastPathComponent == Fixtures.orbit)
+ }
+}
diff --git a/frontend-ios/Tests/ShellHostTests/FrameworkTestSupport.swift b/frontend-ios/Tests/ShellHostTests/FrameworkTestSupport.swift
new file mode 100644
index 00000000..fb0e4392
--- /dev/null
+++ b/frontend-ios/Tests/ShellHostTests/FrameworkTestSupport.swift
@@ -0,0 +1,35 @@
+import Foundation
+@testable import ShellHost
+
+/// A temporary folder standing in for `<App>/Frameworks`, removed with the object. Only manifests, a launcher list and
+/// empty files, never game data.
+final class FrameworkBox: @unchecked Sendable {
+ let root = FileManager.default.temporaryDirectory.appendingPathComponent("shellhost-fw-\(UUID().uuidString)", isDirectory: true)
+ var frameworks: URL { root.appendingPathComponent("Frameworks", isDirectory: true) }
+ var documents: URL { root.appendingPathComponent("Documents", isDirectory: true) }
+ var resources: URL { root.appendingPathComponent("App", isDirectory: true) }
+ init() throws { try FileManager.default.createDirectory(at: frameworks, withIntermediateDirectories: true) }
+ deinit { try? FileManager.default.removeItem(at: root) }
+
+ /// Makes `<folder>` with the orbit fixture's manifest (its `framework` and `title_id` replaced) and launcher list.
+ @discardableResult func makeFramework(folder: String = "DmGame.framework", titleID: String = Fixtures.orbit, manifestFramework: String? = nil,
+ launcherAt: String = "dm/launcher.json") throws -> URL {
+ let fw = frameworks.appendingPathComponent(folder, isDirectory: true)
+ let source = Fixtures.gamesURL.appendingPathComponent(Fixtures.orbit)
+ var manifest = try String(contentsOf: source.appendingPathComponent("game.manifest.json"), encoding: .utf8)
+ manifest = manifest.replacingOccurrences(of: Fixtures.orbit, with: titleID)
+ .replacingOccurrences(of: "\"DmGame.framework\"", with: "\"\(manifestFramework ?? folder)\"")
+ var launcher = try String(contentsOf: source.appendingPathComponent("launcher.json"), encoding: .utf8)
+ launcher = launcher.replacingOccurrences(of: Fixtures.orbit, with: titleID)
+ try write(manifest, to: fw.appendingPathComponent("game.manifest.json"))
+ try write(launcher, to: fw.appendingPathComponent(launcherAt))
+ return fw
+ }
+
+ 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 makeFolder(_ url: URL) throws { try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true) }
+}
diff --git a/frontend-ios/Tests/ShellHostTests/PartialImageTests.swift b/frontend-ios/Tests/ShellHostTests/PartialImageTests.swift
new file mode 100644
index 00000000..14bacb94
--- /dev/null
+++ b/frontend-ios/Tests/ShellHostTests/PartialImageTests.swift
@@ -0,0 +1,34 @@
+import Foundation
+import Testing
+@testable import ShellHost
+
+/// A romfs.img cut off partway (the Mac launcher's copy stopped when the device locked or was unplugged) is not game data: the
+/// game keeps asking for its data, and the engine is never pointed at the short file. The manifest's identity names the size.
+@Suite struct PartialImageTests {
+ func manifest(identity: String) throws -> GameManifest {
+ let url = Fixtures.gamesURL.appendingPathComponent(Fixtures.orbit).appendingPathComponent("game.manifest.json")
+ let text = try String(contentsOf: url, encoding: .utf8)
+ .replacingOccurrences(of: "\"DMROMFSID1 fixture\"", with: "\"\(identity)\"")
+ return try GameManifest.parse(Data(text.utf8))
+ }
+
+ @Test func theSizeComesFromTheIdentityLine() throws {
+ #expect(DataLocator.expectedImageSize(try manifest(identity: "DMROMFSID1 title=0100000000010000 version=1.0 build=v0 size=12 index=ab")) == 12)
+ #expect(DataLocator.expectedImageSize(try manifest(identity: "DMROMFSID1 fixture")) == nil)
+ }
+
+ @Test func aShortImageIsNotGameDataAndTheFullOneIs() throws {
+ let box = try FrameworkBox()
+ let folder = box.documents.appendingPathComponent("games/0100000000010000", isDirectory: true)
+ try box.makeFolder(folder)
+ let m = try manifest(identity: "DMROMFSID1 title=0100000000010000 version=1.0 build=v0 size=12 index=ab")
+ let image = folder.appendingPathComponent("romfs.img")
+ try Data(count: 5).write(to: image)
+ #expect(DataLocator.locate(manifest: m, picked: .none, appFolder: folder).found == false)
+ try Data(count: 12).write(to: image)
+ #expect(DataLocator.locate(manifest: m, picked: .none, appFolder: folder).url == folder)
+ // Without a size in the identity (a folder build), any non-empty image counts, as before
+ try Data(count: 5).write(to: image)
+ #expect(DataLocator.locate(manifest: try manifest(identity: "DMROMFSID1 fixture"), picked: .none, appFolder: folder).found)
+ }
+}