Skip to content

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

Library: a game's save goes between the Mac and the device it is installed on (#66)

v0lumehi8ebddb449c19
diff --git a/frontend/README.md b/frontend/README.md
index 8fc1ad06..86f0832f 100644
--- a/frontend/README.md
+++ b/frontend/README.md
@@ -56,6 +56,22 @@ unsigned IPA as before. The devices and teams are read with `devicectl list
devices` and `security find-identity`; the team is the certificate's
organizational unit, not the code in its name.
+## Saves
+
+**Manage > Saves…** (a controller's Y) shows a game's save on this Mac
+(`~/Library/Application Support/nxnative/<title ID>/save`, from `dm/mac/launcher.c`) and
+on the device the launcher installed it on (`Documents/games/<title ID>/save` in the app's
+data container, from `dm/ios/Sources/main.m`), each with the date of its newest file, and
+marks the newer one. **Mac → iPhone** and **iPhone → Mac** copy one over the other, after
+asking. The save being replaced is backed up first, beside the Mac save in
+`save-backups/<date> mac` or `<date> device` (the device's is copied to the Mac before
+anything is replaced). A game that also keeps device save data has a `save_device`
+folder beside `save` (`dm/host/hle_fs.c`), which goes along. The copy is refused while
+the game runs on the Mac; close it on the device too, or it writes its own save over the
+copy later. The device side uses the install's route: `devicectl device info files` for
+the date and `devicectl device copy from` / `copy to` with the app's data container. Only
+a game installed from here has a known bundle ID, so a sideloaded IPA has no device side.
+
## Your games folder
Set **Your games folder** in Settings once. The launcher remembers it, checks it
diff --git a/frontend/Sources/NSPortBuilder/LauncherView.swift b/frontend/Sources/NSPortBuilder/LauncherView.swift
index 3fcd6c63..6f9b22a7 100644
--- a/frontend/Sources/NSPortBuilder/LauncherView.swift
+++ b/frontend/Sources/NSPortBuilder/LauncherView.swift
@@ -35,6 +35,7 @@ struct ContentView: View {
@State private var removing: LibraryGame?
@State private var optionsFor: UUID?
@State private var controlsOpen = false
+ @State private var savesFor: UUID? // the game whose Saves sheet is open (SaveTransfer.swift)
@StateObject private var controls = ControlLayout()
@StateObject private var gamepad = LauncherGamepad()
@StateObject private var padFocus = PadFocus()
@@ -128,6 +129,10 @@ struct ContentView: View {
}
.sheet(isPresented: $controlsOpen) { ControlsView(m: m, layout: controls).environmentObject(padFocus) }
.sheet(isPresented: $m.showUpdateSheet) { UpdateSheet(m: m) }
+ .sheet(isPresented: Binding(get: { savesFor != nil }, set: { if !$0 { savesFor = nil } })) {
+ if let id = savesFor { SavesView(m: m, library: library, gameID: id).environmentObject(padFocus) }
+ }
+ .onChange(of: savesFor) { id in padFocus.scope = id != nil ? "saves" : "main" }
.onChange(of: optionsFor) { id in padFocus.scope = id != nil ? "launch" : (controlsOpen ? "controls" : "main") }
.onChange(of: controlsOpen) { open in padFocus.scope = open ? "controls" : (optionsFor != nil ? "launch" : "main") }
.onChange(of: page) { _ in padFocus.focused = nil }
@@ -313,6 +318,7 @@ struct ContentView: View {
Menu {
Button(m.t("library.buildAgain")) { configureBuild(game) }.disabled(m.running || game.inputs["base", default: []].isEmpty)
if game.isReady { Button(m.t("launch.title")) { optionsFor = game.id } }
+ Button(m.t("saves.menu")) { savesFor = game.id }
Button(m.t("library.changeArtwork")) { chooseArtwork(game) }
if !game.artworkPath.isEmpty {
Button(m.t("library.resetArtwork")) { library.setArtwork("", for: game.id) }
@@ -482,6 +488,7 @@ struct ContentView: View {
// The buttons a controller has here, named as the game names them (A on the right)
HStack(spacing: 18) {
padHint("A", m.t("pad.play")); padHint("X", m.t("pad.options")); padHint("B", m.t("pad.back"))
+ padHint("Y", m.t("pad.saves"))
Image(systemName: "gamecontroller").foregroundStyle(.secondary)
}
}
@@ -530,7 +537,8 @@ struct ContentView: View {
/// then the D-pad moves it (PadFocus), A activates, B closes a sheet or goes back to the library, X opens the selected
/// game's launch options, L and R switch the pages.
private func padAction(_ action: LauncherGamepad.Action) {
- let sheetOpen = optionsFor != nil || controlsOpen
+ let sheetOpen = optionsFor != nil || controlsOpen || savesFor != nil
+ if action == .b, savesFor != nil { savesFor = nil; return }
if action == .b {
if optionsFor != nil { optionsFor = nil } else if controlsOpen { controlsOpen = false }
else if searching { searching = false; search = "" } else if page != .library { page = .library }
@@ -553,7 +561,9 @@ struct ContentView: View {
guard !sheetOpen, let at = LauncherPage.allCases.firstIndex(of: page) else { return }
let pages = LauncherPage.allCases
page = pages[(at + (action == .l ? pages.count - 1 : 1)) % pages.count]
- case .b, .y:
+ case .y: // the selected game's saves: the Manage menu is AppKit's, which a controller cannot open
+ if !sheetOpen, let game = library.selected { savesFor = game.id }
+ case .b:
return
}
}
diff --git a/frontend/Sources/NSPortBuilder/Localization.swift b/frontend/Sources/NSPortBuilder/Localization.swift
index 03ebf7f7..58ffde01 100644
--- a/frontend/Sources/NSPortBuilder/Localization.swift
+++ b/frontend/Sources/NSPortBuilder/Localization.swift
@@ -68,6 +68,33 @@ enum L10n {
"dev.team": ("\u{7b7e}\u{540d}\u{56e2}\u{961f}", "Signing team"),
"dev.noTeam": ("\u{6ca1}\u{6709}\u{5f00}\u{53d1}\u{8bc1}\u{4e66}\u{3002}\u{5728} Xcode \u{4e2d}\u{767b}\u{5f55} Apple ID\u{ff08}\u{8bbe}\u{7f6e} \u{2192} \u{8d26}\u{6237}\u{ff09}\u{5373}\u{53ef}\u{83b7}\u{5f97}\u{3002}", "No development certificate. Sign in to Xcode with your Apple ID (Settings \u{2192} Accounts) to get one."),
"dev.note": ("Xcode 会为这台设备签名并直接安装,游戏数据(romfs.img)复制到 App 的“文稿”中,与侧载相同;第一次复制大型游戏需要几分钟。第一次需要在设备上开启开发者模式,并信任开发者(设置 → 通用 → VPN 与设备管理)。", "Xcode signs the game for this device and installs it there, then copies the game data (romfs.img) into the app’s Documents, as for sideloading; the first copy of a large game takes a few minutes. The first time, turn on Developer Mode on the device and trust the developer (Settings → General → VPN & Device Management)."),
+ // ---- Saves: a game's save copied between this Mac and the device it is installed on (SaveTransfer.swift) ----
+ "saves.menu": ("存档…", "Saves…"),
+ "saves.title": ("存档", "Saves"),
+ "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.unreachable": ("无法读取:%@", "Cannot be read: %@"),
+ "saves.newer": ("较新", "Newer"),
+ "saves.toDevice": ("Mac → %@", "Mac → %@"),
+ "saves.toMac": ("%@ → Mac", "%@ → Mac"),
+ "saves.backups": ("显示备份", "Show backups"),
+ "saves.note": ("复制前请先在 Mac 和 %@ 上关闭游戏。被替换的存档会先备份到 Mac 上。", "Close the game on the Mac and on %@ first. The save being replaced is backed up on the Mac first."),
+ "saves.askToDevice": ("用这台 Mac 的存档替换 %@ 上的存档?", "Replace the save on %@ with the one from this Mac?"),
+ "saves.askToMac": ("用 %@ 的存档替换这台 Mac 上的存档?", "Replace the save on this Mac with the one from %@?"),
+ "saves.askNote": ("请先在 %1$@ 上关闭游戏:正在运行的游戏之后会用自己的存档覆盖复制过去的存档。被替换的存档会先保存到 %2$@。", "Close the game on %1$@ first: a running game writes its own save over the copy later. The save being replaced is kept in %2$@ first."),
+ "saves.cancel": ("取消", "Cancel"),
+ "saves.replace": ("替换", "Replace"),
+ "saves.copying": ("正在复制存档…", "Copying the save…"),
+ "saves.copied": ("已复制。", "Copied."),
+ "saves.copiedBackup": ("已复制。被替换的存档在 %@。", "Copied. The save it replaced is in %@."),
+ "saves.running": ("%@ 正在这台 Mac 上运行。请先退出游戏。", "%@ is running on this Mac. Quit it first."),
+ "saves.noMacSave": ("这台 Mac 上还没有这个游戏的存档。", "This Mac has no save for this game yet."),
+ "saves.noDeviceSave": ("%@ 上还没有这个游戏的存档。", "%@ has no save for this game yet."),
+ "saves.failed": ("复制失败:%@", "Copying failed: %@"),
+ "pad.saves": ("存档", "Saves"),
"dev.signStage": ("\u{4e3a} %@ \u{7b7e}\u{540d}", "Sign for %@"),
"dev.installStage": ("\u{5b89}\u{88c5}\u{5230} %@", "Install on %@"),
"dev.copyStage": ("复制游戏文件到 %@", "Copy the game files to %@"),
diff --git a/frontend/Sources/NSPortBuilder/SaveTransfer.swift b/frontend/Sources/NSPortBuilder/SaveTransfer.swift
new file mode 100644
index 00000000..3dd0c9e3
--- /dev/null
+++ b/frontend/Sources/NSPortBuilder/SaveTransfer.swift
@@ -0,0 +1,494 @@
+import AppKit
+import SwiftUI
+
+/// `xcrun devicectl` for the save transfer, as one function: the tests hand in a stand-in, so no test ever reaches a device.
+/// It takes devicectl's arguments and returns whether it exited 0 and what it printed.
+struct DeviceControl {
+ let run: ([String]) -> (ok: Bool, output: String)
+
+ static func xcrun(_ path: String) -> DeviceControl {
+ DeviceControl { args in
+ let p = Process(), out = Pipe()
+ p.executableURL = URL(fileURLWithPath: path)
+ p.arguments = ["devicectl"] + args
+ p.standardOutput = out; p.standardError = out; p.standardInput = FileHandle.nullDevice
+ do { try p.run() } catch { return (false, error.localizedDescription) }
+ let data = out.fileHandleForReading.readDataToEndOfFile()
+ p.waitUntilExit()
+ return (p.terminationStatus == 0, String(decoding: data, as: UTF8.self))
+ }
+ }
+}
+
+/// 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
+/// first, so a copy in the wrong direction loses nothing.
+///
+/// Where the saves are: the Mac app keeps them in ~/Library/Application Support/nxnative/<title ID>/save (dm/mac/launcher.c,
+/// DM_SAVE); 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.
+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,
+ /// cloned again from the committed folder at every mount, so they are not part of the save.
+ static let folders = ["save", "save_device"]
+
+ let titleID: String
+ let mac: URL // the game's Application Support folder on this Mac
+ let device: String // the device's UDID
+ let bundle: String // the installed app's bundle ID: its data container
+ let devicectl: DeviceControl
+ var scratch = FileManager.default.temporaryDirectory
+ var now: () -> Date = Date.init
+
+ enum Failure: Error, Equatable {
+ case noMacSave, noDeviceSave
+ case device(String) // devicectl's last line
+ }
+
+ /// What the device holds: the save folders with files in them, and the newest file's date.
+ struct Contents: Equatable {
+ var folders: [String] = []
+ var newest: Date?
+ }
+
+ static func macFolder(titleID: String,
+ support: URL = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0]) -> URL {
+ support.appendingPathComponent("nxnative").appendingPathComponent(titleID)
+ }
+
+ 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.
+ var backups: URL { mac.appendingPathComponent("save-backups") }
+
+ // ---- reading ----
+
+ func readMac() -> Contents {
+ Self.folders.reduce(into: Contents()) { c, f in
+ guard let date = Self.newest(in: mac.appendingPathComponent(f)) else { return }
+ c.folders.append(f)
+ c.newest = max(c.newest ?? date, date)
+ }
+ }
+
+ /// 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)
+ 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 }
+ c.folders.append(f)
+ if let date = entries.newest { c.newest = max(c.newest ?? date, date) }
+ }
+ return c
+ }
+
+ private func list(_ subdirectory: String, recurse: Bool) throws -> Data {
+ 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)) }
+ return data
+ }
+
+ // ---- 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()
+ guard !there.folders.isEmpty else { throw Failure.noDeviceSave }
+ let fm = FileManager.default
+ let incoming = mac.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))
+ }
+ var backup: URL?
+ for f in there.folders where fm.fileExists(atPath: mac.appendingPathComponent(f).path) {
+ let into = try backup ?? makeBackup("mac")
+ backup = into
+ try fm.moveItem(at: mac.appendingPathComponent(f), to: into.appendingPathComponent(f))
+ }
+ for f in there.folders { try fm.moveItem(at: incoming.appendingPathComponent(f), to: mac.appendingPathComponent(f)) }
+ return backup
+ }
+
+ /// The Mac's save replaces the device's. The device save is copied to the Mac first; if that fails nothing is replaced.
+ /// Returns the backup, nil when the device had no save.
+ func macToDevice() throws -> URL? {
+ let here = readMac()
+ guard !here.folders.isEmpty else { throw Failure.noMacSave }
+ let there = try readDevice()
+ 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 here.folders {
+ let r = devicectl.run(Self.copyToCommand(device: device, bundle: bundle, source: mac.appendingPathComponent(f).path, destination: deviceFolder + "/" + f))
+ guard r.ok else { throw Failure.device(Self.lastLine(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)) }
+ Self.hoist(local)
+ guard Self.newest(in: local) != nil else { throw Failure.device(source) } // the device listed files that did not come
+ }
+
+ private func makeBackup(_ side: String) throws -> URL {
+ let f = DateFormatter()
+ f.locale = Locale(identifier: "en_US_POSIX")
+ f.dateFormat = "yyyy-MM-dd HH.mm.ss"
+ let stamp = f.string(from: now())
+ var url = backups.appendingPathComponent("\(stamp) \(side)"), n = 2
+ while FileManager.default.fileExists(atPath: url.path) { url = backups.appendingPathComponent("\(stamp) \(side) \(n)"); n += 1 }
+ try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)
+ return url
+ }
+
+ // ---- devicectl's command lines (the same domain as the install's archiveCopy) ----
+
+ static func listCommand(device: String, bundle: String, subdirectory: String, recurse: Bool, json: String) -> [String] {
+ ["device", "info", "files", "--device", device, "--domain-type", "appDataContainer", "--domain-identifier", bundle,
+ "--subdirectory", subdirectory, recurse ? "--recurse" : "--no-recurse", "--json-output", json]
+ }
+
+ static func copyFromCommand(device: String, bundle: String, source: String, destination: String) -> [String] {
+ ["device", "copy", "from", "--device", device, "--source", source, "--destination", destination,
+ "--domain-type", "appDataContainer", "--domain-identifier", bundle]
+ }
+
+ /// The destination is the folder itself, as in the install's archiveCopy; the files the Mac does not have go, so the
+ /// device holds the Mac's save and nothing older beside it (the backup has the old one).
+ static func copyToCommand(device: String, bundle: String, source: String, destination: String) -> [String] {
+ ["device", "copy", "to", "--device", device, "--source", source, "--destination", destination,
+ "--domain-type", "appDataContainer", "--domain-identifier", bundle, "--remove-existing-content", "true"]
+ }
+
+ // ---- pure helpers ----
+
+ /// The newest modification date of a file in the folder, nil when it has no files (a save the game has not written).
+ static func newest(in folder: URL) -> Date? {
+ guard let walk = FileManager.default.enumerator(at: folder, includingPropertiesForKeys: [.contentModificationDateKey, .isRegularFileKey]) else { return nil }
+ var newest: Date?
+ for case let url as URL in walk {
+ guard let v = try? url.resourceValues(forKeys: [.contentModificationDateKey, .isRegularFileKey]), v.isRegularFile == true,
+ let date = v.contentModificationDate else { continue }
+ newest = max(newest ?? date, date)
+ }
+ 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
+ /// cannot be read.
+ static func parseListing(_ data: Data) -> (files: Int, newest: Date?)? {
+ guard let root = try? JSONSerialization.jsonObject(with: data) else { return nil }
+ var files = 0, newest: Date?
+ 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 kind = ["fileType", "type", "kind"].compactMap { dict[$0] as? String }.joined().lowercased()
+ if !kind.contains("dir") {
+ files += 1
+ if let date = date(raw) { newest = max(newest ?? date, date) }
+ }
+ }
+ dict.values.forEach(walk)
+ }
+ walk(root)
+ return (files, newest)
+ }
+
+ /// An ISO 8601 date, with or without fractions of a second, or a number of seconds (since 1970, or since 2001 as
+ /// Foundation's reference date when it is small enough to be one).
+ static func date(_ raw: Any) -> Date? {
+ if let n = raw as? Double { return n > 1_000_000_000 ? Date(timeIntervalSince1970: n) : Date(timeIntervalSinceReferenceDate: n) }
+ guard let s = raw as? String else { return nil }
+ let f = ISO8601DateFormatter()
+ f.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
+ if let d = f.date(from: s) { return d }
+ f.formatOptions = [.withInternetDateTime]
+ return f.date(from: s)
+ }
+
+ /// A copy that put the folder inside the destination (local/save/save) instead of being it: its contents move up one
+ /// level, so either way the copy is the save folder itself.
+ static func hoist(_ local: URL) {
+ let fm = FileManager.default
+ var isDir: ObjCBool = false
+ guard let items = try? fm.contentsOfDirectory(atPath: local.path), items == [local.lastPathComponent],
+ fm.fileExists(atPath: local.appendingPathComponent(items[0]).path, isDirectory: &isDir), isDir.boolValue else { return }
+ let aside = local.deletingLastPathComponent().appendingPathComponent(".hoist-\(UUID().uuidString)")
+ guard (try? fm.moveItem(at: local.appendingPathComponent(items[0]), to: aside)) != nil else { return }
+ try? fm.removeItem(at: local)
+ try? fm.moveItem(at: aside, to: local)
+ }
+
+ static func lastLine(_ output: String) -> String {
+ let lines = output.split(separator: "\n").map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty }
+ return lines.last(where: { $0.lowercased().contains("error") }) ?? lines.last ?? "devicectl"
+ }
+
+ enum Side { case mac, device }
+
+ /// The newer of the two saves; nil when neither has one or they were written within the same few seconds.
+ static func newer(mac: Date?, device: Date?) -> Side? {
+ switch (mac, device) {
+ case (nil, nil): return nil
+ case (_, nil): return .mac
+ case (nil, _): return .device
+ case let (m?, d?): return abs(m.timeIntervalSince(d)) < 3 ? nil : (m > d ? .mac : .device)
+ }
+ }
+
+ /// A copy of the game is running on this Mac: one of the running apps is a build of it (DMTitleID in its Info.plist).
+ /// Its save may be half written, and it would write its own over the copy when it saves next.
+ static func running(titleID: String, apps: [URL]) -> Bool {
+ apps.contains { app in
+ (NSDictionary(contentsOf: app.appendingPathComponent("Contents/Info.plist"))?["DMTitleID"] as? String)?.uppercased() == titleID.uppercased()
+ }
+ }
+
+ static func runningOnMac(titleID: String) -> Bool {
+ running(titleID: titleID, apps: NSWorkspace.shared.runningApplications.compactMap(\.bundleURL))
+ }
+}
+
+/// The Saves sheet: the game's save on this Mac and on the device it was installed on, which is newer, and a copy either way.
+/// A copy asks first, in the sheet itself (a controller reaches it), and says where the save it replaced went.
+struct SavesView: View {
+ @ObservedObject var m: BuildModel
+ @ObservedObject var library: GameLibrary
+ let gameID: UUID
+ var devicectl: DeviceControl? = nil // tests and the visual QA hand in a stand-in
+ var support: URL? = nil // the Application Support folder; tests use a temporary one
+ @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 }
+ let mac = support.map { SaveTransfer.macFolder(titleID: game.titleID, support: $0) } ?? SaveTransfer.macFolder(titleID: game.titleID)
+ let bundle = NSDictionary(contentsOfFile: game.iosAppPath + "/Info.plist")?["CFBundleIdentifier"] as? String ?? ""
+ return SaveTransfer(titleID: game.titleID, mac: mac, device: game.installedDevice, bundle: bundle,
+ devicectl: devicectl ?? .xcrun(m.xcrunPath))
+ }
+
+ private var deviceSave: SaveTransfer.Contents? { if case .ready(let c) = deviceState { return c }; return nil }
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 0) {
+ VStack(alignment: .leading, spacing: 4) {
+ 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)
+ VStack(alignment: .leading, spacing: 18) {
+ card {
+ sideRow(.mac)
+ Divider().opacity(0.25).padding(.leading, 18)
+ sideRow(.device)
+ }
+ if let asking { confirmation(asking) } else { actions }
+ if busy {
+ HStack(spacing: 10) {
+ ProgressView().controlSize(.small)
+ Text(m.t("saves.copying")).font(.manrope(13)).foregroundStyle(.secondary)
+ }
+ } else if let result {
+ Label(result.text, systemImage: result.ok ? "checkmark.circle.fill" : "exclamationmark.triangle.fill")
+ .font(.manrope(13)).foregroundStyle(result.ok ? LauncherPalette.ready : LauncherPalette.building)
+ .fixedSize(horizontal: false, vertical: true)
+ }
+ Spacer(minLength: 0)
+ }
+ .padding(.horizontal, 30)
+ Divider().opacity(0.3)
+ HStack(spacing: 14) {
+ Text(String(format: m.t("saves.note"), deviceName)).font(.manrope(12)).foregroundStyle(.secondary)
+ .lineLimit(3).fixedSize(horizontal: false, vertical: true)
+ Spacer(minLength: 8)
+ Button { dismiss() } label: {
+ Text(m.t("launch.done")).font(.manrope(13.5, .bold)).foregroundStyle(.black)
+ .padding(.horizontal, 22).padding(.vertical, 9)
+ .background(LauncherPalette.cream, in: Capsule())
+ }
+ .buttonStyle(.plain).keyboardShortcut(asking == nil ? .defaultAction : nil).disabled(busy)
+ .padTarget("saves.done", scope: "saves", radius: 20) { if !busy { dismiss() } }
+ }
+ .padding(.horizontal, 30).padding(.vertical, 16)
+ }
+ .padScope("saves", focus)
+ .frame(width: 600, height: 520)
+ .background(LauncherPalette.background)
+ .font(.manrope(13))
+ .preferredColorScheme(.dark)
+ .tint(LauncherPalette.cream)
+ .onAppear(perform: refresh)
+ }
+
+ private func card<Content: View>(@ViewBuilder _ content: () -> Content) -> some View {
+ VStack(spacing: 0, content: content)
+ .background(LauncherPalette.surface.opacity(0.75), in: RoundedRectangle(cornerRadius: 14))
+ .overlay(RoundedRectangle(cornerRadius: 14).strokeBorder(Color.white.opacity(0.06)))
+ }
+
+ private func sideRow(_ side: SaveTransfer.Side) -> some View {
+ let newer = SaveTransfer.newer(mac: macSave.newest, device: deviceSave?.newest)
+ let detail: String
+ 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")
+ case .failed(let why): detail = String(format: m.t("saves.unreachable"), why)
+ 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))
+ .foregroundStyle(.secondary).frame(width: 26)
+ VStack(alignment: .leading, spacing: 3) {
+ Text(side == .mac ? m.t("saves.mac") : deviceName).font(.manrope(14, .medium))
+ Text(detail).font(.manrope(12)).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)
+ }
+ Spacer(minLength: 12)
+ if newer == side && (side == .mac || deviceSave != nil) {
+ Text(m.t("saves.newer").uppercased()).font(.manrope(10.5, .bold)).tracking(1.1).foregroundStyle(.black)
+ .padding(.horizontal, 10).padding(.vertical, 4)
+ .background(LauncherPalette.cream, in: Capsule())
+ }
+ }
+ .padding(.horizontal, 18).padding(.vertical, 13)
+ .frame(minHeight: 60)
+ }
+
+ /// The two copies, Refresh and the backups folder. A copy needs both sides readable and a save on the side it copies from.
+ private var actions: some View {
+ let toDevice = !busy && deviceSave != nil && !macSave.folders.isEmpty
+ let toMac = !busy && !(deviceSave?.folders.isEmpty ?? true)
+ return HStack(spacing: 10) {
+ Button(String(format: m.t("saves.toDevice"), deviceName)) { ask(.device) }.disabled(!toDevice)
+ .padTarget("saves.toDevice", scope: "saves") { if toDevice { ask(.device) } }
+ 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("saves.backups")) { NSWorkspace.shared.open(transfer.backups) }
+ .padTarget("saves.backups", scope: "saves") { NSWorkspace.shared.open(transfer.backups) }
+ }
+ }
+ .buttonStyle(LauncherSecondaryButtonStyle())
+ }
+
+ /// Asking before a copy replaces a save: which one, where its backup goes, and that the game must be closed on the device.
+ private func confirmation(_ replacing: SaveTransfer.Side) -> some 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) } ?? ""))
+ .font(.manrope(12.5)).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)
+ HStack(spacing: 10) {
+ Spacer()
+ Button(m.t("saves.cancel")) { asking = nil }.buttonStyle(LauncherSecondaryButtonStyle())
+ .padTarget("saves.cancel", scope: "saves") { asking = nil }
+ Button { copy(replacing) } label: {
+ Text(m.t("saves.replace")).font(.manrope(13, .bold)).foregroundStyle(.black)
+ .padding(.horizontal, 18).padding(.vertical, 9)
+ .background(LauncherPalette.cream, in: RoundedRectangle(cornerRadius: 9))
+ }
+ .buttonStyle(.plain).keyboardShortcut(.defaultAction)
+ .padTarget("saves.replace", scope: "saves") { copy(replacing) }
+ }
+ }
+ .padding(18)
+ .background(LauncherPalette.surface.opacity(0.75), in: RoundedRectangle(cornerRadius: 14))
+ .overlay(RoundedRectangle(cornerRadius: 14).strokeBorder(LauncherPalette.cream.opacity(0.35)))
+ }
+
+ private func dateText(_ date: Date) -> String {
+ let f = DateFormatter()
+ f.locale = m.lang == .zh ? Locale(identifier: "zh_Hans") : (Locale.current.identifier.hasPrefix("zh") ? Locale(identifier: "en_US") : .current)
+ f.dateStyle = .medium; f.timeStyle = .short
+ 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 = nil
+ guard let game, !SaveTransfer.runningOnMac(titleID: game.titleID) else {
+ result = (String(format: m.t("saves.running"), game?.name ?? ""), false)
+ return
+ }
+ asking = replacing
+ focus.focused = "saves.cancel" // the controller's focus moves to the question it has to answer
+ }
+
+ private func copy(_ replacing: SaveTransfer.Side) {
+ asking = nil
+ guard let transfer, let game else { return }
+ if SaveTransfer.runningOnMac(titleID: game.titleID) { // started while the question was open
+ result = (String(format: m.t("saves.running"), game.name), false)
+ return
+ }
+ busy = true
+ DispatchQueue.global(qos: .userInitiated).async {
+ let outcome: (String, Bool)
+ do {
+ let backup = try replacing == .device ? transfer.macToDevice() : transfer.deviceToMac()
+ outcome = (backup.map { String(format: m.t("saves.copiedBackup"), m.shortPath($0.path)) } ?? m.t("saves.copied"), true)
+ } catch { outcome = (String(format: m.t("saves.failed"), message(error)), false) }
+ DispatchQueue.main.async {
+ busy = false
+ result = outcome
+ refresh()
+ focus.focused = "saves.done"
+ }
+ }
+ }
+
+ private func message(_ error: Error) -> String {
+ switch error as? SaveTransfer.Failure {
+ case .noMacSave: return m.t("saves.noMacSave")
+ case .noDeviceSave: return String(format: m.t("saves.noDeviceSave"), deviceName)
+ case .device(let line): return line
+ case nil: return error.localizedDescription
+ }
+ }
+}
diff --git a/frontend/Tests/NSPortBuilderTests/LibraryTests.swift b/frontend/Tests/NSPortBuilderTests/LibraryTests.swift
index 20c9bf34..92c50c8a 100644
--- a/frontend/Tests/NSPortBuilderTests/LibraryTests.swift
+++ b/frontend/Tests/NSPortBuilderTests/LibraryTests.swift
@@ -788,6 +788,45 @@ final class LibraryTests: XCTestCase {
model.stages = [Stage(id: 1, name: "Extract game files", state: .running, percent: 40)]
try capture("building", activeID: library.games[1].id)
model.running = false
+
+ // ---- Saves (#66): the sheet with a stand-in devicectl and a temporary Mac folder, then its question, reached by the controller ----
+ do {
+ let game = library.games[0]
+ let installed = temporary.appendingPathComponent("DmIOS.app")
+ try FileManager.default.createDirectory(at: installed, withIntermediateDirectories: true)
+ try PropertyListSerialization.data(fromPropertyList: ["CFBundleIdentifier": "com.example.hades"], format: .xml, options: 0)
+ .write(to: installed.appendingPathComponent("Info.plist"))
+ library.recordCompletedIOS(ipa: "", archive: "", app: installed.path, device: "00008150-AAAA", for: game.id)
+ let support = temporary.appendingPathComponent("Application Support")
+ let save = SaveTransfer.macFolder(titleID: game.titleID, support: support).appendingPathComponent("save/data.bin")
+ try FileManager.default.createDirectory(at: save.deletingLastPathComponent(), withIntermediateDirectories: true)
+ try Data("mac".utf8).write(to: save)
+ 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 ago
+ guard let i = args.firstIndex(of: "--json-output") else { return (false, "ERROR: not in the visual QA") }
+ 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 window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 600, height: 520), styleMask: [.titled], backing: .buffered, defer: false)
+ window.contentView = host
+ window.orderFront(nil)
+ RunLoop.main.run(until: Date().addingTimeInterval(0.6))
+ func shot(_ name: String) throws {
+ let rep = try XCTUnwrap(host.bitmapImageRepForCachingDisplay(in: host.bounds))
+ host.cacheDisplay(in: host.bounds, to: rep)
+ try XCTUnwrap(rep.representation(using: .png, properties: [:])).write(to: output.appendingPathComponent(name + ".png"))
+ }
+ try shot("saves")
+ focus.scope = "saves"
+ focus.show(default: "saves.toDevice")
+ focus.activate()
+ RunLoop.main.run(until: Date().addingTimeInterval(0.4))
+ try shot("saves-confirm")
+ window.orderOut(nil)
+ }
}
/// Issue #52: the failure note names the last real line, not just the exit code.
diff --git a/frontend/Tests/NSPortBuilderTests/SaveTransferTests.swift b/frontend/Tests/NSPortBuilderTests/SaveTransferTests.swift
new file mode 100644
index 00000000..3a68543c
--- /dev/null
+++ b/frontend/Tests/NSPortBuilderTests/SaveTransferTests.swift
@@ -0,0 +1,260 @@
+import XCTest
+@testable import NSPortBuilder
+
+/// Issue #66: the save copied between the Mac and a device. devicectl is a stand-in that serves a folder as the app's data
+/// container, so no test reaches a device, and the Mac side is a temporary folder, never the real Application Support.
+final class SaveTransferTests: XCTestCase {
+ private var temporary: URL!
+ private let titleID = "0100535012974000"
+ private let fm = FileManager.default
+
+ override func setUpWithError() throws {
+ temporary = fm.temporaryDirectory.appendingPathComponent("nxnative-saves-" + UUID().uuidString)
+ try fm.createDirectory(at: temporary, withIntermediateDirectories: true)
+ }
+
+ override func tearDownWithError() throws { try fm.removeItem(at: temporary) }
+
+ /// A device's app data container as a folder. `nested` copies a folder into the destination instead of as it, the other
+ /// reading of devicectl's --destination; `failCopyFrom` makes every copy from the device fail.
+ final class FakeDevice {
+ let container: URL
+ var reachable = true, nested = false, failCopyFrom = false
+ var calls: [[String]] = []
+ 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)
+ guard reachable else { return (false, "ERROR: The device is not connected. (com.apple.dt.CoreDeviceError error 4)") }
+ let fm = FileManager.default
+ switch Array(args.prefix(3)) {
+ 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.") }
+ let iso = ISO8601DateFormatter()
+ iso.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
+ var files: [[String: Any]] = []
+ for case let url as URL in fm.enumerator(at: dir, includingPropertiesForKeys: nil)! {
+ let v = try! url.resourceValues(forKeys: [.isDirectoryKey, .contentModificationDateKey])
+ files.append(["name": url.lastPathComponent, "fileType": v.isDirectory! ? "directory" : "file",
+ "modificationDate": iso.string(from: v.contentModificationDate!)])
+ }
+ let json = try! JSONSerialization.data(withJSONObject: ["info": ["outcome": "success"], "result": ["files": files]])
+ try! json.write(to: URL(fileURLWithPath: value("--json-output", args)!))
+ return (true, "")
+ case ["device", "copy", "from"]:
+ let source = container.appendingPathComponent(value("--source", args)!)
+ var destination = URL(fileURLWithPath: value("--destination", args)!)
+ guard !failCopyFrom, fm.fileExists(atPath: source.path) else { return (false, "ERROR: copy failed") }
+ if nested {
+ try! fm.createDirectory(at: destination, withIntermediateDirectories: true)
+ destination.appendPathComponent(source.lastPathComponent)
+ }
+ try! fm.copyItem(at: source, to: destination)
+ return (true, "")
+ case ["device", "copy", "to"]:
+ let destination = container.appendingPathComponent(value("--destination", args)!)
+ if value("--remove-existing-content", args) == "true" { try? fm.removeItem(at: destination) }
+ try! fm.createDirectory(at: destination.deletingLastPathComponent(), withIntermediateDirectories: true)
+ try! fm.copyItem(at: URL(fileURLWithPath: value("--source", args)!), to: destination)
+ return (true, "")
+ default:
+ return (false, "unexpected")
+ }
+ }
+ }
+ }
+
+ 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 setUp(device: FakeDevice) -> SaveTransfer {
+ let mac = SaveTransfer.macFolder(titleID: titleID, support: temporary.appendingPathComponent("Application Support"))
+ var t = SaveTransfer(titleID: titleID, mac: mac, device: "00008150-AAAA", bundle: "com.example.game", devicectl: device.control)
+ t.scratch = temporary
+ t.now = { Date(timeIntervalSince1970: 1_800_000_000) }
+ return t
+ }
+
+ private let older = Date(timeIntervalSince1970: 1_700_000_000), newer = Date(timeIntervalSince1970: 1_760_000_000)
+
+ func testTheMacSaveIsTheLaunchersFolderAndItsNewestFile() throws {
+ let support = temporary.appendingPathComponent("Application Support")
+ XCTAssertEqual(SaveTransfer.macFolder(titleID: titleID, support: support).path, support.path + "/nxnative/" + titleID)
+ let t = setUp(device: FakeDevice(temporary.appendingPathComponent("container")))
+ XCTAssertEqual(t.readMac(), SaveTransfer.Contents(), "no save yet")
+ try fm.createDirectory(at: t.mac.appendingPathComponent("save"), withIntermediateDirectories: true)
+ XCTAssertEqual(t.readMac(), SaveTransfer.Contents(), "an empty save folder is no save")
+ try write("a", t.mac.appendingPathComponent("save/slot0/data.bin"), date: older)
+ try write("b", t.mac.appendingPathComponent("save_device/common.bin"), date: newer)
+ try write("c", t.mac.appendingPathComponent("save.work/uncommitted.bin"), date: Date()) // a session's copy, not the save
+ XCTAssertEqual(t.readMac(), SaveTransfer.Contents(folders: ["save", "save_device"], newest: newer))
+ }
+
+ func testTheDeviceSaveIsReadFromTheGamesFolderInTheContainer() throws {
+ let device = FakeDevice(temporary.appendingPathComponent("container"))
+ let t = setUp(device: device)
+ let game = device.container.appendingPathComponent("Documents/games/" + titleID)
+ try write("img", game.appendingPathComponent("romfs.img"), date: older)
+ XCTAssertEqual(try t.readDevice(), SaveTransfer.Contents(), "installed, never saved")
+ try write("d", game.appendingPathComponent("save/data.bin"), date: newer)
+ XCTAssertEqual(try t.readDevice(), SaveTransfer.Contents(folders: ["save"], newest: newer))
+ for call in device.calls {
+ XCTAssertEqual(device.value("--domain-type", call), "appDataContainer")
+ XCTAssertEqual(device.value("--domain-identifier", call), "com.example.game")
+ XCTAssertEqual(device.value("--device", call), "00008150-AAAA")
+ }
+ device.reachable = false
+ XCTAssertThrowsError(try t.readDevice()) { error in
+ XCTAssertEqual(error as? SaveTransfer.Failure, .device("ERROR: The device is not connected. (com.apple.dt.CoreDeviceError error 4)"))
+ }
+ }
+
+ func testDeviceToMacBacksUpTheMacSaveAndReplacesIt() throws {
+ let device = FakeDevice(temporary.appendingPathComponent("container"))
+ let t = setUp(device: device)
+ try write("device save", device.container.appendingPathComponent("Documents/games/\(titleID)/save/data.bin"), date: newer)
+ try write("mac save", t.mac.appendingPathComponent("save/data.bin"), date: older)
+ try write("mac only", t.mac.appendingPathComponent("save/extra.bin"), date: older)
+ let backup = try XCTUnwrap(try t.deviceToMac())
+ XCTAssertEqual(backup.path, t.backups.path + "/\(stamp(1_800_000_000)) mac")
+ XCTAssertEqual(read(backup.appendingPathComponent("save/data.bin")), "mac save")
+ XCTAssertEqual(read(backup.appendingPathComponent("save/extra.bin")), "mac only")
+ XCTAssertEqual(read(t.mac.appendingPathComponent("save/data.bin")), "device save")
+ XCTAssertFalse(fm.fileExists(atPath: t.mac.appendingPathComponent("save/extra.bin").path), "the save is the device's, nothing older beside it")
+ let left = try fm.contentsOfDirectory(atPath: t.mac.path).sorted()
+ XCTAssertEqual(left, ["save", "save-backups"], "the incoming folder is gone")
+ // A second copy in the same second gets a folder of its own
+ let second = try XCTUnwrap(try t.deviceToMac())
+ XCTAssertEqual(second.lastPathComponent, backup.lastPathComponent + " 2")
+ XCTAssertEqual(read(second.appendingPathComponent("save/data.bin")), "device save")
+ }
+
+ func testDeviceToMacWithoutADeviceSaveLeavesTheMacAlone() throws {
+ let device = FakeDevice(temporary.appendingPathComponent("container"))
+ let t = setUp(device: device)
+ try write("img", device.container.appendingPathComponent("Documents/games/\(titleID)/romfs.img"), date: older)
+ try write("mac save", t.mac.appendingPathComponent("save/data.bin"), date: older)
+ XCTAssertThrowsError(try t.deviceToMac()) { XCTAssertEqual($0 as? SaveTransfer.Failure, .noDeviceSave) }
+ XCTAssertEqual(read(t.mac.appendingPathComponent("save/data.bin")), "mac save")
+ XCTAssertFalse(fm.fileExists(atPath: t.backups.path))
+ // A copy that fails partway leaves the Mac save too
+ try write("device save", device.container.appendingPathComponent("Documents/games/\(titleID)/save/data.bin"), date: newer)
+ device.failCopyFrom = true
+ XCTAssertThrowsError(try t.deviceToMac())
+ XCTAssertEqual(read(t.mac.appendingPathComponent("save/data.bin")), "mac save")
+ XCTAssertEqual(try fm.contentsOfDirectory(atPath: t.mac.path), ["save"])
+ }
+
+ func testMacToDeviceCopiesTheDeviceSaveToTheMacFirst() throws {
+ let device = FakeDevice(temporary.appendingPathComponent("container"))
+ let t = setUp(device: device)
+ let game = device.container.appendingPathComponent("Documents/games/\(titleID)")
+ try write("img", game.appendingPathComponent("romfs.img"), date: older)
+ try write("device save", game.appendingPathComponent("save/data.bin"), date: older)
+ try write("device stale", game.appendingPathComponent("save/stale.bin"), date: older)
+ try write("mac save", t.mac.appendingPathComponent("save/data.bin"), date: newer)
+ let backup = try XCTUnwrap(try t.macToDevice())
+ XCTAssertTrue(backup.lastPathComponent.hasSuffix(" device"))
+ XCTAssertEqual(read(backup.appendingPathComponent("save/data.bin")), "device save")
+ XCTAssertEqual(read(backup.appendingPathComponent("save/stale.bin")), "device stale")
+ XCTAssertEqual(read(game.appendingPathComponent("save/data.bin")), "mac save")
+ XCTAssertFalse(fm.fileExists(atPath: game.appendingPathComponent("save/stale.bin").path))
+ XCTAssertEqual(read(game.appendingPathComponent("romfs.img")), "img", "the game files beside the save stay")
+ let copyTo = try XCTUnwrap(device.calls.first { $0.prefix(3) == ["device", "copy", "to"] })
+ XCTAssertEqual(device.value("--destination", copyTo), "Documents/games/\(titleID)/save", "never the game's folder, which holds romfs.img")
+ XCTAssertEqual(device.value("--source", copyTo), t.mac.appendingPathComponent("save").path)
+ }
+
+ func testMacToDeviceReplacesNothingWhenTheBackupFails() throws {
+ let device = FakeDevice(temporary.appendingPathComponent("container"))
+ let t = setUp(device: device)
+ let game = device.container.appendingPathComponent("Documents/games/\(titleID)")
+ try write("device save", game.appendingPathComponent("save/data.bin"), date: older)
+ try write("mac save", t.mac.appendingPathComponent("save/data.bin"), date: newer)
+ device.failCopyFrom = true
+ XCTAssertThrowsError(try t.macToDevice())
+ XCTAssertEqual(read(game.appendingPathComponent("save/data.bin")), "device save")
+ XCTAssertFalse(device.calls.contains { $0.prefix(3) == ["device", "copy", "to"] })
+ // No Mac save: nothing is asked of the device at all
+ try fm.removeItem(at: t.mac.appendingPathComponent("save"))
+ device.calls = []
+ 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
+ device.failCopyFrom = false
+ device.reachable = false
+ try write("mac save", t.mac.appendingPathComponent("save/data.bin"), date: newer)
+ XCTAssertThrowsError(try t.macToDevice())
+ XCTAssertEqual(device.calls.count, 1)
+ }
+
+ func testACopyNestedInItsDestinationIsTheSaveFolderAllTheSame() throws {
+ let device = FakeDevice(temporary.appendingPathComponent("container"))
+ device.nested = true
+ let t = setUp(device: device)
+ try write("device save", device.container.appendingPathComponent("Documents/games/\(titleID)/save/sub/data.bin"), date: newer)
+ _ = try t.deviceToMac()
+ XCTAssertEqual(read(t.mac.appendingPathComponent("save/sub/data.bin")), "device save")
+ }
+
+ func testTheListingsDatesAreReadWhereverTheyAreNested() throws {
+ let json = """
+ {"info": {"outcome": "success"}, "result": {"files": [
+ {"name": "save", "fileType": "directory", "modificationDate": "2030-01-01T00:00:00Z"},
+ {"name": "a.bin", "fileType": "file", "metadata": {"modificationDate": "2025-05-01T10:00:00.250Z"}},
+ {"name": "b.bin", "fileType": "file", "modificationDate": "2025-06-01T10:00:00Z"}
+ ]}}
+ """
+ let parsed = try XCTUnwrap(SaveTransfer.parseListing(Data(json.utf8)))
+ XCTAssertEqual(parsed.files, 2, "the directory is not a file")
+ XCTAssertEqual(parsed.newest, ISO8601DateFormatter().date(from: "2025-06-01T10:00:00Z"))
+ XCTAssertNil(SaveTransfer.parseListing(Data("not json".utf8)))
+ XCTAssertEqual(SaveTransfer.parseListing(Data(#"{"result": {"files": []}}"#.utf8))?.files, 0)
+ XCTAssertEqual(SaveTransfer.date(1_700_000_000.0), Date(timeIntervalSince1970: 1_700_000_000))
+ XCTAssertEqual(SaveTransfer.date(700_000_000.0), Date(timeIntervalSinceReferenceDate: 700_000_000))
+ }
+
+ func testTheNewerSaveIsMarked() {
+ XCTAssertNil(SaveTransfer.newer(mac: nil, device: nil))
+ XCTAssertEqual(SaveTransfer.newer(mac: older, device: nil), .mac)
+ XCTAssertEqual(SaveTransfer.newer(mac: nil, device: older), .device)
+ XCTAssertEqual(SaveTransfer.newer(mac: older, device: newer), .device)
+ XCTAssertEqual(SaveTransfer.newer(mac: newer, device: older), .mac)
+ XCTAssertNil(SaveTransfer.newer(mac: older, device: older.addingTimeInterval(1)), "written together")
+ }
+
+ func testARunningBuildOfTheGameIsFoundByItsTitleID() throws {
+ func app(_ name: String, _ id: String?) throws -> URL {
+ let url = temporary.appendingPathComponent(name + ".app")
+ try fm.createDirectory(at: url.appendingPathComponent("Contents"), withIntermediateDirectories: true)
+ let info: [String: Any] = id.map { ["DMTitleID": $0] } ?? ["CFBundleName": name]
+ try PropertyListSerialization.data(fromPropertyList: info, format: .xml, options: 0).write(to: url.appendingPathComponent("Contents/Info.plist"))
+ return url
+ }
+ let other = try app("Other", "01007EF00011E000"), finder = try app("Finder", nil), game = try app("Hades", titleID.lowercased())
+ XCTAssertFalse(SaveTransfer.running(titleID: titleID, apps: [other, finder]))
+ XCTAssertTrue(SaveTransfer.running(titleID: titleID, apps: [other, finder, game]))
+ }
+
+ func testDevicectlsLastErrorLineIsTheMessage() {
+ XCTAssertEqual(SaveTransfer.lastLine("Acquired tunnel\nERROR: Failed to copy\n underlying: x\n"), "ERROR: Failed to copy")
+ XCTAssertEqual(SaveTransfer.lastLine("one\ntwo\n"), "two")
+ XCTAssertEqual(SaveTransfer.lastLine(""), "devicectl")
+ }
+
+ private func stamp(_ seconds: TimeInterval) -> String {
+ let f = DateFormatter()
+ f.locale = Locale(identifier: "en_US_POSIX")
+ f.dateFormat = "yyyy-MM-dd HH.mm.ss"
+ return f.string(from: Date(timeIntervalSince1970: seconds))
+ }
+}