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
Saves: follow the library folder marker for the Mac save, and say which folder is used
v0lumehib60ccdfd4333
diff --git a/frontend-qt/nspb_qt/localization.py b/frontend-qt/nspb_qt/localization.pyindex 61bd3020..9ec10195 100644--- a/frontend-qt/nspb_qt/localization.py+++ b/frontend-qt/nspb_qt/localization.py@@ -235,6 +235,9 @@ TABLE: dict[str, tuple[str, str, str]] = {'saves.mac': ('这台 Mac', 'This Mac', 'Den här Mac-datorn'),'saves.saved': ('保存于 %@', 'Saved %@', 'Sparad %@'),'saves.none': ('还没有存档', 'No save yet', 'Ingen sparfil ännu'),+ 'saves.macLibrary': ('资料库文件夹中的存档:%@', 'In the library folder: %@', 'I biblioteksmappen: %@'),+ 'saves.macStandard': ('默认位置:%@', 'In the default location: %@', 'På standardplatsen: %@'),+ 'saves.macPending': ('默认位置:%@。游戏下次启动时会把它复制到资料库文件夹。', 'In the default location: %@. The game copies it to the library folder on its next start.', 'På standardplatsen: %@. Spelet kopierar den till biblioteksmappen vid nästa start.'),'saves.reading': ('正在读取 %@…', 'Reading %@…', 'Läser från %@ …'),'saves.notInstalled': ('在 %@ 上没有找到这个游戏。请先安装,再刷新。', 'This game was not found on %@. Install it there, then refresh.', 'Spelet hittades inte på %@. Installera det där och uppdatera sedan.'),'saves.noDevices': ('没有已配对的 iPhone 或 iPad。请在 Xcode 中配对设备并解锁,然后刷新。', 'No paired iPhone or iPad found. Pair it in Xcode and unlock it, then refresh.', 'Ingen ihopparad iPhone eller iPad hittades. Para ihop den i Xcode, lås upp den och uppdatera sedan.'),diff --git a/frontend/Sources/NSPortBuilder/Localization.swift b/frontend/Sources/NSPortBuilder/Localization.swiftindex 822d5d16..ff2e84b7 100644--- a/frontend/Sources/NSPortBuilder/Localization.swift+++ b/frontend/Sources/NSPortBuilder/Localization.swift@@ -276,6 +276,9 @@ enum L10n {"saves.mac": ("这台 Mac", "This Mac"),"saves.saved": ("保存于 %@", "Saved %@"),"saves.none": ("还没有存档", "No save yet"),+ "saves.macLibrary": ("资料库文件夹中的存档:%@", "In the library folder: %@"),+ "saves.macStandard": ("默认位置:%@", "In the default location: %@"),+ "saves.macPending": ("默认位置:%@。游戏下次启动时会把它复制到资料库文件夹。", "In the default location: %@. The game copies it to the library folder on its next start."),"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."),@@ -1186,6 +1189,9 @@ enum L10n {"saves.mac": "Den här Mac-datorn","saves.saved": "Sparad %@","saves.none": "Ingen sparfil ännu",+ "saves.macLibrary": "I biblioteksmappen: %@",+ "saves.macStandard": "På standardplatsen: %@",+ "saves.macPending": "På standardplatsen: %@. Spelet kopierar den till biblioteksmappen vid nästa start.","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.",diff --git a/frontend/Sources/NSPortBuilder/SaveDiscovery.swift b/frontend/Sources/NSPortBuilder/SaveDiscovery.swiftindex 710a580c..28c00e7f 100644--- a/frontend/Sources/NSPortBuilder/SaveDiscovery.swift+++ b/frontend/Sources/NSPortBuilder/SaveDiscovery.swift@@ -97,6 +97,7 @@ final class SavesModel: ObservableObject {@Published private(set) var selected = ""@Published private(set) var deviceState = DeviceState.reading@Published private(set) var macSave = SaveTransfer.Contents()+ @Published private(set) var macLocation: SaveTransfer.MacLocation@Published private(set) var found: SaveTransfer? // the game's app on the selected device, once it is readyprivate var generation = 0private var started = false@@ -107,6 +108,7 @@ final class SavesModel: ObservableObject {self.template = template; self.name = name; self.recordedBundle = recordedBundle; self.recordedDevice = recordedDeviceself.installTarget = installTarget; self.remembered = remembered; self.rememberChoice = rememberChoiceself.listDevices = listDevices; self.timeout = timeout+ self.macLocation = template.macLocation()}var isReading: Bool { deviceState == .reading }@@ -151,6 +153,7 @@ final class SavesModel: ObservableObject {generation += 1let mine = generationmacSave = template.readMac()+ macLocation = template.macLocation()deviceState = .readingfound = nillet known = devices, current = selecteddiff --git a/frontend/Sources/NSPortBuilder/SaveTransfer.swift b/frontend/Sources/NSPortBuilder/SaveTransfer.swiftindex fa7ddaaa..e682d235 100644--- a/frontend/Sources/NSPortBuilder/SaveTransfer.swift+++ b/frontend/Sources/NSPortBuilder/SaveTransfer.swift@@ -48,8 +48,8 @@ struct DeviceControl {/// 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;+/// Where the saves are: the Mac app keeps them beside itself in <app's folder>/save/<title ID> when that folder holds the+/// library marker (.nx2apple-library, which the launcher's build writes, fork patch mac-library-folder), 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, 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@@ -86,14 +86,14 @@ struct SaveTransfer {support.appendingPathComponent("nxnative").appendingPathComponent(titleID).appendingPathComponent("save")}- /// The Mac app's DM_SAVE, by launcher.c's rule: beside the app when the app's folder also holds games/, else ~/Library.+ /// The Mac app's DM_SAVE, by launcher.c's rule: beside the app when the app's folder holds the library marker, else ~/Library.+ /// The second value is the ~/Library save the app copies across on its first start in a library folder (nil without the marker).static func macSave(titleID: String, appPath: String,support: URL = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0]) -> (save: URL, legacy: URL?) {let legacy = legacyMacSave(titleID: titleID, support: support)guard !appPath.isEmpty else { return (legacy, nil) }let folder = URL(fileURLWithPath: appPath).deletingLastPathComponent()- var isDir: ObjCBool = false- guard FileManager.default.fileExists(atPath: folder.appendingPathComponent("games").path, isDirectory: &isDir), isDir.boolValue else { return (legacy, nil) }+ guard FileManager.default.fileExists(atPath: folder.appendingPathComponent(GameLog.marker).path) else { return (legacy, nil) }return (folder.appendingPathComponent("save").appendingPathComponent(titleID), legacy)}@@ -121,6 +121,24 @@ struct SaveTransfer {// ---- reading ----+ /// Which Mac save the Saves window reads, for the line under "This Mac".+ enum MacLocation: Equatable {+ case library(URL) // beside the app, the library folder's save/<title ID>: what the game reads+ case standard(URL) // ~/Library/Application Support, the default location (no library folder)+ case pending(URL) // the ~/Library save of a game in a library folder, which the game copies across on its next start+ }++ /// The folder the game reads its save from, by the launcher's rule. In a library folder that is save/<title ID> beside the+ /// app, also when both exist (the game reads that one and copies the ~/Library save only while it is empty), and the+ /// ~/Library one only while nothing is beside the app yet.+ func macLocation() -> MacLocation {+ guard legacySave != nil else { return .standard(macSave) }+ for f in Self.folders {+ if let source = macSource(f), Self.macPath(f, save: macSave) != source { return .pending(Self.macPath("save", save: legacySave!)) }+ }+ return .library(macSave)+ }+func readMac() -> Contents {Self.folders.reduce(into: Contents()) { c, f inguard let source = macSource(f), let date = Self.newest(in: source) else { return }@@ -398,6 +416,15 @@ struct SavesView: View {private var game: LibraryGame? { library.games.first { $0.id == gameID } }private var macSave: SaveTransfer.Contents { model.macSave }private var deviceSave: SaveTransfer.Contents? { model.deviceSave }+ /// Which folder the Mac save is read from, so "No save yet" says where it looked.+ private var macLocationText: String {+ func shown(_ url: URL) -> String { (url.path as NSString).abbreviatingWithTildeInPath }+ switch model.macLocation {+ case .library(let url): return String(format: m.t("saves.macLibrary"), shown(url))+ case .standard(let url): return String(format: m.t("saves.macStandard"), shown(url))+ case .pending(let url): return String(format: m.t("saves.macPending"), shown(url))+ }+ }/// 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 }@@ -491,6 +518,10 @@ struct SavesView: View {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)+ if side == .mac {+ Text(macLocationText).font(.manrope(11)).foregroundStyle(.tertiary).lineLimit(2).truncationMode(.middle)+ .fixedSize(horizontal: false, vertical: true)+ }}Spacer(minLength: 12)if newer == side && (side == .mac || deviceSave != nil) {diff --git a/frontend/Tests/NSPortBuilderTests/SaveTransferTests.swift b/frontend/Tests/NSPortBuilderTests/SaveTransferTests.swiftindex 619f3472..ebca2483 100644--- a/frontend/Tests/NSPortBuilderTests/SaveTransferTests.swift+++ b/frontend/Tests/NSPortBuilderTests/SaveTransferTests.swift@@ -95,15 +95,17 @@ final class SaveTransferTests: XCTestCase {return t}- /// The launcher's layout: <folder>/<id>.app beside <folder>/games keeps its save in <folder>/save/<id> (launcher.c), and- /// reads the ~/Library save only until it has brought it across. A bundle anywhere else keeps ~/Library.- func testTheMacSaveFollowsTheAppWhenItsFolderHoldsGames() throws {+ /// The library folder layout: <folder>/<id>.app beside <folder>/.nx2apple-library keeps its save in <folder>/save/<id>+ /// (launcher.c), and reads the ~/Library save only until it has brought it across. A bundle anywhere else keeps ~/Library.+ func testTheMacSaveFollowsTheAppWhenItsFolderHoldsTheLibraryMarker() throws {let support = temporary.appendingPathComponent("Application Support")let library = temporary.appendingPathComponent("Games")let app = library.appendingPathComponent("\(titleID).app")try fm.createDirectory(at: app, withIntermediateDirectories: true)- XCTAssertNil(SaveTransfer.macSave(titleID: titleID, appPath: app.path, support: support).legacy, "no games/ beside it: ~/Library")+ XCTAssertNil(SaveTransfer.macSave(titleID: titleID, appPath: app.path, support: support).legacy, "no marker beside it: ~/Library")try fm.createDirectory(at: library.appendingPathComponent("games"), withIntermediateDirectories: true)+ XCTAssertNil(SaveTransfer.macSave(titleID: titleID, appPath: app.path, support: support).legacy, "a games/ folder alone is not the layout")+ try Data().write(to: library.appendingPathComponent(".nx2apple-library"))let paths = SaveTransfer.macSave(titleID: titleID, appPath: app.path, support: support)XCTAssertEqual(paths.save.path, library.path + "/save/" + titleID)XCTAssertEqual(SaveTransfer.macPath("save_device", save: paths.save).path, library.path + "/save/" + titleID + "_device")@@ -118,6 +120,58 @@ final class SaveTransferTests: XCTestCase {XCTAssertEqual(t.backups.path, library.path + "/save/" + titleID + "-backups")}+ /// A library folder in a temporary place: the app, the marker, and the Application Support folder the default save lives in.+ private func layout(marker: Bool) throws -> (library: URL, app: URL, support: URL, transfer: SaveTransfer) {+ let support = temporary.appendingPathComponent("Application Support")+ let library = temporary.appendingPathComponent("Library folder")+ let app = library.appendingPathComponent("\(titleID).app")+ try fm.createDirectory(at: app, withIntermediateDirectories: true)+ if marker { try Data().write(to: library.appendingPathComponent(".nx2apple-library")) }+ let paths = SaveTransfer.macSave(titleID: titleID, appPath: app.path, support: support)+ var t = SaveTransfer(titleID: titleID, macSave: paths.save, legacySave: paths.legacy, device: "00008150-AAAA", bundle: "com.example.game",+ devicectl: FakeDevice(temporary.appendingPathComponent("container")).control)+ t.scratch = temporary+ return (library, app, support, t)+ }++ func testALibraryFolderGameReadsItsSaveBesideTheApp() throws {+ let l = try layout(marker: true)+ let beside = l.library.appendingPathComponent("save/\(titleID)")+ XCTAssertEqual(l.transfer.macLocation(), .library(beside), "nothing yet: where the game will write")+ XCTAssertEqual(l.transfer.readMac(), SaveTransfer.Contents(), "no save yet")+ try write("a", beside.appendingPathComponent("slot0/data.bin"), date: newer)+ XCTAssertEqual(l.transfer.readMac(), SaveTransfer.Contents(folders: ["save"], newest: newer))+ XCTAssertEqual(l.transfer.macLocation(), .library(beside))+ XCTAssertEqual(l.transfer.macSource("save"), beside)+ }++ func testADefaultLocationGameReadsApplicationSupport() throws {+ let l = try layout(marker: false)+ let standard = SaveTransfer.legacyMacSave(titleID: titleID, support: l.support)+ XCTAssertEqual(l.transfer.macLocation(), .standard(standard))+ try write("a", standard.appendingPathComponent("data.bin"), date: older)+ try write("b", l.library.appendingPathComponent("save/\(titleID)/data.bin"), date: newer) // not the layout: ignored+ XCTAssertEqual(l.transfer.readMac(), SaveTransfer.Contents(folders: ["save"], newest: older))+ XCTAssertEqual(l.transfer.macLocation(), .standard(standard))+ }++ /// Both exist: the game reads (and writes) the one beside the app, whatever the dates, and copies ~/Library only while+ /// that one is empty. So the window shows the library folder's save, and the ~/Library one only until the first start.+ func testALibraryFolderWithBothSavesPrefersTheOneBesideTheApp() throws {+ let l = try layout(marker: true)+ let standard = SaveTransfer.legacyMacSave(titleID: titleID, support: l.support)+ let beside = l.library.appendingPathComponent("save/\(titleID)")+ try write("old", standard.appendingPathComponent("data.bin"), date: newer)+ XCTAssertEqual(l.transfer.macLocation(), .pending(standard), "only the ~/Library save: the game copies it on its next start")+ XCTAssertEqual(l.transfer.readMac(), SaveTransfer.Contents(folders: ["save"], newest: newer))+ try fm.createDirectory(at: beside, withIntermediateDirectories: true)+ XCTAssertEqual(l.transfer.macLocation(), .pending(standard), "an empty folder beside the app counts as nothing, as for the game")+ try write("kept", beside.appendingPathComponent("data.bin"), date: older)+ XCTAssertEqual(l.transfer.macLocation(), .library(beside))+ XCTAssertEqual(l.transfer.readMac(), SaveTransfer.Contents(folders: ["save"], newest: older), "the library folder wins over a newer ~/Library save")+ XCTAssertEqual(l.transfer.macSource("save"), beside)+ }+private let older = Date(timeIntervalSince1970: 1_700_000_000), newer = Date(timeIntervalSince1970: 1_760_000_000)func testTheMacSaveIsTheLaunchersFolderAndItsNewestFile() throws {