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
Find the game's save on the device itself and choose an iPhone or iPad
v0lumehi1b9d0ce7004c
diff --git a/frontend/Sources/NSPortBuilder/Devices.swift b/frontend/Sources/NSPortBuilder/Devices.swiftindex e6655a6e..6857ca65 100644--- a/frontend/Sources/NSPortBuilder/Devices.swift+++ b/frontend/Sources/NSPortBuilder/Devices.swift@@ -42,10 +42,11 @@ struct XcodeTeam: Equatable {/// it only reads what is paired and what can sign.enum DeviceTools {/// The paired physical iPhones and iPads, reachable ones first.- static func devices(xcrun: String = "/usr/bin/xcrun") -> [AppleDevice] {+ /// `timeout` ends a listing that hangs (the Saves sheet asks with one), as no devices.+ static func devices(xcrun: String = "/usr/bin/xcrun", timeout: TimeInterval? = nil) -> [AppleDevice] {let file = FileManager.default.temporaryDirectory.appendingPathComponent("nxnative-devices-\(UUID().uuidString).json")defer { try? FileManager.default.removeItem(at: file) }- guard run(xcrun, ["devicectl", "list", "devices", "--json-output", file.path]) != nil,+ guard run(xcrun, ["devicectl", "list", "devices", "--json-output", file.path], timeout: timeout) != nil,let data = try? Data(contentsOf: file) else { return [] }return parseDevices(data)}@@ -145,7 +146,7 @@ enum DeviceTools {return subject[range].split(separator: "=").last.map { $0.trimmingCharacters(in: .whitespaces) }}- private static func run(_ tool: String, _ args: [String], input: String? = nil) -> String? {+ private static func run(_ tool: String, _ args: [String], input: String? = nil, timeout: TimeInterval? = nil) -> String? {let p = Process(), out = Pipe(), inPipe = Pipe()p.executableURL = URL(fileURLWithPath: tool)p.arguments = args@@ -153,6 +154,12 @@ enum DeviceTools {p.standardError = FileHandle.nullDevicep.standardInput = input == nil ? FileHandle.nullDevice : inPipedo { try p.run() } catch { return nil }+ if let timeout {+ DispatchQueue.global().asyncAfter(deadline: .now() + timeout) {+ if p.isRunning { p.terminate() }+ DispatchQueue.global().asyncAfter(deadline: .now() + 2) { if p.isRunning { kill(p.processIdentifier, SIGKILL) } }+ }+ }if let input { inPipe.fileHandleForWriting.write(Data(input.utf8)); try? inPipe.fileHandleForWriting.close() }let data = out.fileHandleForReading.readDataToEndOfFile()p.waitUntilExit()diff --git a/frontend/Sources/NSPortBuilder/Localization.swift b/frontend/Sources/NSPortBuilder/Localization.swiftindex 338b0419..822d5d16 100644--- a/frontend/Sources/NSPortBuilder/Localization.swift+++ b/frontend/Sources/NSPortBuilder/Localization.swift@@ -276,8 +276,12 @@ enum L10n {"saves.mac": ("这台 Mac", "This Mac"),"saves.saved": ("保存于 %@", "Saved %@"),"saves.none": ("还没有存档", "No save yet"),- "saves.reading": ("正在读取…", "Reading…"),- "saves.notInstalled": ("这个游戏没有从这里安装到 iPhone 或 iPad。在“构建”页面选择设备和签名团队安装后,就可以在这里复制存档。", "This game was not installed on an iPhone or iPad from here. Install it from the Builds page (a device and a signing team), then its save can be copied here."),+ "saves.reading": ("正在读取 %@…", "Reading %@…"),+ "saves.notInstalled": ("在 %@ 上没有找到这个游戏。请先安装,再刷新。", "This game was not found on %@. Install it there, then refresh."),+ "saves.noDevices": ("没有已配对的 iPhone 或 iPad。请在 Xcode 中配对设备并解锁,然后刷新。", "No paired iPhone or iPad found. Pair it in Xcode and unlock it, then refresh."),+ "saves.notConnected": ("%@ 未连接。请连接并解锁设备,然后刷新。", "%@ is not connected. Connect and unlock it, then refresh."),+ "saves.timeout": ("%@ 没有及时响应。请连接并解锁设备,然后刷新。", "%@ did not answer in time. Connect and unlock it, then refresh."),+ "saves.device": ("设备", "Device"),"saves.unreachable": ("无法读取:%@", "Cannot be read: %@"),"saves.newer": ("较新", "Newer"),"saves.toDevice": ("Mac → %@", "Mac → %@"),@@ -1182,8 +1186,12 @@ enum L10n {"saves.mac": "Den här Mac-datorn","saves.saved": "Sparad %@","saves.none": "Ingen sparfil ännu",- "saves.reading": "Läser …",- "saves.notInstalled": "Det här spelet har inte installerats på en iPhone eller iPad härifrån. Installera det från sidan Byggen med en enhet och ett signeringsteam. Därefter kan sparfilen kopieras hit.",+ "saves.reading": "Läser från %@ …",+ "saves.notInstalled": "Spelet hittades inte på %@. Installera det där och uppdatera sedan.",+ "saves.noDevices": "Ingen ihopparad iPhone eller iPad hittades. Para ihop den i Xcode, lås upp den och uppdatera sedan.",+ "saves.notConnected": "%@ är inte ansluten. Anslut och lås upp den och uppdatera sedan.",+ "saves.timeout": "%@ svarade inte i tid. Anslut och lås upp den och uppdatera sedan.",+ "saves.device": "Enhet","saves.unreachable": "Kan inte läsas: %@","saves.newer": "Nyare","saves.toDevice": "Mac → %@",diff --git a/frontend/Sources/NSPortBuilder/SaveDiscovery.swift b/frontend/Sources/NSPortBuilder/SaveDiscovery.swiftnew file mode 100644index 00000000..710a580c--- /dev/null+++ b/frontend/Sources/NSPortBuilder/SaveDiscovery.swift@@ -0,0 +1,194 @@+import Foundation++/// An app installed on a device, as `devicectl device info apps` lists it.+struct InstalledApp: Equatable {+ let bundle: String+ let name: String+}++/// Finding the game on the device itself, so the Saves sheet needs neither the launcher's install record nor the signed app+/// it cached (#250): a game exported as an IPA and signed by another tool (LCSign, Sideloadly, AltStore) has a data container+/// the Mac can read all the same, under whatever bundle ID that tool gave it.+enum SaveDiscovery {+ static func listCommand(device: String, json: String) -> [String] {+ ["device", "info", "apps", "--device", device, "--include-default-apps", "--include-removable-apps", "--json-output", json]+ }++ /// `result.apps` of the listing. nil for JSON that cannot be read.+ static func parseApps(_ data: Data) -> [InstalledApp]? {+ guard let root = try? JSONSerialization.jsonObject(with: data) as? [String: Any],+ let result = root["result"] as? [String: Any], let list = result["apps"] as? [[String: Any]] else { return nil }+ return list.compactMap { app in+ guard let bundle = app["bundleIdentifier"] as? String, !bundle.isEmpty else { return nil }+ return InstalledApp(bundle: bundle, name: app["name"] as? String ?? "")+ }+ }++ /// The apps on the device. A failure is the device's (not connected, locked, timed out), never "no apps".+ static func apps(device: String, devicectl: DeviceControl, scratch: URL = FileManager.default.temporaryDirectory) throws -> [InstalledApp] {+ let json = scratch.appendingPathComponent("nxnative-apps-\(UUID().uuidString).json")+ defer { try? FileManager.default.removeItem(at: json) }+ let r = devicectl.run(listCommand(device: device, json: json.path))+ guard r.ok, let data = try? Data(contentsOf: json) else { throw SaveTransfer.failure(r.output) }+ guard let apps = parseApps(data) else { throw SaveTransfer.Failure.device("devicectl") }+ return apps+ }++ /// The installed app that is this game, best match first: the bundle ID this launcher recorded, the launcher's own+ /// (`org.nxnative.<title ID>`), any bundle ID with the title ID in it (a team suffix, a re-signer's prefix), then the+ /// app's display name against the game's name or its title ID. Of equal matches the first by bundle ID wins, so the+ /// answer does not change between refreshes.+ static func match(_ apps: [InstalledApp], titleID: String, name: String, recordedBundle: String?) -> InstalledApp? {+ let id = titleID.lowercased(), wanted = name.trimmingCharacters(in: .whitespaces).lowercased()+ func rank(_ app: InstalledApp) -> Int? {+ let bundle = app.bundle.lowercased(), shown = app.name.trimmingCharacters(in: .whitespaces).lowercased()+ if let recordedBundle, !recordedBundle.isEmpty, app.bundle == recordedBundle { return 0 }+ if !id.isEmpty, bundle == "org.nxnative." + id { return 1 }+ if !id.isEmpty, bundle.contains(id) { return 2 }+ if !wanted.isEmpty, shown == wanted { return 3 }+ if !id.isEmpty, shown.contains(id) { return 3 }+ return nil+ }+ return apps.compactMap { app in rank(app).map { (rank: $0, app: app) } }+ .min { ($0.rank, $0.app.bundle) < ($1.rank, $1.app.bundle) }?.app+ }++ /// The game's app on one device and what its save holds. nil when the device has no app that is this game. `template`+ /// carries the Mac side and the title ID (its device and bundle are replaced).+ static func find(template: SaveTransfer, name: String, recordedBundle: String?, device: String) throws -> (transfer: SaveTransfer, contents: SaveTransfer.Contents)? {+ let installed = try apps(device: device, devicectl: template.devicectl, scratch: template.scratch)+ guard let app = match(installed, titleID: template.titleID, name: name, recordedBundle: recordedBundle) else { return nil }+ var transfer = SaveTransfer(titleID: template.titleID, macSave: template.macSave, legacySave: template.legacySave,+ device: device, bundle: app.bundle, devicectl: template.devicectl)+ transfer.scratch = template.scratch+ transfer.now = template.now+ return (transfer, try transfer.readDevice())+ }+}++/// What the Saves sheet shows and does: which device is asked, what it holds, and when it is safe to ask again.+///+/// Only one query runs at a time. Refresh does nothing while one runs, a query that takes longer than `timeout` ends as+/// `.timedOut` (the command underneath has its own deadline, DeviceControl.xcrun, but a hang anywhere in the chain must not+/// leave the sheet reading for good), and choosing another device cancels the one running: a result that arrives after+/// its query was given up or replaced is dropped. Used on the main thread.+final class SavesModel: ObservableObject {+ enum DeviceState: Equatable {+ case noDevices // no paired iPhone or iPad+ case notConnected // the chosen device is paired but not connected: nothing is asked of it+ case notInstalled // connected, and this game is not on it+ case reading+ case ready(SaveTransfer.Contents)+ case failed(String) // devicectl's last line+ case timedOut+ }++ let template: SaveTransfer // the Mac side, and the title ID+ let name: String+ let recordedBundle: String?+ let recordedDevice: String+ let installTarget: String // the device Builds installs to+ let listDevices: () -> [AppleDevice]+ var timeout: TimeInterval+ var rememberChoice: (String) -> Void+ private var remembered: String++ @Published private(set) var devices: [AppleDevice] = []+ @Published private(set) var selected = ""+ @Published private(set) var deviceState = DeviceState.reading+ @Published private(set) var macSave = SaveTransfer.Contents()+ @Published private(set) var found: SaveTransfer? // the game's app on the selected device, once it is ready+ private var generation = 0+ private var started = false++ init(template: SaveTransfer, name: String, recordedBundle: String?, recordedDevice: String, installTarget: String,+ remembered: String = "", rememberChoice: @escaping (String) -> Void = { _ in },+ listDevices: @escaping () -> [AppleDevice], timeout: TimeInterval = 30) {+ self.template = template; self.name = name; self.recordedBundle = recordedBundle; self.recordedDevice = recordedDevice+ self.installTarget = installTarget; self.remembered = remembered; self.rememberChoice = rememberChoice+ self.listDevices = listDevices; self.timeout = timeout+ }++ var isReading: Bool { deviceState == .reading }+ var canRefresh: Bool { !isReading }+ var deviceSave: SaveTransfer.Contents? { if case .ready(let c) = deviceState { return c }; return nil }+ var selectedDevice: AppleDevice? { devices.first { $0.id == selected } }+ /// The selector shows when there is a choice to make.+ var showsSelector: Bool { devices.count > 1 }++ /// The device to ask first: the one picked here before, the one this game was installed on, the one Builds installs to,+ /// each only while connected; else the first connected one; else whichever of those is paired, so its name is shown.+ static func defaultDevice(in list: [AppleDevice], remembered: String, recorded: String, installTarget: String) -> String? {+ let preferred = [remembered, recorded, installTarget].filter { !$0.isEmpty }+ if let id = preferred.first(where: { id in list.contains { $0.id == id && $0.reachable } }) { return id }+ if let first = list.first(where: \.reachable) { return first.id }+ return preferred.first { id in list.contains { $0.id == id } } ?? list.first?.id+ }++ /// Reads the Mac save and asks the device again, device list included. Does nothing while a query runs.+ func refresh() {+ guard canRefresh else { return }+ start(relist: true)+ }++ /// The sheet opened: the first query.+ func begin() {+ guard !started else { return }+ started = true+ start(relist: true)+ }++ /// Asks another device. A query still running is given up.+ func select(_ id: String) {+ guard id != selected || !isReading else { return }+ selected = id+ remembered = id+ rememberChoice(id)+ start(relist: false)+ }++ private func start(relist: Bool) {+ generation += 1+ let mine = generation+ macSave = template.readMac()+ deviceState = .reading+ found = nil+ let known = devices, current = selected+ let (template, name, recordedBundle) = (self.template, self.name, self.recordedBundle)+ let (remembered, recorded, target, listDevices) = (self.remembered, recordedDevice, installTarget, self.listDevices)+ DispatchQueue.global(qos: .userInitiated).async {+ let list = relist ? listDevices() : known+ let id = (list.contains { $0.id == current } ? current+ : SavesModel.defaultDevice(in: list, remembered: remembered, recorded: recorded, installTarget: target)) ?? ""+ // The list and the choice show at once, while the query still runs: the sheet says which device it is asking,+ // and another one can be chosen if this one never answers.+ DispatchQueue.main.async {+ guard mine == self.generation else { return }+ self.devices = list; self.selected = id+ }+ var state = DeviceState.reading, transfer: SaveTransfer?+ if list.isEmpty || id.isEmpty {+ state = .noDevices+ } else if list.first(where: { $0.id == id })?.reachable != true {+ state = .notConnected+ } else {+ do {+ if let hit = try SaveDiscovery.find(template: template, name: name, recordedBundle: recordedBundle, device: id) {+ state = .ready(hit.contents); transfer = hit.transfer+ } else {+ state = .notInstalled+ }+ } catch SaveTransfer.Failure.timeout { state = .timedOut } catch SaveTransfer.Failure.device(let line) { state = .failed(line) } catch { state = .failed(error.localizedDescription) }+ }+ DispatchQueue.main.async {+ guard mine == self.generation else { return } // given up or replaced meanwhile+ self.deviceState = state; self.found = transfer+ }+ }+ DispatchQueue.main.asyncAfter(deadline: .now() + timeout) { [weak self] in+ guard let self, mine == self.generation, self.deviceState == .reading else { return }+ self.generation += 1 // whatever the query still says is stale+ self.deviceState = .timedOut+ }+ }+}diff --git a/frontend/Sources/NSPortBuilder/SaveTransfer.swift b/frontend/Sources/NSPortBuilder/SaveTransfer.swiftindex 97f44330..fa7ddaaa 100644--- a/frontend/Sources/NSPortBuilder/SaveTransfer.swift+++ b/frontend/Sources/NSPortBuilder/SaveTransfer.swift@@ -1,4 +1,5 @@import AppKit+import Darwinimport SwiftUI/// `xcrun devicectl` for the save transfer, as one function: the tests hand in a stand-in, so no test ever reaches a device.@@ -6,30 +7,53 @@ import SwiftUIstruct DeviceControl {let run: ([String]) -> (ok: Bool, output: String)- static func xcrun(_ path: String) -> DeviceControl {+ /// What a command that ran out of time prints in place of devicectl's own output (and what a stand-in prints to say the same).+ static let timedOut = "devicectl timed out"++ /// Every command has a deadline: devicectl's own (`--timeout`), and behind it one on the process, because CoreDevice can+ /// stall on a paired device whose connection is not ready, and a command that never returns leaves the Saves sheet at+ /// "Reading..." for good. A copy gets the longer deadline, a query the shorter one.+ static func xcrun(_ path: String, queryTimeout: TimeInterval = 10, copyTimeout: TimeInterval = 180) -> DeviceControl {DeviceControl { args in+ let timeout = args.starts(with: ["device", "copy"]) ? copyTimeout : queryTimeoutlet p = Process(), out = Pipe()p.executableURL = URL(fileURLWithPath: path)- p.arguments = ["devicectl"] + args+ p.arguments = ["devicectl", "--timeout", String(max(1, Int(timeout.rounded(.up))))] + argsp.standardOutput = out; p.standardError = out; p.standardInput = FileHandle.nullDevicedo { try p.run() } catch { return (false, error.localizedDescription) }+ let fired = Fired()+ let deadline = DispatchWorkItem {+ fired.set()+ if p.isRunning { p.terminate() }+ DispatchQueue.global().asyncAfter(deadline: .now() + 2) { if p.isRunning { kill(p.processIdentifier, SIGKILL) } }+ }+ DispatchQueue.global().asyncAfter(deadline: .now() + timeout + 2, execute: deadline)let data = out.fileHandleForReading.readDataToEndOfFile()p.waitUntilExit()+ deadline.cancel()+ if fired.value { return (false, timedOut) }return (p.terminationStatus == 0, String(decoding: data, as: UTF8.self))}}++ private final class Fired {+ private let lock = NSLock()+ private var flag = false+ func set() { lock.lock(); flag = true; lock.unlock() }+ var value: Bool { lock.lock(); defer { lock.unlock() }; return flag }+ }}-/// A game's save on this Mac and in the app the launcher installed on a paired iPhone or iPad (#66), copied either way over-/// the route the install takes (devicectl and the app's data container). The save that is replaced is backed up on the Mac+/// A game's save on this Mac and in its app on a paired iPhone or iPad (#66), copied either way over the route the install+/// takes (devicectl and the app's data container). The save that is replaced is backed up on the Mac/// first, so a copy in the wrong direction loses nothing.////// Where the saves are: the Mac app keeps them beside itself in <app's folder>/save/<title ID> when that folder also holds/// games/ (the launcher's layout), else in ~/Library/Application Support/nxnative/<title ID>/save (dm/mac/launcher.c, DM_SAVE;/// the device save is DM_SAVE + "_device", dm/host/hle_fs.c); the iPhone app in Documents/games/<title ID>/save (dm/ios/Sources/main.m), the per-game folder it uses when the-/// game files come from Documents/games/<title ID>/, which is where the launcher's install puts them. A sideloaded IPA with-/// the game files inside keeps Documents/save instead, but the launcher knows the bundle ID (the data container) only of the-/// apps it installed, so those are the ones it copies to.+/// game files come from Documents/games/<title ID>/, which is where the launcher's install puts them, or in Documents/save+/// for a sideloaded IPA with the game files inside. Both are read (resolveDevice), and the one in use decides where a copy+/// goes. The app itself is found on the device (SaveDiscovery), not from the launcher's install records.struct SaveTransfer {/// The committed save folders (dm/host/hle_fs.c): `save`, and `save_device` for a game that mounts device save data beside/// its account save (Mario Kart 8 Deluxe). The `.work` and `.new` folders beside them are one session's uncommitted copy,@@ -48,6 +72,7 @@ struct SaveTransfer {enum Failure: Error, Equatable {case noMacSave, noDeviceSavecase device(String) // devicectl's last line+ case timeout // a command ran out of time (DeviceControl.timedOut)}/// What the device holds: the save folders with files in them, and the newest file's date.@@ -88,6 +113,7 @@ struct SaveTransfer {return nil}+ /// The per-game layout (patch 0003, the launcher's install). The other is Documents itself (resolveDevice).var deviceFolder: String { "Documents/games/\(titleID)" }/// Backups go beside the save, one folder per copy: "<date> mac" holds the Mac save a copy from the device replaced,/// "<date> device" the device save a copy from the Mac replaced.@@ -103,13 +129,35 @@ struct SaveTransfer {}}- /// Lists the game's folder on the device first: when that fails the device or the app cannot be reached, which is an- /// error; a save folder that cannot be listed after it is one the app has not made yet.- func readDevice() throws -> Contents {- _ = try list(deviceFolder, recurse: false)+ /// What the device holds, from the layout the app uses (resolveDevice).+ func readDevice() throws -> Contents { try resolveDevice().contents }++ /// Which of the two save layouts the app on the device uses, and what is in it. Documents is listed first: when that+ /// fails the device or the app cannot be reached, which is an error (a timeout is one too, never an empty save). The+ /// layout that holds a save is the one in use. With saves in both, or in neither, it is the per-game folder when that+ /// holds the game's files (the runtime then uses it, dm/ios/Sources/main.m), else Documents.+ func resolveDevice() throws -> (base: String, contents: Contents) {+ let documents = try list("Documents", recurse: false)+ let games = try readDevice(at: deviceFolder), plain = try readDevice(at: "Documents")+ switch (games.folders.isEmpty, plain.folders.isEmpty) {+ case (false, true): return (deviceFolder, games)+ case (true, false): return ("Documents", plain)+ default:+ let hasGames = Self.names(documents).contains("games")+ let files = hasGames ? (try? list(deviceFolder, recurse: false)).map(Self.names) ?? [] : []+ let perGame = !files.isDisjoint(with: ["romfs.img", "romfs"])+ return perGame ? (deviceFolder, games) : ("Documents", plain)+ }+ }++ /// The save folders under a layout. A folder that cannot be listed is one the app has not made yet, except when the+ /// command timed out: that is rethrown.+ private func readDevice(at base: String) throws -> Contents {var c = Contents()for f in Self.folders {- guard let data = try? list(deviceFolder + "/" + f, recurse: true), let entries = Self.parseListing(data), entries.files > 0 else { continue }+ let data: Data+ do { data = try list(base + "/" + f, recurse: true) } catch Failure.timeout { throw Failure.timeout } catch { continue }+ guard let entries = Self.parseListing(data), entries.files > 0 else { continue }c.folders.append(f)if let date = entries.newest { c.newest = max(c.newest ?? date, date) }}@@ -120,24 +168,35 @@ struct SaveTransfer {let json = scratch.appendingPathComponent("nxnative-files-\(UUID().uuidString).json")defer { try? FileManager.default.removeItem(at: json) }let r = devicectl.run(Self.listCommand(device: device, bundle: bundle, subdirectory: subdirectory, recurse: recurse, json: json.path))- guard r.ok, let data = try? Data(contentsOf: json) else { throw Failure.device(Self.lastLine(r.output)) }+ guard r.ok, let data = try? Data(contentsOf: json) else { throw Self.failure(r.output) }return data}+ /// The file and folder names in a non-recursive listing, lowercased.+ static func names(_ data: Data) -> Set<String> {+ guard let root = try? JSONSerialization.jsonObject(with: data) as? [String: Any],+ let result = root["result"] as? [String: Any], let files = result["files"] as? [[String: Any]] else { return [] }+ return Set(files.compactMap { ($0["name"] as? String).map { ($0 as NSString).lastPathComponent.lowercased() } })+ }++ static func failure(_ output: String) -> Failure {+ output.contains(DeviceControl.timedOut) || output.lowercased().contains("timed out") ? .timeout : .device(lastLine(output))+ }+// ---- copying ----/// The device's save replaces the Mac's. The device save comes into a folder beside the Mac's first, so a copy that/// fails leaves the Mac save as it was; then the Mac save moves into the backup and the copy takes its place./// Returns the backup, nil when the Mac had no save.func deviceToMac() throws -> URL? {- let there = try readDevice()+ let (folder, there) = try resolveDevice()guard !there.folders.isEmpty else { throw Failure.noDeviceSave }let fm = FileManager.defaultlet incoming = macSave.deletingLastPathComponent().appendingPathComponent(".save-incoming-\(UUID().uuidString)")try fm.createDirectory(at: incoming, withIntermediateDirectories: true)defer { try? fm.removeItem(at: incoming) }for f in there.folders {- try copyFrom(deviceFolder + "/" + f, to: incoming.appendingPathComponent(f))+ try copyFrom(folder + "/" + f, to: incoming.appendingPathComponent(f))}var backup: URL?// A ~/Library save the app has not brought across yet stays where it is: macSave gets the copy, so the app keeps it@@ -155,23 +214,23 @@ struct SaveTransfer {func macToDevice() throws -> URL? {let here = readMac()guard !here.folders.isEmpty else { throw Failure.noMacSave }- let there = try readDevice()+ let (folder, there) = try resolveDevice()var backup: URL?if !there.folders.isEmpty {let into = try makeBackup("device")backup = into- for f in there.folders { try copyFrom(deviceFolder + "/" + f, to: into.appendingPathComponent(f)) }+ for f in there.folders { try copyFrom(folder + "/" + f, to: into.appendingPathComponent(f)) }}for f in here.folders {- let r = devicectl.run(Self.copyToCommand(device: device, bundle: bundle, source: (macSource(f) ?? Self.macPath(f, save: macSave)).path, destination: deviceFolder + "/" + f))- guard r.ok else { throw Failure.device(Self.lastLine(r.output)) }+ let r = devicectl.run(Self.copyToCommand(device: device, bundle: bundle, source: (macSource(f) ?? Self.macPath(f, save: macSave)).path, destination: folder + "/" + f))+ guard r.ok else { throw Self.failure(r.output) }}return backup}private func copyFrom(_ source: String, to local: URL) throws {let r = devicectl.run(Self.copyFromCommand(device: device, bundle: bundle, source: source, destination: local.path))- guard r.ok else { throw Failure.device(Self.lastLine(r.output)) }+ guard r.ok else { throw Self.failure(r.output) }Self.hoist(local)guard Self.newest(in: local) != nil else { throw Failure.device(source) } // the device listed files that did not come}@@ -220,8 +279,8 @@ struct SaveTransfer {return newest}- /// `devicectl device info files --json-output`: the entries that carry a `modificationDate` (the key CoreDevice's file- /// metadata uses), wherever the JSON nests them, directories left out when an entry says it is one. nil for JSON that+ /// `devicectl device info files --json-output`: the entries that carry a `modificationDate` (or `lastModDate` in the+ /// `metadata` of the current CoreDevice), wherever the JSON nests them, directories left out when an entry says it is one. nil for JSON that/// cannot be read.static func parseListing(_ data: Data) -> (files: Int, newest: Date?)? {guard let root = try? JSONSerialization.jsonObject(with: data) else { return nil }@@ -229,14 +288,16 @@ struct SaveTransfer {func walk(_ node: Any) {if let list = node as? [Any] { list.forEach(walk); return }guard let dict = node as? [String: Any] else { return }- if let raw = dict["modificationDate"] {+ let metadata = dict["metadata"] as? [String: Any]+ let raw = dict["modificationDate"] ?? metadata?["modificationDate"] ?? metadata?["lastModDate"]+ if let raw {let kind = ["fileType", "type", "kind"].compactMap { dict[$0] as? String }.joined().lowercased()- if !kind.contains("dir") {+ if !kind.contains("dir") && (dict["resources"] as? [String: Any])?["isDirectory"] as? Bool != true {files += 1if let date = date(raw) { newest = max(newest ?? date, date) }}}- dict.values.forEach(walk)+ for (key, value) in dict where key != "metadata" || raw == nil { walk(value) }}walk(root)return (files, newest)@@ -303,31 +364,43 @@ struct SavesView: View {@ObservedObject var m: BuildModel@ObservedObject var library: GameLibrarylet gameID: UUID- var devicectl: DeviceControl? = nil // tests and the visual QA hand in a stand-invar support: URL? = nil // the Application Support folder; tests use a temporary one+ @StateObject private var model: SavesModel@Environment(\.dismiss) private var dismiss@EnvironmentObject private var focus: PadFocus- enum DeviceState: Equatable { case notInstalled, reading, ready(SaveTransfer.Contents), failed(String) }- @State private var macSave = SaveTransfer.Contents()- @State private var deviceState = DeviceState.notInstalled@State private var asking: SaveTransfer.Side? // the side whose save a copy would replace@State private var busy = false@State private var result: (text: String, ok: Bool)?- private var game: LibraryGame? { library.games.first { $0.id == gameID } }- private var deviceName: String { game.map { m.deviceName($0.installedDevice) } ?? "iPhone" }-- private var transfer: SaveTransfer? {- guard let game else { return nil }+ /// `devicectl` and `listDevices` are what tests and the visual QA hand in as stand-ins: with a stand-in devicectl and no+ /// device list, the devices are the ones the launcher already knows, so nothing asks the system for them.+ init(m: BuildModel, library: GameLibrary, gameID: UUID, devicectl: DeviceControl? = nil, support: URL? = nil,+ listDevices: (() -> [AppleDevice])? = nil, timeout: TimeInterval = 30) {+ self.m = m; self.library = library; self.gameID = gameID; self.support = support+ let game = library.games.first { $0.id == gameID } ?? LibraryGame(titleID: "", name: "")let mac = support.map { SaveTransfer.macSave(titleID: game.titleID, appPath: game.appPath, support: $0) }?? SaveTransfer.macSave(titleID: game.titleID, appPath: game.appPath)- let bundle = NSDictionary(contentsOfFile: game.iosAppPath + "/Info.plist")?["CFBundleIdentifier"] as? String ?? ""- return SaveTransfer(titleID: game.titleID, macSave: mac.save, legacySave: mac.legacy, device: game.installedDevice, bundle: bundle,- devicectl: devicectl ?? .xcrun(m.xcrunPath))+ let control = devicectl ?? .xcrun(m.xcrunPath)+ let template = SaveTransfer(titleID: game.titleID, macSave: mac.save, legacySave: mac.legacy, device: "", bundle: "", devicectl: control)+ let known = m.devices, xcrun = m.xcrunPath+ let list: () -> [AppleDevice] = listDevices ?? (devicectl == nil ? { DeviceTools.devices(xcrun: xcrun, timeout: 10) } : { known })+ let key = "saveTransfer.device." + game.titleID+ _model = StateObject(wrappedValue: SavesModel(+ template: template, name: game.name,+ recordedBundle: NSDictionary(contentsOfFile: game.iosAppPath + "/Info.plist")?["CFBundleIdentifier"] as? String,+ recordedDevice: game.installedDevice, installTarget: m.installDevice,+ remembered: UserDefaults.standard.string(forKey: key) ?? "",+ rememberChoice: { UserDefaults.standard.set($0, forKey: key) },+ listDevices: list, timeout: timeout))}- private var deviceSave: SaveTransfer.Contents? { if case .ready(let c) = deviceState { return c }; return nil }+ private var game: LibraryGame? { library.games.first { $0.id == gameID } }+ private var macSave: SaveTransfer.Contents { model.macSave }+ private var deviceSave: SaveTransfer.Contents? { model.deviceSave }+ /// The device the sheet asks: its name, or what the launcher recorded when the list has not come yet.+ private var deviceName: String { model.selectedDevice?.name ?? game.map { m.deviceName($0.installedDevice) } ?? "iPhone" }+ private var transfer: SaveTransfer { model.found ?? model.template }var body: some View {VStack(alignment: .leading, spacing: 0) {@@ -335,7 +408,17 @@ struct SavesView: View {Text(m.t("saves.title")).font(.manrope(26, .heavy)).tracking(-0.6)if let game { Text(game.name).font(.manrope(14)).foregroundStyle(.secondary) }}- .padding(.horizontal, 30).padding(.top, 28).padding(.bottom, 20)+ .padding(.horizontal, 30).padding(.top, 28).padding(.bottom, model.showsSelector ? 12 : 20)+ if model.showsSelector {+ HStack(spacing: 12) {+ Text(m.t("saves.device")).font(.manrope(13)).foregroundStyle(.secondary)+ LauncherMenuPicker(options: model.devices.map { d in+ (value: d.id, label: d.name + (d.reachable ? "" : " (" + m.t("dev.notConnected") + ")"))+ }, selection: model.selected) { model.select($0) }+ .padTarget("saves.device", scope: "saves") {}+ }+ .padding(.horizontal, 30).padding(.bottom, 16)+ }VStack(alignment: .leading, spacing: 18) {card {sideRow(.mac)@@ -377,7 +460,7 @@ struct SavesView: View {.font(.manrope(13)).preferredColorScheme(.dark).tint(LauncherPalette.cream)- .onAppear(perform: refresh)+ .onAppear { model.begin() }}private func card<Content: View>(@ViewBuilder _ content: () -> Content) -> some View {@@ -392,15 +475,18 @@ struct SavesView: View {switch side {case .mac: detail = macSave.newest.map { String(format: m.t("saves.saved"), dateText($0)) } ?? m.t("saves.none")case .device:- switch deviceState {- case .notInstalled: detail = m.t("saves.notInstalled")- case .reading: detail = m.t("saves.reading")+ switch model.deviceState {+ case .noDevices: detail = m.t("saves.noDevices")+ case .notConnected: detail = String(format: m.t("saves.notConnected"), deviceName)+ case .notInstalled: detail = String(format: m.t("saves.notInstalled"), deviceName)+ case .reading: detail = String(format: m.t("saves.reading"), deviceName)case .failed(let why): detail = String(format: m.t("saves.unreachable"), why)+ case .timedOut: detail = String(format: m.t("saves.timeout"), deviceName)case .ready(let c): detail = c.newest.map { String(format: m.t("saves.saved"), dateText($0)) } ?? m.t("saves.none")}}return HStack(spacing: 14) {- Image(systemName: side == .mac ? "desktopcomputer" : "iphone").font(.system(size: 18, weight: .light))+ Image(systemName: side == .mac ? "desktopcomputer" : (model.selectedDevice?.model.lowercased().contains("ipad") == true ? "ipad" : "iphone")).font(.system(size: 18, weight: .light)).foregroundStyle(.secondary).frame(width: 26)VStack(alignment: .leading, spacing: 3) {Text(side == .mac ? m.t("saves.mac") : deviceName).font(.manrope(14, .medium))@@ -427,9 +513,9 @@ struct SavesView: View {Button(String(format: m.t("saves.toMac"), deviceName)) { ask(.mac) }.disabled(!toMac).padTarget("saves.toMac", scope: "saves") { if toMac { ask(.mac) } }Spacer(minLength: 8)- Button(m.t("dev.refresh")) { refresh() }.disabled(busy)- .padTarget("saves.refresh", scope: "saves") { if !busy { refresh() } }- if let transfer, FileManager.default.fileExists(atPath: transfer.backups.path) {+ Button(m.t("dev.refresh")) { model.refresh() }.disabled(busy || !model.canRefresh)+ .padTarget("saves.refresh", scope: "saves") { if !busy { model.refresh() } }+ if FileManager.default.fileExists(atPath: transfer.backups.path) {Button(m.t("saves.backups")) { NSWorkspace.shared.open(transfer.backups) }.padTarget("saves.backups", scope: "saves") { NSWorkspace.shared.open(transfer.backups) }}@@ -442,7 +528,7 @@ struct SavesView: View {VStack(alignment: .leading, spacing: 12) {Text(replacing == .device ? String(format: m.t("saves.askToDevice"), deviceName) : String(format: m.t("saves.askToMac"), deviceName)).font(.manrope(15, .semibold)).fixedSize(horizontal: false, vertical: true)- Text(String(format: m.t("saves.askNote"), deviceName, transfer.map { m.shortPath($0.backups.path) } ?? ""))+ Text(String(format: m.t("saves.askNote"), deviceName, m.shortPath(transfer.backups.path))).font(.manrope(12.5)).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)HStack(spacing: 10) {Spacer()@@ -469,18 +555,6 @@ struct SavesView: View {return f.string(from: date)}- private func refresh() {- guard let transfer, let game else { return }- macSave = transfer.readMac()- guard game.onDevice, !transfer.bundle.isEmpty else { deviceState = .notInstalled; return }- deviceState = .reading- DispatchQueue.global(qos: .userInitiated).async {- let state: DeviceState- do { state = .ready(try transfer.readDevice()) } catch { state = .failed(message(error)) }- DispatchQueue.main.async { deviceState = state }- }- }-private func ask(_ replacing: SaveTransfer.Side) {result = nilguard let game, !SaveTransfer.runningOnMac(titleID: game.titleID) else {@@ -493,7 +567,7 @@ struct SavesView: View {private func copy(_ replacing: SaveTransfer.Side) {asking = nil- guard let transfer, let game else { return }+ guard let game, let transfer = model.found else { return }if SaveTransfer.runningOnMac(titleID: game.titleID) { // started while the question was openresult = (String(format: m.t("saves.running"), game.name), false)return@@ -508,7 +582,7 @@ struct SavesView: View {DispatchQueue.main.async {busy = falseresult = outcome- refresh()+ model.refresh()focus.focused = "saves.done"}}@@ -519,6 +593,7 @@ struct SavesView: View {case .noMacSave: return m.t("saves.noMacSave")case .noDeviceSave: return String(format: m.t("saves.noDeviceSave"), deviceName)case .device(let line): return line+ case .timeout: return String(format: m.t("saves.timeout"), deviceName)case nil: return error.localizedDescription}}diff --git a/frontend/Tests/NSPortBuilderTests/LibraryTests.swift b/frontend/Tests/NSPortBuilderTests/LibraryTests.swiftindex 0dfb9ef0..6fa5af01 100644--- a/frontend/Tests/NSPortBuilderTests/LibraryTests.swift+++ b/frontend/Tests/NSPortBuilderTests/LibraryTests.swift@@ -1155,12 +1155,19 @@ final class LibraryTests: XCTestCase {try FileManager.default.setAttributes([.modificationDate: Date(timeIntervalSinceNow: -3 * 86_400)], ofItemAtPath: save.path)let device = DeviceControl { args in // a device whose save is from an hour agoguard let i = args.firstIndex(of: "--json-output") else { return (false, "ERROR: not in the visual QA") }+ if args.starts(with: ["device", "info", "apps"]) {+ try? JSONSerialization.data(withJSONObject: ["result": ["apps": [["bundleIdentifier": "com.example.hades", "name": game.name]]]]).write(to: URL(fileURLWithPath: args[i + 1]))+ return (true, "")+ }let files = args.contains("--recurse") ? [["name": "data.bin", "fileType": "file", "modificationDate": ISO8601DateFormatter().string(from: Date(timeIntervalSinceNow: -3600))]] : []try? JSONSerialization.data(withJSONObject: ["result": ["files": files]]).write(to: URL(fileURLWithPath: args[i + 1]))return (true, "")}let focus = PadFocus()- let host = NSHostingView(rootView: SavesView(m: model, library: library, gameID: game.id, devicectl: device, support: support).environmentObject(focus))+ let host = NSHostingView(rootView: SavesView(m: model, library: library, gameID: game.id, devicectl: device, support: support, listDevices: {+ [AppleDevice(id: "00008150-AAAA", name: "Zijad\u{2019}s iPhone", model: "iPhone 17", os: "27.0", reachable: true),+ AppleDevice(id: "00008150-BBBB", name: "Zijad\u{2019}s iPad", model: "iPad Pro", os: "27.0", reachable: true)]+ }).environmentObject(focus))let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 600, height: 520), styleMask: [.titled], backing: .buffered, defer: false)window.contentView = hostwindow.orderFront(nil)diff --git a/frontend/Tests/NSPortBuilderTests/SaveDiscoveryTests.swift b/frontend/Tests/NSPortBuilderTests/SaveDiscoveryTests.swiftnew file mode 100644index 00000000..436581a1--- /dev/null+++ b/frontend/Tests/NSPortBuilderTests/SaveDiscoveryTests.swift@@ -0,0 +1,308 @@+import XCTest+@testable import NSPortBuilder++/// Issue #250: the game's save found on the device itself, a choice between an iPhone and an iPad, and a device that does not+/// answer. devicectl is the stand-in of SaveTransferTests (a folder per device), so no test reaches a device.+final class SaveDiscoveryTests: XCTestCase {+ private typealias Fake = SaveTransferTests.FakeDevice+ private var temporary: URL!+ private let titleID = "0100535012974000"+ private let fm = FileManager.default+ private let older = Date(timeIntervalSince1970: 1_700_000_000), newer = Date(timeIntervalSince1970: 1_760_000_000)+ private let iPhone = AppleDevice(id: "PHONE", name: "Zijad's iPhone", model: "iPhone 17", os: "27.0", reachable: true)+ private let iPad = AppleDevice(id: "PAD", name: "Zijad's iPad", model: "iPad Pro", os: "27.0", reachable: true)++ override func setUpWithError() throws {+ temporary = fm.temporaryDirectory.appendingPathComponent("nxnative-discovery-" + UUID().uuidString)+ try fm.createDirectory(at: temporary, withIntermediateDirectories: true)+ }++ override func tearDownWithError() throws { try fm.removeItem(at: temporary) }++ private func write(_ text: String, _ url: URL, date: Date) throws {+ try fm.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)+ try Data(text.utf8).write(to: url)+ try fm.setAttributes([.modificationDate: date], ofItemAtPath: url.path)+ }++ private func read(_ url: URL) -> String? { (try? Data(contentsOf: url)).map { String(decoding: $0, as: UTF8.self) } }++ private func fake(_ name: String) -> Fake { Fake(temporary.appendingPathComponent(name)) }++ /// Routes a command to the device it names, as devicectl does.+ private func fleet(_ devices: [String: Fake]) -> DeviceControl {+ DeviceControl { args in+ guard let i = args.firstIndex(of: "--device"), let device = devices[args[i + 1]] else { return (false, "ERROR: no such device") }+ return device.control.run(args)+ }+ }++ private func template(_ control: DeviceControl) -> SaveTransfer {+ let mac = SaveTransfer.legacyMacSave(titleID: titleID, support: temporary.appendingPathComponent("Application Support"))+ var t = SaveTransfer(titleID: titleID, macSave: mac, device: "", bundle: "", devicectl: control)+ t.scratch = temporary+ t.now = { Date(timeIntervalSince1970: 1_800_000_000) }+ return t+ }++ private func model(_ control: DeviceControl, devices: [AppleDevice], recorded: String = "", remembered: String = "",+ timeout: TimeInterval = 5, name: String = "Hades", bundle: String? = nil) -> SavesModel {+ SavesModel(template: template(control), name: name, recordedBundle: bundle, recordedDevice: recorded, installTarget: "",+ remembered: remembered, listDevices: { devices }, timeout: timeout)+ }++ private func wait(_ what: String, _ condition: () -> Bool) {+ let end = Date().addingTimeInterval(5)+ while !condition() && Date() < end { RunLoop.main.run(until: Date().addingTimeInterval(0.01)) }+ XCTAssertTrue(condition(), what)+ }++ // ---- the app is found on the device ----++ func testTheGameIsFoundByBundleIDPatternThenByName() {+ let apps = [InstalledApp(bundle: "com.apple.mobilesafari", name: "Safari"),+ InstalledApp(bundle: "org.nxnative.otherthing", name: "Other"),+ InstalledApp(bundle: "org.nxnative.\(titleID.lowercased()).ABCDE12345", name: "Hades"),+ InstalledApp(bundle: "org.nxnative.\(titleID.lowercased())", name: "Hades"),+ InstalledApp(bundle: "com.lcsign.x1", name: "Hades")]+ func match(_ list: [InstalledApp], name: String = "Hades", recorded: String? = nil) -> String? {+ SaveDiscovery.match(list, titleID: titleID, name: name, recordedBundle: recorded)?.bundle+ }+ XCTAssertEqual(match(apps), "org.nxnative.\(titleID.lowercased())", "the launcher's own ID first")+ XCTAssertEqual(match(apps, recorded: "com.lcsign.x1"), "com.lcsign.x1", "the one this launcher recorded beats the pattern")+ XCTAssertEqual(match(Array(apps.dropLast(2))), "org.nxnative.\(titleID.lowercased()).ABCDE12345", "a team suffix")+ XCTAssertEqual(match([apps[0], InstalledApp(bundle: "dev.resigner.\(titleID.uppercased())", name: "x")]), "dev.resigner.\(titleID.uppercased())", "the title ID inside any ID, any case")+ XCTAssertEqual(match([apps[0], apps[4]]), "com.lcsign.x1", "a re-signed app under another ID, by its name")+ XCTAssertEqual(match([apps[0], InstalledApp(bundle: "a.b", name: " hades ")]), "a.b", "the name, trimmed and case-blind")+ XCTAssertNil(match([apps[0], apps[1]]))+ XCTAssertNil(match([apps[0], apps[1], apps[4]], name: ""), "no name to match and no title ID in any ID")+ XCTAssertEqual(SaveDiscovery.match([InstalledApp(bundle: "b.two", name: "Hades"), InstalledApp(bundle: "a.one", name: "Hades")],+ titleID: titleID, name: "Hades", recordedBundle: nil)?.bundle, "a.one", "equal matches: the same answer every time")+ }++ func testTheAppsListingIsParsed() throws {+ let json = #"{"result": {"apps": [{"bundleIdentifier": "a.b", "name": "A"}, {"name": "no id"}, {"bundleIdentifier": "c.d"}]}}"#+ XCTAssertEqual(SaveDiscovery.parseApps(Data(json.utf8)), [InstalledApp(bundle: "a.b", name: "A"), InstalledApp(bundle: "c.d", name: "")])+ XCTAssertNil(SaveDiscovery.parseApps(Data("[]".utf8)))+ let command = SaveDiscovery.listCommand(device: "PHONE", json: "/tmp/x.json")+ XCTAssertTrue(command.contains("--include-default-apps"), "a game signed by another tool is not a developer app")+ }++ /// A game installed another way (the exported IPA, re-signed): no install record, no cached signed app, another bundle ID.+ func testAGameInstalledAnotherWayIsFoundAndItsSaveCopied() throws {+ let phone = fake("phone")+ phone.apps = [("com.apple.mobilesafari", "Safari"), ("com.lcsign.hades42", "Hades")]+ try write("legacy", phone.container.appendingPathComponent("Documents/save/SYSTEM.DAT"), date: newer)+ let m = model(fleet(["PHONE": phone]), devices: [iPhone])+ m.begin()+ wait("ready") { m.deviceSave != nil }+ XCTAssertEqual(m.deviceSave, SaveTransfer.Contents(folders: ["save"], newest: newer))+ let found = try XCTUnwrap(m.found)+ XCTAssertEqual(found.bundle, "com.lcsign.hades42")+ _ = try found.deviceToMac()+ XCTAssertEqual(read(found.macSave.appendingPathComponent("SYSTEM.DAT")), "legacy")+ try write("edited", found.macSave.appendingPathComponent("SYSTEM.DAT"), date: newer)+ _ = try found.macToDevice()+ XCTAssertEqual(read(phone.container.appendingPathComponent("Documents/save/SYSTEM.DAT")), "edited", "back where the app keeps it")+ XCTAssertFalse(fm.fileExists(atPath: phone.container.appendingPathComponent("Documents/games").path))+ for call in phone.calls where call.prefix(3) != ["device", "info", "apps"] {+ XCTAssertEqual(phone.value("--domain-identifier", call), "com.lcsign.hades42")+ }+ }++ func testAGameThatIsNotOnTheDeviceIsSaidSo() {+ let phone = fake("phone")+ phone.apps = [("com.apple.mobilesafari", "Safari")]+ let m = model(fleet(["PHONE": phone]), devices: [iPhone])+ m.begin()+ wait("answered") { !m.isReading }+ XCTAssertEqual(m.deviceState, .notInstalled)+ XCTAssertNil(m.found)+ }++ // ---- both save layouts ----++ private func transfer(_ device: Fake, bundle: String = "com.example.game") -> SaveTransfer {+ var t = template(device.control)+ t = SaveTransfer(titleID: titleID, macSave: t.macSave, device: "PHONE", bundle: bundle, devicectl: device.control)+ t.scratch = temporary+ t.now = { Date(timeIntervalSince1970: 1_800_000_000) }+ return t+ }++ func testDocumentsSaveAndThePerGameSaveAreBothRead() throws {+ let plain = fake("plain"), perGame = fake("pergame"), both = fake("both"), none = fake("none")+ try write("a", plain.container.appendingPathComponent("Documents/save/data.bin"), date: older)+ try write("b", perGame.container.appendingPathComponent("Documents/games/\(titleID)/save/data.bin"), date: newer)+ try write("img", perGame.container.appendingPathComponent("Documents/games/\(titleID)/romfs.img"), date: older)+ try write("a", both.container.appendingPathComponent("Documents/save/data.bin"), date: older)+ try write("b", both.container.appendingPathComponent("Documents/games/\(titleID)/save/data.bin"), date: newer)+ try write("img", both.container.appendingPathComponent("Documents/games/\(titleID)/romfs.img"), date: older)+ try write("img", none.container.appendingPathComponent("Documents/games/\(titleID)/romfs.img"), date: older)+ try fm.createDirectory(at: plain.container.appendingPathComponent("Documents/games"), withIntermediateDirectories: true)+ let t = transfer(plain)+ XCTAssertEqual(try t.resolveDevice().base, "Documents")+ XCTAssertEqual(try t.resolveDevice().contents, SaveTransfer.Contents(folders: ["save"], newest: older))+ XCTAssertEqual(try transfer(perGame).resolveDevice().base, "Documents/games/\(titleID)")+ XCTAssertEqual(try transfer(perGame).resolveDevice().contents.newest, newer)+ XCTAssertEqual(try transfer(both).resolveDevice().base, "Documents/games/\(titleID)", "both: the one the game's files are in")+ XCTAssertEqual(try transfer(none).resolveDevice().base, "Documents/games/\(titleID)", "no save yet: where the game's files are")+ XCTAssertEqual(try transfer(none).readDevice(), SaveTransfer.Contents())+ }++ func testACopyToTheDeviceGoesToTheLayoutInUse() throws {+ let plain = fake("plain")+ try write("old", plain.container.appendingPathComponent("Documents/save/data.bin"), date: older)+ let t = transfer(plain)+ try write("mac", t.macSave.appendingPathComponent("data.bin"), date: newer)+ let backup = try XCTUnwrap(try t.macToDevice())+ XCTAssertEqual(read(backup.appendingPathComponent("save/data.bin")), "old", "the confirmation's backup is made in both layouts")+ XCTAssertEqual(read(plain.container.appendingPathComponent("Documents/save/data.bin")), "mac")+ let copyTo = try XCTUnwrap(plain.calls.first { $0.prefix(3) == ["device", "copy", "to"] })+ XCTAssertEqual(plain.value("--destination", copyTo), "Documents/save")+ // A device with no save and no game files in a per-game folder: the save goes into Documents too+ let fresh = fake("fresh")+ try fm.createDirectory(at: fresh.container.appendingPathComponent("Documents"), withIntermediateDirectories: true)+ XCTAssertNil(try transfer(fresh).macToDevice())+ XCTAssertEqual(read(fresh.container.appendingPathComponent("Documents/save/data.bin")), "mac")+ }++ // ---- two devices ----++ func testTheSelectorStartsOnTheRecordedDeviceAndAsksTheOneChosen() throws {+ let phone = fake("phone"), pad = fake("pad")+ phone.apps = [("org.nxnative.\(titleID.lowercased())", "Hades")]+ pad.apps = [("com.lcsign.hades", "Hades")]+ try write("p", phone.container.appendingPathComponent("Documents/games/\(titleID)/save/data.bin"), date: older)+ try write("d", pad.container.appendingPathComponent("Documents/save/data.bin"), date: newer)+ let control = fleet(["PHONE": phone, "PAD": pad])+ var remembered: [String] = []+ let m = SavesModel(template: template(control), name: "Hades", recordedBundle: nil, recordedDevice: "PAD", installTarget: "PHONE",+ rememberChoice: { remembered.append($0) }, listDevices: { [self.iPhone, self.iPad] }, timeout: 5)+ XCTAssertFalse(m.showsSelector, "nothing listed yet")+ m.begin()+ wait("ready") { m.deviceSave != nil }+ XCTAssertTrue(m.showsSelector)+ XCTAssertEqual(m.selected, "PAD", "the device the game was installed on")+ XCTAssertEqual(m.selectedDevice?.name, "Zijad's iPad")+ XCTAssertEqual(m.found?.device, "PAD")+ XCTAssertEqual(m.deviceSave?.newest, newer)+ XCTAssertTrue(phone.calls.isEmpty, "the other device is not asked")+ m.select("PHONE")+ XCTAssertEqual(m.deviceState, .reading)+ XCTAssertEqual(m.selected, "PHONE")+ wait("the iPhone answered") { m.found?.device == "PHONE" && m.deviceSave != nil }+ XCTAssertEqual(m.deviceSave?.newest, older)+ XCTAssertEqual(m.found?.bundle, "org.nxnative.\(titleID.lowercased())")+ XCTAssertEqual(remembered, ["PHONE"])+ m.refresh()+ wait("refreshed") { m.deviceSave != nil }+ XCTAssertEqual(m.selected, "PHONE", "a refresh keeps the choice")+ }++ func testTheDefaultDeviceFollowsWhatIsConnected() {+ let away = AppleDevice(id: "AWAY", name: "Away", model: "iPhone", os: "27.0", reachable: false)+ func pick(_ list: [AppleDevice], remembered: String = "", recorded: String = "", target: String = "") -> String? {+ SavesModel.defaultDevice(in: list, remembered: remembered, recorded: recorded, installTarget: target)+ }+ XCTAssertEqual(pick([iPhone, iPad], remembered: "PAD", recorded: "PHONE"), "PAD", "the choice made here first")+ XCTAssertEqual(pick([away, iPad], recorded: "AWAY"), "PAD", "a device that is not connected is passed over")+ XCTAssertEqual(pick([away], recorded: "AWAY"), "AWAY", "when nothing is connected, its name is shown with the reason")+ XCTAssertEqual(pick([iPhone, iPad], target: "PAD"), "PAD")+ XCTAssertEqual(pick([iPad, iPhone], recorded: "GONE"), "PAD")+ XCTAssertNil(pick([]))+ }++ func testADeviceThatIsNotConnectedIsNotAsked() {+ let away = AppleDevice(id: "AWAY", name: "Away", model: "iPad", os: "27.0", reachable: false)+ let phone = fake("away")+ let m = model(fleet(["AWAY": phone]), devices: [away], recorded: "AWAY")+ m.begin()+ wait("answered") { !m.isReading }+ XCTAssertEqual(m.deviceState, .notConnected)+ XCTAssertTrue(phone.calls.isEmpty, "a connection that is not ready is what hangs")+ let none = model(fleet([:]), devices: [])+ none.begin()+ wait("answered") { !none.isReading }+ XCTAssertEqual(none.deviceState, .noDevices)+ }++ // ---- a device that does not answer ----++ func testAQueryThatNeverAnswersEndsAtTheTimeoutAndItsLateAnswerIsDropped() throws {+ let phone = fake("phone")+ phone.apps = [("com.lcsign.hades", "Hades")]+ try write("late", phone.container.appendingPathComponent("Documents/save/data.bin"), date: newer)+ let gate = DispatchSemaphore(value: 0)+ phone.hang = gate+ let m = model(fleet(["PHONE": phone]), devices: [iPhone], timeout: 0.3)+ m.begin()+ XCTAssertEqual(m.deviceState, .reading)+ XCTAssertFalse(m.canRefresh)+ wait("timed out") { m.deviceState == .timedOut }+ XCTAssertTrue(m.canRefresh, "Refresh is back")+ phone.hang = nil+ gate.signal() // the stuck command finally answers, after the sheet gave up on it+ RunLoop.main.run(until: Date().addingTimeInterval(0.4))+ XCTAssertEqual(m.deviceState, .timedOut, "a stale answer does not overwrite the message")+ XCTAssertNil(m.found)+ m.refresh() // and a new try works+ wait("ready") { m.deviceSave != nil }+ }++ func testACommandThatTimedOutIsATimeoutNotAnEmptySave() throws {+ let timedOut = DeviceControl { _ in (false, DeviceControl.timedOut) }+ let t = SaveTransfer(titleID: titleID, macSave: temporary.appendingPathComponent("save"), device: "PHONE", bundle: "x", devicectl: timedOut)+ XCTAssertThrowsError(try t.readDevice()) { XCTAssertEqual($0 as? SaveTransfer.Failure, .timeout) }+ // devicectl's own deadline says "timed out" in its words+ XCTAssertEqual(SaveTransfer.failure("ERROR: The operation timed out. (CoreDeviceError 9)"), .timeout)+ XCTAssertEqual(SaveTransfer.failure("Acquired tunnel\nERROR: not connected"), .device("ERROR: not connected"))+ // a save folder that times out in the middle is no "no save yet"+ let phone = fake("phone")+ try write("a", phone.container.appendingPathComponent("Documents/save/data.bin"), date: older)+ let inner = phone.control+ let flaky = DeviceControl { args in+ args.contains("Documents/save") ? (false, DeviceControl.timedOut) : inner.run(args)+ }+ let u = SaveTransfer(titleID: titleID, macSave: temporary.appendingPathComponent("save"), device: "PHONE", bundle: "x", devicectl: flaky)+ XCTAssertThrowsError(try u.readDevice()) { XCTAssertEqual($0 as? SaveTransfer.Failure, .timeout) }+ }++ func testARealCommandThatHangsIsStopped() throws {+ let command = temporary.appendingPathComponent("unresponsive-xcrun") // stands in for xcrun, never devicectl+ try "#!/bin/sh\nexec /bin/sleep 30\n".write(to: command, atomically: true, encoding: .utf8)+ try fm.setAttributes([.posixPermissions: 0o755], ofItemAtPath: command.path)+ let started = Date()+ let result = DeviceControl.xcrun(command.path, queryTimeout: 0.2).run(["device", "info", "files"])+ XCTAssertFalse(result.ok)+ XCTAssertEqual(result.output, DeviceControl.timedOut)+ XCTAssertLessThan(Date().timeIntervalSince(started), 10)+ }++ // ---- refresh while a query runs ----++ func testRefreshWhileAQueryRunsDoesNothingAndAnotherDeviceReplacesIt() throws {+ let phone = fake("phone"), pad = fake("pad")+ phone.apps = [("com.lcsign.hades", "Hades")]+ pad.apps = [("com.lcsign.hades", "Hades")]+ try write("p", phone.container.appendingPathComponent("Documents/save/data.bin"), date: older)+ try write("d", pad.container.appendingPathComponent("Documents/save/data.bin"), date: newer)+ let gate = DispatchSemaphore(value: 0)+ phone.hang = gate+ let m = model(fleet(["PHONE": phone, "PAD": pad]), devices: [iPhone, iPad], remembered: "PHONE")+ m.begin()+ wait("the iPhone is asked") { !phone.calls.isEmpty && m.showsSelector }+ m.refresh(); m.refresh(); m.begin()+ XCTAssertEqual(m.deviceState, .reading)+ m.select("PAD") // the iPad is asked in its place+ wait("the iPad answered") { m.deviceSave != nil }+ XCTAssertEqual(m.found?.device, "PAD")+ XCTAssertEqual(m.deviceSave?.newest, newer)+ phone.hang = nil+ gate.signal() // the iPhone's answer comes after, and is dropped+ RunLoop.main.run(until: Date().addingTimeInterval(0.4))+ XCTAssertEqual(m.found?.device, "PAD")+ XCTAssertEqual(m.deviceSave?.newest, newer)+ XCTAssertEqual(phone.calls.filter { $0.prefix(3) == ["device", "info", "apps"] }.count, 1, "the clicks while it ran asked nothing")+ }+}diff --git a/frontend/Tests/NSPortBuilderTests/SaveTransferTests.swift b/frontend/Tests/NSPortBuilderTests/SaveTransferTests.swiftindex 2f97cb61..619f3472 100644--- a/frontend/Tests/NSPortBuilderTests/SaveTransferTests.swift+++ b/frontend/Tests/NSPortBuilderTests/SaveTransferTests.swift@@ -20,17 +20,28 @@ final class SaveTransferTests: XCTestCase {final class FakeDevice {let container: URLvar reachable = true, nested = false, failCopyFrom = false- var calls: [[String]] = []+ var apps: [(bundle: String, name: String)] = [] // what `device info apps` lists+ var hang: DispatchSemaphore? // a command waits here first: a device that never answers+ var calls: [[String]] { lock.lock(); defer { lock.unlock() }; return recorded }+ private var recorded: [[String]] = []+ private let lock = NSLock()+ func clearCalls() { lock.lock(); recorded = []; lock.unlock() }init(_ container: URL) { self.container = container }func value(_ flag: String, _ args: [String]) -> String? { args.firstIndex(of: flag).map { args[$0 + 1] } }var control: DeviceControl {DeviceControl { [self] args in- calls.append(args)+ lock.lock(); recorded.append(args); lock.unlock()+ if let hang { hang.wait() }guard reachable else { return (false, "ERROR: The device is not connected. (com.apple.dt.CoreDeviceError error 4)") }let fm = FileManager.defaultswitch Array(args.prefix(3)) {+ case ["device", "info", "apps"]:+ let list = apps.map { ["bundleIdentifier": $0.bundle, "name": $0.name, "version": "1.0"] }+ let json = try! JSONSerialization.data(withJSONObject: ["info": ["outcome": "success"], "result": ["apps": list]])+ try! json.write(to: URL(fileURLWithPath: value("--json-output", args)!))+ return (true, "")case ["device", "info", "files"]:let dir = container.appendingPathComponent(value("--subdirectory", args)!)guard fm.fileExists(atPath: dir.path) else { return (false, "ERROR: The file couldn't be opened because there is no such file.") }@@ -209,7 +220,7 @@ final class SaveTransferTests: XCTestCase {XCTAssertFalse(device.calls.contains { $0.prefix(3) == ["device", "copy", "to"] })// No Mac save: nothing is asked of the device at alltry fm.removeItem(at: t.mac.appendingPathComponent("save"))- device.calls = []+ device.clearCalls()XCTAssertThrowsError(try t.macToDevice()) { XCTAssertEqual($0 as? SaveTransfer.Failure, .noMacSave) }XCTAssertTrue(device.calls.isEmpty)// A device that is not reachable: the copy stops before anything is replaced