Skip to content

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

Mac saves move beside the game; the iPhone can pick its game data from anywhere

LNPANDY0f779f5e63fa
diff --git a/dm/ios/Sources/DataBookmark.h b/dm/ios/Sources/DataBookmark.h
new file mode 100644
index 00000000..3aef3338
--- /dev/null
+++ b/dm/ios/Sources/DataBookmark.h
@@ -0,0 +1,32 @@
+// The game data the player picked from the Files app, remembered across launches.
+//
+// Why this exists: until now the only way to get a game's RomFS onto an iPhone was to copy it into
+// the app's Documents through the Files app — which the Files app can do, but only for a folder
+// *inside* the app's own container. A player who keeps 16 GB of game data on an external drive or
+// in iCloud Drive had to duplicate it into every game's container.
+//
+// iOS does not allow an app to remember a path outside its sandbox. It allows a *bookmark*: the
+// system hands back a token when the player picks a file in the document picker, and the app can
+// resolve that token later — even after a relaunch — and keep reading that file. The token is bound
+// to the app's signing identity, so a re-signed build (a new sideload, a new team) gets a stale one;
+// `stale` below is how that is reported, and the launcher asks the player to pick again rather than
+// failing silently.
+//
+// This file only holds and resolves the bookmark. The picker UI and the call that stores a new one
+// are in LauncherSettings.swift, which is where the rest of the player-facing settings live.
+
+#import <Foundation/Foundation.h>
+
+/// The bookmark the player stored, or nil when none was ever picked.
+NSData *dm_picked_data_bookmark(void);
+
+/// Resolve the stored bookmark to a path, or nil when there is none or it no longer resolves.
+/// `stale` (optional) is set when a bookmark exists but could not be used — the app is not signed
+/// the way it was when the player picked, so the picker has to be shown again.
+NSString *dm_picked_data_path(BOOL *stale);
+
+/// Store a bookmark for a URL the player just picked. Returns NO when the system refuses to make one.
+BOOL dm_store_picked_data(NSURL *url);
+
+/// Forget it (a player who wants the app to go back to its Documents copy).
+void dm_clear_picked_data(void);
diff --git a/dm/ios/Sources/DataBookmark.m b/dm/ios/Sources/DataBookmark.m
new file mode 100644
index 00000000..470e2949
--- /dev/null
+++ b/dm/ios/Sources/DataBookmark.m
@@ -0,0 +1,51 @@
+// See DataBookmark.h for why this exists.
+
+#import "DataBookmark.h"
+
+static NSString *const kPickedData = @"pickedDataBookmark";
+
+NSData *dm_picked_data_bookmark(void) {
+ return [NSUserDefaults.standardUserDefaults dataForKey:kPickedData];
+}
+
+NSString *dm_picked_data_path(BOOL *stale) {
+ if (stale) *stale = NO;
+ NSData *bookmark = dm_picked_data_bookmark();
+ if (bookmark.length == 0) return nil;
+ BOOL isStale = NO;
+ NSError *error = nil;
+ NSURL *url = [NSURL URLByResolvingBookmarkData:bookmark
+ options:0
+ relativeToURL:nil
+ bookmarkDataIsStale:&isStale
+ error:&error];
+ if (isStale && stale) *stale = YES;
+ if (!url) {
+ // A re-signed build gets a bookmark the system will not resolve for it. Keep the data —
+ // the player may install the same signature again — and let the caller ask for a new pick.
+ fprintf(stderr, "boot: the picked game-data bookmark does not resolve (%s)\n",
+ error.localizedDescription.UTF8String ?: "no reason given");
+ if (stale) *stale = YES;
+ return nil;
+ }
+ // The picker can hand back a file that was moved or deleted since. The caller checks what it
+ // needs (an image, a folder with the marker) and falls through if this path no longer holds it.
+ return url.path;
+}
+
+BOOL dm_store_picked_data(NSURL *url) {
+ NSError *error = nil;
+ NSData *bookmark = [url bookmarkDataWithOptions:0 includingResourceValuesForKeys:nil relativeToURL:nil error:&error];
+ if (!bookmark) {
+ fprintf(stderr, "[RED] could not bookmark %s: %s\n", url.path.UTF8String ?: "?",
+ error.localizedDescription.UTF8String ?: "no reason given");
+ return NO;
+ }
+ [NSUserDefaults.standardUserDefaults setObject:bookmark forKey:kPickedData];
+ fprintf(stderr, "launcher: game data set to %s\n", url.path.UTF8String ?: "?");
+ return YES;
+}
+
+void dm_clear_picked_data(void) {
+ [NSUserDefaults.standardUserDefaults removeObjectForKey:kPickedData];
+}
diff --git a/dm/ios/Sources/DmIOS-Bridging-Header.h b/dm/ios/Sources/DmIOS-Bridging-Header.h
new file mode 100644
index 00000000..92a2b3a5
--- /dev/null
+++ b/dm/ios/Sources/DmIOS-Bridging-Header.h
@@ -0,0 +1,3 @@
+// What Swift sees of the app's Objective-C: the data bookmark the Files app hands out (see
+// DataBookmark.h). project.yml points SWIFT_OBJC_BRIDGING_HEADER here.
+#import "DataBookmark.h"
diff --git a/dm/ios/Sources/Launcher.swift b/dm/ios/Sources/Launcher.swift
index 3c72edea..d5e3a961 100644
--- a/dm/ios/Sources/Launcher.swift
+++ b/dm/ios/Sources/Launcher.swift
@@ -64,6 +64,90 @@ private struct SettingRow: View {
}
}
+/// Where this game's data comes from, and a picker to change it.
+///
+/// The app can only read files it owns unless the player hands it a location through the document
+/// picker — so a game's RomFS kept on an external drive or in iCloud Drive could not be used at all
+/// before this. Picking an image (romfs.img) or a folder stores a bookmark (DataBookmark.m), and
+/// romfs_locate() prefers it from the next launch on.
+private struct GameDataSection: View {
+ @State private var picked: String = ""
+ @State private var note: String = ""
+ @State private var picking = false
+
+ var body: some View {
+ Section {
+ HStack {
+ Text("Game data")
+ Spacer()
+ Text(picked.isEmpty ? "This app's folder" : (picked as NSString).lastPathComponent)
+ .foregroundStyle(.secondary).lineLimit(1).truncationMode(.middle)
+ }
+ Button(picked.isEmpty ? "Choose game data…" : "Choose a different location…") { picking = true }
+ if !picked.isEmpty {
+ Button("Use the app's own data again", role: .destructive) {
+ dm_clear_picked_data(); refresh(); note = ""
+ }
+ }
+ } footer: {
+ Text(note.isEmpty
+ ? "Pick the game's romfs.img or its RomFS folder — an external drive or iCloud Drive works. The app remembers the choice; a re-signed build asks once more."
+ : note)
+ }
+ .sheet(isPresented: $picking) {
+ DocumentPicker { url in
+ picking = false
+ if dm_store_picked_data(url) {
+ note = "Saved. The game uses this location from the next start."
+ refresh()
+ } else {
+ note = "That location could not be remembered — try a different one."
+ }
+ } onCancel: { picking = false }
+ }
+ .onAppear(perform: refresh)
+ }
+
+ private func refresh() {
+ var stale = false
+ picked = dm_picked_data_path(&stale) ?? ""
+ if stale && picked.isEmpty {
+ note = "The location you picked before is no longer readable (the app was signed differently). Please choose it again."
+ }
+ }
+}
+
+/// UIDocumentPickerViewController for files and folders, in the two callbacks a SwiftUI sheet wants.
+private struct DocumentPicker: UIViewControllerRepresentable {
+ let onPick: (URL) -> Void
+ let onCancel: () -> Void
+
+ func makeUIViewController(context: Context) -> UIDocumentPickerViewController {
+ // .open (not .import): the file stays where it is and the bookmark keeps pointing at it,
+ // which is the whole point — an import would copy 16 GB into the app's container.
+ let picker = UIDocumentPickerViewController(forOpeningContentTypes: [.item], asCopy: false)
+ picker.allowsMultipleSelection = false
+ picker.delegate = context.coordinator
+ return picker
+ }
+
+ func updateUIViewController(_ vc: UIDocumentPickerViewController, context: Context) {}
+
+ func makeCoordinator() -> Coordinator { Coordinator(onPick: onPick, onCancel: onCancel) }
+
+ final class Coordinator: NSObject, UIDocumentPickerDelegate {
+ let onPick: (URL) -> Void
+ let onCancel: () -> Void
+ init(onPick: @escaping (URL) -> Void, onCancel: @escaping () -> Void) {
+ self.onPick = onPick; self.onCancel = onCancel
+ }
+ func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
+ if let url = urls.first { onPick(url) } else { onCancel() }
+ }
+ func documentPickerWasCancelled(_ controller: UIDocumentPickerViewController) { onCancel() }
+ }
+}
+
private struct LauncherView: View {
@ObservedObject var m: LauncherModel
let play: () -> Void
@@ -98,6 +182,7 @@ private struct LauncherView: View {
} footer: {
Text("Brings back all settings this game was tested with.")
}
+ GameDataSection()
Section {
HStack {
Text("Memory available")
diff --git a/dm/ios/Sources/main.m b/dm/ios/Sources/main.m
index de02ef4f..1393523e 100644
--- a/dm/ios/Sources/main.m
+++ b/dm/ios/Sources/main.m
@@ -9,6 +9,7 @@
#include "hle_profile.h" // the runtime game profile (DM_PROFILE): the RomFS marker path comes from it
#include "front.h"
#include "romfs_image.h"
+#include "DataBookmark.h"
int dm_main(int argc, char **argv); // dm/host/main.c compiled in with -Dmain=dm_main
UIViewController *front_ios_root(void);
@@ -53,6 +54,22 @@ static NSString *game_dir_for(const char *title_id) {
static NSString *romfs_locate(void) {
NSFileManager *fm = NSFileManager.defaultManager;
NSString *doc = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
+ // What the player picked in the Files app wins over everything: it is the one path they chose
+ // on purpose, possibly on an external drive, and it costs nothing when they never picked one
+ // (the bookmark is absent and this falls straight through). An image or a folder both work,
+ // and a pick that no longer holds this game's data falls through rather than failing the boot.
+ {
+ BOOL stale = NO;
+ NSString *picked = dm_picked_data_path(&stale);
+ if (stale) fprintf(stderr, "boot: the picked game-data location needs to be chosen again (the app is signed differently now)\n");
+ if (picked.length) {
+ if (romfs_image_complete(picked)) { fprintf(stderr, "boot: game data from the picked image %s\n", picked.UTF8String); return picked; }
+ NSString *pimg = [picked stringByAppendingPathComponent:@"romfs.img"];
+ if (romfs_image_complete(pimg)) { fprintf(stderr, "boot: game data from the picked folder %s\n", pimg.UTF8String); return pimg; }
+ if (romfs_dir_ok(picked)) { fprintf(stderr, "boot: game data from the picked folder %s\n", picked.UTF8String); return picked; }
+ fprintf(stderr, "boot: the picked location %s holds no game data for this title; using the app's own\n", picked.UTF8String);
+ }
+ }
// Per-game first: Documents/games/<id>/romfs.img (one file, what push_romfs.sh sends) or
// Documents/games/<id>/romfs/ — the launcher-style layout, and what lets a user keep several
// games' data side by side or on an external drive. The marker check inside romfs_dir_ok is
diff --git a/dm/ios/project.yml b/dm/ios/project.yml
index 4a1e3b65..298b2eed 100644
--- a/dm/ios/project.yml
+++ b/dm/ios/project.yml
@@ -76,6 +76,7 @@ targets:
OTHER_CFLAGS: $(inherited) -mcpu=apple-a18 # The host assembly contains LSE atomic instructions, which the default baseline does not accept
CLANG_ENABLE_OBJC_ARC: YES
SWIFT_VERSION: "5.0" # Launcher.swift (SwiftUI)
+ SWIFT_OBJC_BRIDGING_HEADER: Sources/DmIOS-Bridging-Header.h # DataBookmark (the Files app pick)
DEBUG_INFORMATION_FORMAT: dwarf
GCC_WARN_INHIBIT_ALL_WARNINGS: YES
schemes:
diff --git a/dm/ios/tests/test_romfs_startup.py b/dm/ios/tests/test_romfs_startup.py
index de7fca36..271744e3 100644
--- a/dm/ios/tests/test_romfs_startup.py
+++ b/dm/ios/tests/test_romfs_startup.py
@@ -27,9 +27,15 @@ class Startup(unittest.TestCase):
'@interface FixtureBundle : NSObject\n+ (instancetype)mainBundle;\n- (NSString *)resourcePath;\n@end\n'
'@implementation FixtureBundle\n+ (instancetype)mainBundle { return [self new]; }\n'
'- (NSString *)resourcePath { return fixture_bundle; }\n@end\n#define NSBundle FixtureBundle\n'
- '#define NSSearchPathForDirectoriesInDomains(a,b,c) @[fixture_doc]\n#define NSTemporaryDirectory() fixture_tmp\n' + locator +
+ '#define NSSearchPathForDirectoriesInDomains(a,b,c) @[fixture_doc]\n#define NSTemporaryDirectory() fixture_tmp\n'
+ # The picked-location bookmark (DataBookmark.m): the fixture answers it from a
+ # variable, so a test can put the player's choice anywhere on disk.
+ 'static NSString *fixture_picked;\n'
+ 'NSString *dm_picked_data_path(BOOL *stale) { if (stale) *stale = NO; return fixture_picked; }\n' + locator +
'\nint main(int argc, char **argv) { @autoreleasepool { if (argc < 3) return 2;\n'
- 'fixture_doc = @(argv[1]); fixture_tmp = @(argv[2]); fixture_bundle = argc > 3 ? @(argv[3]) : @"/nonexistent-fixture"; NSString *p = romfs_locate();\n'
+ 'fixture_doc = @(argv[1]); fixture_tmp = @(argv[2]); fixture_bundle = argc > 3 ? @(argv[3]) : @"/nonexistent-fixture";\n'
+ 'if (argc > 4) fixture_picked = @(argv[4]); // the location the player picked, when a test sets one\n'
+ 'NSString *p = romfs_locate();\n'
'if (!p) return 1; puts(p.fileSystemRepresentation); return 0; }}\n')
cls.locator = root / 'locator'
subprocess.run(['clang', '-fobjc-arc', '-Wall', '-Werror', '-I', str(REPO / 'dm/host'),
@@ -66,5 +72,35 @@ class Startup(unittest.TestCase):
self.assertEqual(locate(), str(folder))
image.pack(source, doc / 'romfs.img'); self.assertEqual(locate(), str(doc / 'romfs.img'))
+ def test_the_location_the_player_picked_wins_over_everything(self):
+ """The Files-app pick (DataBookmark): an image, a folder holding one, or a plain tree."""
+ with tempfile.TemporaryDirectory() as temporary:
+ root = Path(temporary); doc = root / 'Documents'; doc.mkdir()
+ tmp = root / 'temp'; tmp.mkdir(); bundle = root / 'App'; bundle.mkdir()
+ source = root / 'source'; source.mkdir(); (source / 'marker').write_text('resource')
+ image.pack(source, bundle / 'romfs.img')
+ # something the app would otherwise use, so "wins" means something
+ image.pack(source, doc / 'romfs.img')
+ external = root / 'external'; external.mkdir()
+
+ def locate(picked=None):
+ argv = [str(self.locator), str(doc), str(tmp), str(bundle)] + ([str(picked)] if picked else [])
+ result = subprocess.run(argv, capture_output=True, text=True)
+ self.assertEqual(result.returncode, 0, result.stderr)
+ return result.stdout.strip()
+
+ # 1. the picked path IS the image
+ image.pack(source, external / 'mine.img')
+ self.assertEqual(locate(external / 'mine.img'), str(external / 'mine.img'))
+ # 2. the picked path is a folder holding romfs.img
+ image.pack(source, external / 'romfs.img')
+ self.assertEqual(locate(external), str(external / 'romfs.img'))
+ # 3. the picked path is a plain RomFS tree
+ (external / 'romfs.img').unlink(); (external / 'marker').write_text('resource')
+ self.assertEqual(locate(external), str(external))
+ # 4. a picked path holding none of this game's data falls through to the app's own copy
+ empty = root / 'empty'; empty.mkdir()
+ self.assertEqual(locate(empty), str(doc / 'romfs.img'))
+
if __name__ == '__main__': unittest.main()
diff --git a/dm/mac/launcher.c b/dm/mac/launcher.c
index 3c5d1fef..21819303 100644
--- a/dm/mac/launcher.c
+++ b/dm/mac/launcher.c
@@ -16,6 +16,7 @@
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
+#include <dirent.h>
#include <sys/wait.h>
#include <unistd.h>
#include "romfs_image.h"
@@ -58,6 +59,43 @@ static void mkdirs(const char *path) { // mkdir -p
mkdir(p, 0755);
}
+static int dir_has_entries(const char *path) { // anything inside at all (a save folder, a log folder)
+ DIR *d = opendir(path); if (!d) return 0;
+ struct dirent *e; int any = 0;
+ while ((e = readdir(d))) if (strcmp(e->d_name, ".") && strcmp(e->d_name, "..")) { any = 1; break; }
+ closedir(d); return any;
+}
+
+static int copy_file(const char *from, const char *to) {
+ FILE *in = fopen(from, "rb"); if (!in) return 0;
+ FILE *out = fopen(to, "wb"); if (!out) { fclose(in); return 0; }
+ char buf[1 << 16]; size_t n; int ok = 1;
+ while ((n = fread(buf, 1, sizeof buf, in)) > 0) if (fwrite(buf, 1, n, out) != n) { ok = 0; break; }
+ if (ferror(in)) ok = 0;
+ fclose(in); if (fclose(out)) ok = 0;
+ if (!ok) unlink(to);
+ return ok;
+}
+
+/// Recursive copy for the one-time migration of a save folder. Symlinks are followed (a save is
+/// plain files); a file that already exists is left alone, so a half-finished copy can be resumed.
+static void copy_tree(const char *from, const char *to) {
+ mkdirs(to);
+ DIR *d = opendir(from); if (!d) return;
+ struct dirent *e;
+ while ((e = readdir(d))) {
+ if (!strcmp(e->d_name, ".") || !strcmp(e->d_name, "..")) continue;
+ char a[PATH_MAX], b[PATH_MAX];
+ snprintf(a, sizeof a, "%s/%s", from, e->d_name);
+ snprintf(b, sizeof b, "%s/%s", to, e->d_name);
+ struct stat st;
+ if (stat(a, &st)) continue;
+ if (S_ISDIR(st.st_mode)) copy_tree(a, b);
+ else if (S_ISREG(st.st_mode) && access(b, F_OK)) copy_file(a, b);
+ }
+ closedir(d);
+}
+
static void env_file(const char *path) { // KEY=VALUE lines, # starts a comment; a variable already set stays
FILE *f = fopen(path, "r"); if (!f) return;
char ln[4096];
@@ -98,6 +136,39 @@ int main(void) {
snprintf(sup, sizeof sup, "%s/Library/Application Support/nxnative/%s", home, id);
snprintf(save, sizeof save, "%s/save", sup); snprintf(temp, sizeof temp, "%s/temp", sup);
snprintf(logs, sizeof logs, "%s/Library/Logs/nxnative", home);
+ // Saves and logs beside the game, not under ~/Library: a library folder the user can move or
+ // keep on an external drive has to carry its saves with it, or they are effectively lost the
+ // moment the folder moves (the files are still in ~/Library, where nobody looks for them).
+ //
+ // The library root is the folder the app sits in, when that folder also holds games/ — the
+ // layout the Mac front end writes (<out>/<id>.app, <out>/games/<id>/romfs.img). A bundle
+ // copied somewhere else keeps the old ~/Library paths, so nothing breaks for a user who never
+ // used the launcher's folder.
+ {
+ char appdir[PATH_MAX]; snprintf(appdir, sizeof appdir, "%s", exe);
+ *strrchr(appdir, '/') = 0; *strrchr(appdir, '/') = 0; *strrchr(appdir, '/') = 0; // …/<id>.app/Contents/MacOS/<launcher> → the .app's folder
+ char probe[PATH_MAX]; snprintf(probe, sizeof probe, "%s/games", appdir);
+ if (!stat(probe, &st)) {
+ snprintf(save, sizeof save, "%s/save/%s", appdir, id);
+ snprintf(logs, sizeof logs, "%s/log", appdir);
+ snprintf(temp, sizeof temp, "%s/temp/%s", appdir, id);
+ // First run after this change: bring the old saves and log across rather than starting
+ // the player on an empty save slot. Copied, not moved — an older build of the same app
+ // still reads the old place, and a copy is cheap next to a save.
+ char oldsave[PATH_MAX], oldlog[PATH_MAX];
+ snprintf(oldsave, sizeof oldsave, "%s/Library/Application Support/nxnative/%s/save", home, id);
+ snprintf(oldlog, sizeof oldlog, "%s/Library/Logs/nxnative/%s.log", home, id);
+ mkdirs(save); mkdirs(logs); mkdirs(temp);
+ if (dir_has_entries(oldsave) && !dir_has_entries(save)) {
+ copy_tree(oldsave, save);
+ fprintf(stderr, "launcher: saves copied from %s to %s (they now live with the game)\n", oldsave, save);
+ }
+ char newlog[PATH_MAX]; snprintf(newlog, sizeof newlog, "%s/%s.log", logs, id);
+ if (!stat(oldlog, &st) && stat(newlog, &st)) {
+ if (copy_file(oldlog, newlog)) fprintf(stderr, "launcher: the previous log was copied from %s\n", oldlog);
+ }
+ }
+ }
snprintf(log, sizeof log, "%s/%s.log", logs, id); snprintf(prev, sizeof prev, "%s/%s.prev.log", logs, id);
mkdirs(save); mkdirs(temp); mkdirs(logs);
rename(log, prev);
diff --git a/scripts/sync_upstream.py b/scripts/sync_upstream.py
index fe1670e4..05a30b47 100644
--- a/scripts/sync_upstream.py
+++ b/scripts/sync_upstream.py
@@ -893,6 +893,22 @@ static NSString *game_dir_for(const char *title_id) {
static NSString *romfs_locate(void) {
NSFileManager *fm = NSFileManager.defaultManager;
NSString *doc = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
+ // What the player picked in the Files app wins over everything: it is the one path they chose
+ // on purpose, possibly on an external drive, and it costs nothing when they never picked one
+ // (the bookmark is absent and this falls straight through). An image or a folder both work,
+ // and a pick that no longer holds this game's data falls through rather than failing the boot.
+ {
+ BOOL stale = NO;
+ NSString *picked = dm_picked_data_path(&stale);
+ if (stale) fprintf(stderr, "boot: the picked game-data location needs to be chosen again (the app is signed differently now)\\n");
+ if (picked.length) {
+ if (romfs_image_complete(picked)) { fprintf(stderr, "boot: game data from the picked image %s\\n", picked.UTF8String); return picked; }
+ NSString *pimg = [picked stringByAppendingPathComponent:@"romfs.img"];
+ if (romfs_image_complete(pimg)) { fprintf(stderr, "boot: game data from the picked folder %s\\n", pimg.UTF8String); return pimg; }
+ if (romfs_dir_ok(picked)) { fprintf(stderr, "boot: game data from the picked folder %s\\n", picked.UTF8String); return picked; }
+ fprintf(stderr, "boot: the picked location %s holds no game data for this title; using the app's own\\n", picked.UTF8String);
+ }
+ }
// Per-game first: Documents/games/<id>/romfs.img (one file, what push_romfs.sh sends) or
// Documents/games/<id>/romfs/ — the launcher-style layout, and what lets a user keep several
// games\' data side by side or on an external drive. The marker check inside romfs_dir_ok is
@@ -946,6 +962,9 @@ def patch_main_m(t):
('runtime profile include',
('#include "game_profile.h" // game profile constants (the RomFS marker path)',
'#include "hle_profile.h" // the runtime game profile (DM_PROFILE): the RomFS marker path comes from it')),
+ # the Files-app pick (DataBookmark.m): romfs_locate asks it before anything else
+ ('picked data include',
+ ('#include "romfs_image.h"\n', '#include "romfs_image.h"\n#include "DataBookmark.h"\n')),
('romfs per-game', MAIN_M_ROMFS),
('per-game data dirs', MAIN_M_ENV),
]