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: find each game in the shell data folder by its image's identity
v0lumehidc267a6146cc
diff --git a/frontend-ios/Sources/ShellHost/GameCatalogue.swift b/frontend-ios/Sources/ShellHost/GameCatalogue.swiftindex 794e0c96..17a15dd5 100644--- a/frontend-ios/Sources/ShellHost/GameCatalogue.swift+++ b/frontend-ios/Sources/ShellHost/GameCatalogue.swift@@ -190,13 +190,14 @@ public struct DataResolution: Equatable, Sendable {}/// 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. It differs in the-/// shell-level folder, which the per-game app has no counterpart for: one folder serves every game, so it is searched as-/// `<folder>/<title ID>/` first (one `romfs.img` per game, DLC in `aoc/` beside it), then as the folder itself, the-/// layout for a single game. The order is the game's own pick, the shell folder, then the app folder.+/// app's `Documents/games/<title ID>/`, each accepted only when it holds the game's image or marker. It differs by the+/// shell-level folder, which the per-game app has no counterpart for: one folder serves every game. The order is the game's+/// own pick, then in the shell folder `shellMatch` (the folder of the image with the game's identity, found by+/// `ShellDataIndex` whatever the folder is called), `<folder>/<title ID>/` by name (instant, no scan), the folder itself+/// (the layout for a single game), and last the app's folder. All shell folder cases say `.shell`.public enum DataLocator {public static func locate(manifest: GameManifest, picked: BookmarkResolution, appFolder: URL, fileManager fm: FileManager = .default,- global: BookmarkResolution = .none) -> DataResolution {+ global: BookmarkResolution = .none, shellMatch: URL? = nil) -> DataResolution {var result = DataResolution.missingswitch picked {case .stale: result.pickedIsStale = true@@ -206,6 +207,8 @@ public enum DataLocator {}switch global { // the shell-level data folder: the game's own bookmark wins, this backs it upcase .url(let url):+ // `shellMatch`: the folder whose image has this game's identity (`ShellDataIndex`), whatever the folder is called.+ if let match = shellMatch, let dir = holder(of: match, manifest: manifest, fm) { result.url = dir; result.source = .shell; return result }let titleFolder = url.appendingPathComponent(manifest.titleID, isDirectory: true)if let dir = holder(of: titleFolder, manifest: manifest, fm) ?? holder(of: url, manifest: manifest, fm) {result.url = dir; result.source = .shell; return resultdiff --git a/frontend-ios/Sources/ShellHost/RomfsIdentity.swift b/frontend-ios/Sources/ShellHost/RomfsIdentity.swiftnew file mode 100644index 00000000..777c440b--- /dev/null+++ b/frontend-ios/Sources/ShellHost/RomfsIdentity.swift@@ -0,0 +1,126 @@+import Foundation++/// The identity of a RomFS image (DMROMFS1): its size and a hash of its header and index, never of the file data. The+/// same computation as `romfs_id_of_image` in `dm/host/romfs_identity.h`, so it matches the `romfs_identity` line the+/// game's manifest carries (`DMROMFSID1 title=… version=… build=… size=<bytes> index=<16 hex digits>`).+struct RomfsIdentity: Equatable, Sendable {+ var size: UInt64+ var index: UInt64++ private static let offsetBasis: UInt64 = 0xcbf29ce484222325, prime: UInt64 = 0x100000001b3, chunk: UInt64 = 1 << 20++ /// FNV-1a 64 over the little-endian 64-bit words of `bytes`, zero-padded to a multiple of 8 (`romfs_id_mix`).+ static func mix(_ hash: UInt64, _ bytes: [UInt8]) -> UInt64 {+ var h = hash+ var i = 0+ while i < bytes.count {+ var word: UInt64 = 0+ for k in 0..<8 where i + k < bytes.count { word |= UInt64(bytes[i + k]) << (8 * UInt64(k)) }+ h = (h ^ word) &* prime+ i += 8+ }+ return h+ }++ /// The `size=` and `index=` of an identity line, nil when the line has no magic, or lacks either (`romfs_id_parse`).+ static func parse(_ line: String) -> RomfsIdentity? {+ let fields = line.split(whereSeparator: { $0 == " " || $0 == "\n" })+ guard fields.first == "DMROMFSID1" else { return nil }+ var size: UInt64?, index: UInt64?+ for field in fields.dropFirst() {+ guard let eq = field.firstIndex(of: "=") else { continue }+ let value = field[field.index(after: eq)...]+ switch field[..<eq] {+ case "size": guard let v = UInt64(value) else { return nil }; size = v+ case "index": guard let v = UInt64(value, radix: 16) else { return nil }; index = v+ default: break+ }+ }+ guard let size, let index else { return nil }+ return RomfsIdentity(size: size, index: index)+ }++ /// The identity of the image at `url`, nil for a missing, cut off or invalid image (`romfs_id_of_image`).+ static func ofImage(at url: URL) -> RomfsIdentity? {+ guard let handle = try? FileHandle(forReadingFrom: url) else { return nil }+ defer { try? handle.close() }+ guard let total = try? handle.seekToEnd(), (try? handle.seek(toOffset: 0)) != nil,+ let head = try? handle.read(upToCount: 32), head.count == 32 else { return nil }+ let h = [UInt8](head)+ func word(_ at: Int) -> UInt64 { (0..<8).reduce(0) { $0 | UInt64(h[at + $1]) << (8 * UInt64($1)) } }+ let indexOffset = word(8), indexSize = word(16)+ guard Array(h[0..<8]) == Array("DMROMFS1".utf8), indexOffset >= 32, indexOffset <= total, indexSize == total - indexOffset else { return nil }+ var hash = mix(offsetBasis, h)+ do {+ try handle.seek(toOffset: indexOffset)+ var left = indexSize+ while left > 0 {+ guard let data = try handle.read(upToCount: Int(min(left, chunk))), !data.isEmpty else { return nil }+ hash = mix(hash, [UInt8](data))+ left -= UInt64(data.count)+ }+ } catch { return nil }+ return RomfsIdentity(size: total, index: hash)+ }+}++/// The `romfs.img` files under a folder the player picked for every game, found by the image's own identity so the folder+/// names do not matter. A scan lists the folder one and two levels down (a bounded number of entries, hidden items and+/// symbolic links skipped, so no loop and no deep walk of an external drive) and `stat`s each image. Only an image with the+/// size of the game's `romfs_identity` is read (its header and index), and that identity is remembered per image.+/// This reads the drive, so it runs off the main actor (`ShellHostModel` starts it and shows the games as needing data+/// until it is done).+final class ShellDataIndex: @unchecked Sendable {+ static let maxEntries = 2000++ let folder: URL+ private let fm: FileManager+ private let lock = NSLock()+ private var images: [(url: URL, size: UInt64)] = []+ private var identities: [URL: RomfsIdentity?] = [:]++ init(folder: URL, fileManager: FileManager = .default) {+ self.folder = folder+ fm = fileManager+ scan()+ }++ /// `<folder>/*/romfs.img` and `<folder>/*/*/romfs.img` (any case of the name), up to `maxEntries` entries listed.+ private func scan() {+ var seen = 0+ func children(_ dir: URL) -> [URL] {+ let urls = (try? fm.contentsOfDirectory(at: dir, includingPropertiesForKeys: [.isDirectoryKey, .isSymbolicLinkKey, .fileSizeKey],+ options: [.skipsHiddenFiles])) ?? []+ seen += urls.count+ return urls.sorted { $0.lastPathComponent < $1.lastPathComponent }+ }+ func visit(_ dir: URL, depth: Int) {+ for url in children(dir) where seen <= Self.maxEntries {+ let values = try? url.resourceValues(forKeys: [.isDirectoryKey, .isSymbolicLinkKey, .fileSizeKey])+ if values?.isSymbolicLink == true { continue }+ if values?.isDirectory == true {+ if depth < 2 { visit(url, depth: depth + 1) }+ } else if depth >= 1, url.lastPathComponent.lowercased() == "romfs.img", let size = values?.fileSize, size > 0 {+ images.append((url, UInt64(size)))+ }+ }+ }+ visit(folder, depth: 0)+ }++ /// The folder of the image that is this game's: the size equals `want.size` and the identity equals `want`.+ func folder(matching want: RomfsIdentity) -> URL? {+ for image in images where image.size == want.size {+ lock.lock()+ let known = identities[image.url]+ lock.unlock()+ let identity: RomfsIdentity?+ if let known { identity = known } else {+ identity = RomfsIdentity.ofImage(at: image.url)+ lock.lock(); identities[image.url] = .some(identity); lock.unlock()+ }+ if identity == want { return image.url.deletingLastPathComponent() }+ }+ return nil+ }+}diff --git a/frontend-ios/Sources/ShellHost/ShellHostModel.swift b/frontend-ios/Sources/ShellHost/ShellHostModel.swiftindex acde06ce..d7ead35b 100644--- a/frontend-ios/Sources/ShellHost/ShellHostModel.swift+++ b/frontend-ios/Sources/ShellHost/ShellHostModel.swift@@ -70,6 +70,10 @@ public struct ShellHostConfig: Sendable {@ObservationIgnored private let shellData: BookmarkStore@ObservationIgnored private let shellCloud: BookmarkStore@ObservationIgnored private var shellChoices: [String]+ /// The shell data folder the games were matched in by identity, each game's matched folder by title ID, and the scan in flight.+ @ObservationIgnored private var scannedShellFolder: String?+ @ObservationIgnored private var shellMatches: [String: URL] = [:]+ @ObservationIgnored private var shellScan: Task<Void, Never>?@ObservationIgnored nonisolated(unsafe) private var defaultsObserver: (any NSObjectProtocol)?public init(config: ShellHostConfig, launcher: any GameLauncher = StubGameLauncher(), picker: any FolderPicker = NoFolderPicker(),@@ -97,9 +101,41 @@ public struct ShellHostConfig: Sendable {/// Builds the details again, in the same order. A change of a shell folder or of the performance overlay comes through here.public func refreshAll() {shellChoices = Self.choices(of: shellSettings)+ startShellScan()details = entries.map(detail(for:))}+ /// Looks for every game's image by identity in the shell data folder. The drive is read off the main actor: until the scan is+ /// done the games show what the by-name paths give (usually "Needs game data"), then the details are built again. A new+ /// folder starts a new scan and drops the old matches, the same folder keeps its matches unless `force`.+ private func startShellScan(force: Bool = false) {+ guard case .url(let folder) = shellData.resolve() else {+ shellScan?.cancel(); scannedShellFolder = nil; shellMatches = [:]; return+ }+ if !force && scannedShellFolder == folder.path { return }+ shellScan?.cancel()+ scannedShellFolder = folder.path+ shellMatches = [:]+ let wanted = entries.compactMap { e in+ e.problem == nil ? e.manifest.flatMap { m in RomfsIdentity.parse(m.romfsIdentity).map { (m.titleID, $0) } } : nil+ }+ guard !wanted.isEmpty else { return }+ shellScan = Task { [weak self] in+ let found = await Task.detached(priority: .utility) { () -> [String: URL] in+ let index = ShellDataIndex(folder: folder)+ var found: [String: URL] = [:]+ for (titleID, identity) in wanted where !Task.isCancelled { if let dir = index.folder(matching: identity) { found[titleID] = dir } }+ return found+ }.value+ guard let self, !Task.isCancelled, self.scannedShellFolder == folder.path else { return }+ self.shellMatches = found+ if !found.isEmpty { self.details = self.entries.map(self.detail(for:)) }+ }+ }++ /// For tests: returns when the scan of the shell data folder is done.+ func waitForShellScan() async { await shellScan?.value }+private func defaultsDidChange() {if Self.choices(of: shellSettings) != shellChoices { refreshAll() }}@@ -116,6 +152,7 @@ public struct ShellHostConfig: Sendable {let position = Dictionary(uniqueKeysWithValues: order.enumerated().map { ($1, $0) })entries = scanned.sorted { position[$0.id] ?? 0 < position[$1.id] ?? 0 }details = built.sorted { position[$0.id] ?? 0 < position[$1.id] ?? 0 }+ startShellScan(force: true)}private func lastPlayed(_ id: String) -> Date? { LastPlayedStore(defaults: config.defaults(id)).date }@@ -161,7 +198,7 @@ public struct ShellHostConfig: Sendable {private func data(for entry: CatalogueEntry) -> DataResolution {guard let manifest = entry.manifest, entry.problem == nil else { return .missing }return DataLocator.locate(manifest: manifest, picked: dataStore(entry.id).resolve(), appFolder: appFolder(for: entry.id),- global: shellData.resolve())+ global: shellData.resolve(), shellMatch: shellMatches[manifest.titleID])}private func image(_ url: URL?) -> Artwork? {diff --git a/frontend-ios/Sources/ShellUI/Resources/Localizable.xcstrings b/frontend-ios/Sources/ShellUI/Resources/Localizable.xcstringsindex 3b9dda52..54790553 100644--- a/frontend-ios/Sources/ShellUI/Resources/Localizable.xcstrings+++ b/frontend-ios/Sources/ShellUI/Resources/Localizable.xcstrings@@ -401,18 +401,18 @@}}},- "Games look for their data here. Put one folder per game inside, named by its title ID, with its romfs.img in it. Each game can also have a folder of its own.": {+ "Games look for their data here. Keep one romfs.img per game in any folder inside. Each game is found by the image itself, so the folder names do not matter. Each game can also have a folder of its own.": {"localizations": {"en": {"stringUnit": {"state": "translated",- "value": "Games look for their data here. Put one folder per game inside, named by its title ID, with its romfs.img in it. Each game can also have a folder of its own."+ "value": "Games look for their data here. Keep one romfs.img per game in any folder inside. Each game is found by the image itself, so the folder names do not matter. Each game can also have a folder of its own."}},"zh-Hans": {"stringUnit": {"state": "translated",- "value": "游戏会在这里查找游戏数据。请为每个游戏放一个以 Title ID 命名的文件夹,其中放入它的 romfs.img。每个游戏也可以单独指定文件夹。"+ "value": "游戏会在这里查找游戏数据。请在其中的任意文件夹里为每个游戏放一个 romfs.img。应用会按镜像本身识别游戏,所以文件夹名称不限。每个游戏也可以单独指定文件夹。"}}}diff --git a/frontend-ios/Sources/ShellUI/ShellSettingsView.swift b/frontend-ios/Sources/ShellUI/ShellSettingsView.swiftindex ede7cb0f..543bc7f7 100644--- a/frontend-ios/Sources/ShellUI/ShellSettingsView.swift+++ b/frontend-ios/Sources/ShellUI/ShellSettingsView.swift@@ -50,7 +50,7 @@ struct ShellSettingsView: View {}.id("shs.top")SettingsGroup(title: ShellStrings.text("Game data")) {SourceRow(symbol: "folder", title: store.dataFolderName ?? ShellStrings.text("No folder chosen"),- note: ShellStrings.text("Games look for their data here. Put one folder per game inside, named by its title ID, with its romfs.img in it. Each game can also have a folder of its own.")) {+ note: ShellStrings.text("Games look for their data here. Keep one romfs.img per game in any folder inside. Each game is found by the image itself, so the folder names do not matter. Each game can also have a folder of its own.")) {Button(ShellStrings.text("Choose folder…")) { actions.onPickShellData() }.buttonStyle(ShellButtonStyle(fills: true)).accessibilityIdentifier("shellSettings.data").shellTarget("shs.data") { actions.onPickShellData() }diff --git a/frontend-ios/Tests/ShellHostTests/ShellDataFolderTests.swift b/frontend-ios/Tests/ShellHostTests/ShellDataFolderTests.swiftindex 4bf056dc..232e1505 100644--- a/frontend-ios/Tests/ShellHostTests/ShellDataFolderTests.swift+++ b/frontend-ios/Tests/ShellHostTests/ShellDataFolderTests.swift@@ -1,13 +1,14 @@import Foundationimport Testing+import ShellUI@testable import ShellHost-/// The shell-level data folder serves every game: `<folder>/<title ID>/romfs.img` per game, the folder itself for one game.+/// The shell-level data folder serves every game: found by the image's identity in any folder name, `<folder>/<title ID>/romfs.img` by name, the folder itself for one game.@Suite struct ShellDataFolderTests {- func manifest(title: String, size: Int) throws -> GameManifest {+ func manifest(title: String, size: Int, index: String = "ab") 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: "\"DMROMFSID1 title=\(title) version=1.0 build=v0 size=\(size) index=ab\"")+ .replacingOccurrences(of: "\"DMROMFSID1 fixture\"", with: "\"DMROMFSID1 title=\(title) version=1.0 build=v0 size=\(size) index=\(index)\"").replacingOccurrences(of: Fixtures.orbit, with: title)return try GameManifest.parse(Data(text.utf8))}@@ -17,6 +18,93 @@ import Testingtry Data(count: size).write(to: url)}+ /// A DMROMFS1 image: header, 16 bytes of game data, then `index` (13 bytes here, so the hash pads to a multiple of 8).+ static func dmromfs(_ index: [UInt8], data: [UInt8] = [UInt8](repeating: 0x41, count: 16)) -> Data {+ func le(_ v: UInt64) -> [UInt8] { (0..<8).map { UInt8((v >> (8 * UInt64($0))) & 0xff) } }+ return Data(Array("DMROMFS1".utf8) + le(UInt64(32 + data.count)) + le(UInt64(index.count)) + le(0) + data + index)+ }+ static let indexA = Array(1...13).map(UInt8.init), indexB = Array(21...33).map(UInt8.init)++ func place(_ data: Data, at url: URL) throws {+ try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)+ try data.write(to: url)+ }++ func ident(_ index: [UInt8]) throws -> RomfsIdentity { try #require(RomfsIdentity.parse("DMROMFSID1 title=1 version=1 build=1 size=61 index=" + (index == Self.indexA ? "90b5abb4d1ea10d2" : "9da33c3b161c746a"))) }++ /// The folder `ShellDataIndex` finds for an identity.+ /// Compared by resolved path: the temporary folder is a symbolic link and the listing may spell it either way.+ func found(_ want: RomfsIdentity, in folder: URL) -> String? { ShellDataIndex(folder: folder).folder(matching: want)?.resolvingSymlinksInPath().path }+ func path(_ url: URL) -> String { url.resolvingSymlinksInPath().path }++ // The expected values are what `romfs_id_of_image` (dm/host/romfs_identity.h) returns for these two images.+ @Test func theIdentityIsTheOneTheCCodeComputes() throws {+ let box = try Sandbox()+ let a = box.root.appendingPathComponent("a.img"), b = box.root.appendingPathComponent("b.img")+ try place(Self.dmromfs(Self.indexA), at: a)+ try place(Self.dmromfs(Self.indexB), at: b)+ #expect(RomfsIdentity.ofImage(at: a) == RomfsIdentity(size: 61, index: 0x90b5abb4d1ea10d2))+ #expect(RomfsIdentity.ofImage(at: b) == RomfsIdentity(size: 61, index: 0x9da33c3b161c746a))+ #expect(RomfsIdentity.parse("DMROMFSID1 title=0100000000010000 version=1.0 build=v0 size=61 index=90b5abb4d1ea10d2") == RomfsIdentity(size: 61, index: 0x90b5abb4d1ea10d2))+ #expect(RomfsIdentity.parse("DMROMFSID1 fixture") == nil && RomfsIdentity.parse("DMROMFSID1 size=5") == nil && RomfsIdentity.parse("size=5 index=ab") == nil)+ }++ @Test func anInvalidOrCutOffImageHasNoIdentity() throws {+ let box = try Sandbox()+ let good = Self.dmromfs(Self.indexA)+ for (name, data) in [("short", good.prefix(40)), ("magic", Data("XXXXXXXX".utf8) + good.dropFirst(8)), ("empty", Data())] {+ try place(Data(data), at: box.root.appendingPathComponent("\(name).img"))+ #expect(RomfsIdentity.ofImage(at: box.root.appendingPathComponent("\(name).img")) == nil)+ }+ #expect(RomfsIdentity.ofImage(at: box.root.appendingPathComponent("missing.img")) == nil)+ }++ @Test func gamesInFoldersWithAnyNamesAreFoundByIdentity() throws {+ let box = try Sandbox()+ let shared = box.root.appendingPathComponent("Drive", isDirectory: true)+ try place(Self.dmromfs(Self.indexA), at: shared.appendingPathComponent("Hades II (1.0.0)/romfs.img"))+ try place(Self.dmromfs(Self.indexB), at: shared.appendingPathComponent("Switch games/whatever/ROMFS.IMG"))+ // Two images of the same size (61 bytes): only the index tells them apart.+ #expect(found(try ident(Self.indexA), in: shared) == path(shared.appendingPathComponent("Hades II (1.0.0)")))+ #expect(found(try ident(Self.indexB), in: shared) == path(shared.appendingPathComponent("Switch games/whatever")))+ let m = try manifest(title: Fixtures.orbit, size: 61, index: "90b5abb4d1ea10d2")+ let r = DataLocator.locate(manifest: m, picked: .none, appFolder: box.appData.appendingPathComponent(m.titleID), global: .url(shared),+ shellMatch: shared.appendingPathComponent("Hades II (1.0.0)"))+ #expect(r.source == .shell && r.url == shared.appendingPathComponent("Hades II (1.0.0)"))+ }++ @Test func aCutOffCopyOrAnotherImageIsNotAMatch() throws {+ let box = try Sandbox()+ let shared = box.root.appendingPathComponent("Drive", isDirectory: true)+ try place(Self.dmromfs(Self.indexA).prefix(50), at: shared.appendingPathComponent("Copy/romfs.img"))+ #expect(found(try ident(Self.indexA), in: shared) == nil)+ // The size fits but the index does not.+ try place(Self.dmromfs(Self.indexB), at: shared.appendingPathComponent("Other/romfs.img"))+ #expect(found(try ident(Self.indexA), in: shared) == nil)+ }++ @Test func theScanIsBounded() throws {+ let box = try Sandbox()+ let shared = box.root.appendingPathComponent("Drive", isDirectory: true)+ let image = Self.dmromfs(Self.indexA)+ try place(image, at: shared.appendingPathComponent("one/two/romfs.img"))+ #expect(found(try ident(Self.indexA), in: shared) == path(shared.appendingPathComponent("one/two")), "two levels down")+ try FileManager.default.removeItem(at: shared)+ try place(image, at: shared.appendingPathComponent("one/two/three/romfs.img"))+ #expect(found(try ident(Self.indexA), in: shared) == nil, "three levels down is not looked at")+ try FileManager.default.removeItem(at: shared)+ try place(image, at: shared.appendingPathComponent(".hidden/romfs.img"))+ try FileManager.default.createDirectory(at: box.root.appendingPathComponent("Real"), withIntermediateDirectories: true)+ try place(image, at: box.root.appendingPathComponent("Real/romfs.img"))+ try FileManager.default.createSymbolicLink(at: shared.appendingPathComponent("Link"), withDestinationURL: box.root.appendingPathComponent("Real"))+ try FileManager.default.createSymbolicLink(at: shared.appendingPathComponent("Loop"), withDestinationURL: shared)+ #expect(found(try ident(Self.indexA), in: shared) == nil, "hidden items and symbolic links are skipped")+ try FileManager.default.removeItem(at: shared)+ for i in 0..<(ShellDataIndex.maxEntries + 100) { try place(Data(), at: shared.appendingPathComponent("a/f\(i)")) }+ try place(image, at: shared.appendingPathComponent("z/romfs.img"))+ #expect(found(try ident(Self.indexA), in: shared) == nil, "a folder with more entries than the cap ends the scan")+ }+@Test func oneFolderHoldsSeveralGames() throws {let box = try Sandbox()let shared = box.root.appendingPathComponent("Drive/All", isDirectory: true)@@ -69,3 +157,86 @@ import Testing#expect(FileManager.default.fileExists(atPath: try #require(r.url).appendingPathComponent("aoc/0.img").path))}}++extension ShellDataFolderTests {+ @Test func dlcSitsBesideTheMatchedImage() throws {+ let box = try Sandbox()+ let shared = box.root.appendingPathComponent("Drive", isDirectory: true)+ let folder = shared.appendingPathComponent("My game", isDirectory: true)+ try place(Self.dmromfs(Self.indexA), at: folder.appendingPathComponent("romfs.img"))+ try place(Data(count: 3), at: folder.appendingPathComponent("aoc/0.img"))+ try FileManager.default.createDirectory(at: folder.appendingPathComponent("aoc/1"), withIntermediateDirectories: true)+ let m = try manifest(title: Fixtures.orbit, size: 61, index: "90b5abb4d1ea10d2")+ let match = try #require(ShellDataIndex(folder: shared).folder(matching: try ident(Self.indexA)))+ let r = DataLocator.locate(manifest: m, picked: .none, appFolder: box.appData.appendingPathComponent(m.titleID), global: .url(shared), shellMatch: match)+ let dir = try #require(r.url)+ #expect(FileManager.default.fileExists(atPath: dir.appendingPathComponent("aoc/0.img").path) && FileManager.default.fileExists(atPath: dir.appendingPathComponent("aoc/1").path))+ }++ @Test func aGameKeepsItsOwnPickAndTheMatchBeatsTheTitleFolder() throws {+ let box = try Sandbox()+ let shared = box.root.appendingPathComponent("Drive", isDirectory: true)+ let m = try manifest(title: Fixtures.orbit, size: 61, index: "90b5abb4d1ea10d2")+ let app = box.appData.appendingPathComponent(m.titleID)+ try place(Self.dmromfs(Self.indexA), at: shared.appendingPathComponent("Named/romfs.img"))+ try place(Self.dmromfs(Self.indexA), at: shared.appendingPathComponent(m.titleID).appendingPathComponent("romfs.img"))+ let named = shared.appendingPathComponent("Named")+ #expect(DataLocator.locate(manifest: m, picked: .none, appFolder: app, global: .url(shared), shellMatch: named).url == named)+ #expect(DataLocator.locate(manifest: m, picked: .none, appFolder: app, global: .url(shared)).url == shared.appendingPathComponent(m.titleID), "no match yet: by name")+ let own = box.root.appendingPathComponent("Own", isDirectory: true)+ try place(Self.dmromfs(Self.indexA), at: own.appendingPathComponent("romfs.img"))+ let r = DataLocator.locate(manifest: m, picked: .url(own), appFolder: app, global: .url(shared), shellMatch: named)+ #expect(r.source == .picked && r.url == own)+ // A match that was deleted since the scan is not game data.+ try FileManager.default.removeItem(at: named)+ #expect(DataLocator.locate(manifest: m, picked: .none, appFolder: app, global: .url(shared), shellMatch: named).url == shared.appendingPathComponent(m.titleID))+ }++ @Test func aManifestWithoutAnIdentityLineIsNotMatchedByIdentity() throws {+ #expect(RomfsIdentity.parse(try manifest(title: Fixtures.orbit, size: 5).romfsIdentity) != nil)+ let url = Fixtures.gamesURL.appendingPathComponent(Fixtures.orbit).appendingPathComponent("game.manifest.json")+ let m = try GameManifest.parse(Data(contentsOf: url))+ #expect(RomfsIdentity.parse(m.romfsIdentity) == nil, "the fixture's line is `DMROMFSID1 fixture`: only the by-name paths apply")+ }+}++final class MutablePicker: FolderPicker, @unchecked Sendable {+ var url: URL?+ init(_ url: URL?) { self.url = url }+ func pickFolder() async -> URL? { url }+}++@MainActor @Suite struct ShellDataFolderModelTests {+ private func model(_ box: Sandbox, picker: MutablePicker) -> ShellHostModel {+ ShellHostModel(config: box.config(), picker: picker,+ shellSettings: ShellSettingsStore(defaults: UserDefaults(suiteName: "t-shell-\(UUID().uuidString)")!))+ }++ @Test func theScanFindsTheGameThenANewFolderDropsIt() async throws {+ let box = try Sandbox()+ let manifestURL = box.games.appendingPathComponent(Fixtures.orbit).appendingPathComponent("game.manifest.json")+ let text = try String(contentsOf: manifestURL, encoding: .utf8)+ .replacingOccurrences(of: "\"DMROMFSID1 fixture\"", with: "\"DMROMFSID1 title=\(Fixtures.orbit) version=1.0 build=v0 size=61 index=90b5abb4d1ea10d2\"")+ try text.write(to: manifestURL, atomically: true, encoding: .utf8)+ let drive = box.root.appendingPathComponent("Drive", isDirectory: true)+ try FileManager.default.createDirectory(at: drive.appendingPathComponent("Some name"), withIntermediateDirectories: true)+ try ShellDataFolderTests.dmromfs(ShellDataFolderTests.indexA).write(to: drive.appendingPathComponent("Some name/romfs.img"))+ let empty = box.root.appendingPathComponent("Empty", isDirectory: true)+ try FileManager.default.createDirectory(at: empty, withIntermediateDirectories: true)++ let picker = MutablePicker(drive)+ let m = model(box, picker: picker)+ await m.pickShellDataNow()+ await m.waitForShellScan()+ var orbit = try #require(m.details.first { $0.id == Fixtures.orbit })+ #expect(orbit.game.state == .playable && orbit.dataFromShell)+ #expect(orbit.dataSource.hasSuffix("(from Settings)"))++ // A new folder: the old matches are gone and the new folder is scanned.+ picker.url = empty+ await m.pickShellDataNow()+ await m.waitForShellScan()+ orbit = try #require(m.details.first { $0.id == Fixtures.orbit })+ #expect(orbit.game.state == .needsGameData)+ }+}