Skip to content

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

Device install: the game files go as the RomFS archive, as for sideloading

v0lumehi6278a69a1249
diff --git a/frontend-qt/nspb_qt/localization.py b/frontend-qt/nspb_qt/localization.py
index 8bfa2962..95dcc001 100644
--- a/frontend-qt/nspb_qt/localization.py
+++ b/frontend-qt/nspb_qt/localization.py
@@ -33,9 +33,11 @@ TABLE: dict[str, tuple[str, str]] = {
'dev.refresh': ('刷新', 'Refresh'),
'dev.team': ('签名团队', 'Signing team'),
'dev.noTeam': ('没有开发证书。在 Xcode 中登录 Apple ID(设置 → 账户)即可获得。', 'No development certificate. Sign in to Xcode with your Apple ID (Settings → Accounts) to get one.'),
- 'dev.note': ('Xcode 会为这台设备签名并直接安装,游戏文件已包含在 App 中,安装可能需要几分钟。第一次需要在设备上开启开发者模式,并信任开发者(设置 → 通用 → VPN 与设备管理)。', 'Xcode signs the game for this device and installs it there, with the game files inside the app; installing can take a few minutes. The first time, turn on Developer Mode on the device and trust the developer (Settings → General → VPN & Device Management).'),
+ 'dev.note': ('Xcode 会为这台设备签名并直接安装,游戏文件以 RomFS 归档复制到 App 的“文稿”中,与侧载相同;第一次复制大型游戏需要几分钟。第一次需要在设备上开启开发者模式,并信任开发者(设置 → 通用 → VPN 与设备管理)。', 'Xcode signs the game for this device and installs it there, then copies the game files into the app’s Documents as the RomFS archive, 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).'),
'dev.signStage': ('为 %@ 签名', 'Sign for %@'),
'dev.installStage': ('安装到 %@', 'Install on %@'),
+ 'dev.copyStage': ('复制游戏文件到 %@', 'Copy the game files to %@'),
+ 'dev.copyFailed': ('复制游戏文件失败:%@', 'Copying the game files failed: %@'),
'dev.installed': ('已安装到 %@', 'Installed on %@'),
'dev.installedNote': ('游戏已在设备上,可以直接打开。', 'The game is on the device, ready to open.'),
'dev.open': ('在 %@ 上打开', 'Open on %@'),
diff --git a/frontend/README.md b/frontend/README.md
index fc7d3709..34e91dfb 100644
--- a/frontend/README.md
+++ b/frontend/README.md
@@ -41,9 +41,13 @@ next to it. The script then prepares the game's Xcode project
(`--prepare-xcode --team-id`, the route it offers developers) instead of an IPA,
`xcodebuild -allowProvisioningUpdates` signs it for that device with the team
(Xcode makes the provisioning profile), and `xcrun devicectl device install app`
-installs it. The game files are inside the app, so there is no RomFS to copy;
-installing a large game takes a few minutes. The game then appears in the
-collection, and its button opens it on the device.
+installs it. The game files take the same route as for sideloading. They are packed into
+the RomFS archive, and the app is built without them (`DM_COPY_ROMFS=NO`). After the
+install, `xcrun devicectl device copy to` puts the archive into the app's
+`Documents/games/<title ID>/romfs`, where the app looks first. devicectl skips files
+that did not change, so a reinstall sends the code and shaders, not the whole game
+again. The first copy of a large game takes a few minutes. The game then appears
+in the collection, and its button opens it on the device.
The first time, turn on Developer Mode on the device and trust the developer
under Settings → General → VPN & Device Management. With a free Apple ID the
diff --git a/frontend/Sources/NSPortBuilder/ContentView.swift b/frontend/Sources/NSPortBuilder/ContentView.swift
index 2e970eac..ddaecbfa 100644
--- a/frontend/Sources/NSPortBuilder/ContentView.swift
+++ b/frontend/Sources/NSPortBuilder/ContentView.swift
@@ -123,8 +123,8 @@ final class BuildModel: ObservableObject {
// ---- Installing on an iPhone or iPad (Xcode with a development certificate) ----
// Optional: with a paired device and a signing team chosen, the script prepares the game's Xcode project
// (--prepare-xcode, the route its README gives developers), xcodebuild signs it for that device with the
- // team (Xcode makes the provisioning profile), and devicectl installs it. The game files are inside the app,
- // so no RomFS copy follows. Without a device or a team the build stays an unsigned IPA, as before.
+ // team (Xcode makes the provisioning profile) without the game files, devicectl installs it and copies the RomFS
+ // archive into its Documents, as a sideloaded copy has it. Without a device or a team the build stays an unsigned IPA, as before.
@Published var devices: [AppleDevice] = []
@Published var teams: [SigningTeam] = []
@Published var devicesChecked = false
@@ -791,7 +791,8 @@ final class BuildModel: ObservableObject {
self.running = false
self.cleanupStaging()
} else if self.installsDirectly {
- self.signAndInstall() // keeps running=true until the app is on the device
+ // The same archive as for sideloading, then the app without the game files, then the archive into its Documents
+ self.packArchive(workDir: self.effectiveWorkDir) { self.signAndInstall(archive: $0) }
} else {
self.packArchive(workDir: self.effectiveWorkDir) // keeps running=true until the archive is done
}
@@ -1042,7 +1043,8 @@ final class BuildModel: ObservableObject {
/// Pack the extracted RomFS into a ROMFSARC archive. The extracted folder is
/// <work>/extract/v<N>/RomFS where N is the profile's package version, so take
/// the highest v* that actually has a RomFS instead of hardcoding one game.
- private func packArchive(workDir: String) {
+ /// `then` continues the build with the archive's folder (installing on a device) instead of ending it.
+ private func packArchive(workDir: String, then: ((String) -> Void)? = nil) {
running = true
let fm = FileManager.default
let extract = workDir + "/extract"
@@ -1079,6 +1081,7 @@ final class BuildModel: ObservableObject {
stages.append(Stage(id: 1000, name: t("prog.archive"), state: .done,
detail: String(format: t("prog.archiveReused"), reused)))
say(String(format: t("msg.archiveReused"), dest))
+ if let then { return then(dest) }
cleanupStaging()
finishBuild(ok: true, note: t("msg.done"))
return
@@ -1110,7 +1113,6 @@ final class BuildModel: ObservableObject {
}
p.terminationHandler = { [weak self] st in Self.untrack(st); DispatchQueue.main.async {
guard let self else { return }
- self.cleanupStaging()
let cancelled = self.stopping
let succeeded = st.terminationStatus == 0 && !cancelled
self.stopping = false
@@ -1135,6 +1137,8 @@ final class BuildModel: ObservableObject {
? String(format: self.t("prog.archiveDone"), dest)
: String(format: self.t("msg.archiveFailed"), st.terminationStatus)
}
+ if succeeded, let then { return then(dest) }
+ self.cleanupStaging()
self.running = false
self.done = succeeded
if cancelled { self.resetProgress() }
@@ -1151,8 +1155,11 @@ final class BuildModel: ObservableObject {
// MARK: Installing on a device
- /// After the script prepared the Xcode project: sign it for the device, then install it there.
- private func signAndInstall() {
+ /// After the script prepared the Xcode project and the archive is packed: sign the app for the device without the
+ /// game files (DM_COPY_ROMFS=NO), install it, then copy the archive into its Documents/games/<title ID>/romfs, where
+ /// the app looks first (main.m), as a sideloaded copy has it. devicectl skips files that did not change, so a
+ /// reinstall sends the code and shaders, not the game again.
+ private func signAndInstall(archive: String) {
let work = effectiveWorkDir, project = work + "/xcode/DmIOS.xcodeproj", derived = work + "/xcode-derived-data"
let device = installDevice, team = signingTeam, name = deviceName(device), xcrun = xcrunPath
guard FileManager.default.fileExists(atPath: project) else { return finishInstall(String(format: t("dev.noProject"), shortPath(project))) }
@@ -1162,7 +1169,7 @@ final class BuildModel: ObservableObject {
guard let scheme else { return self.finishInstall(String(format: self.t("dev.noProject"), self.shortPath(project))) }
let sign = [xcrun, "xcodebuild", "-project", project, "-scheme", scheme, "-configuration", "Release",
"-destination", "id=\(device)", "-derivedDataPath", derived, "-allowProvisioningUpdates",
- "DEVELOPMENT_TEAM=\(team)", "build"]
+ "DEVELOPMENT_TEAM=\(team)", "DM_COPY_ROMFS=NO", "build"]
self.runTool(id: 1001, name: String(format: self.t("dev.signStage"), name), sign, step: Self.xcodeStep) { error in
if let error { return self.finishInstall(String(format: self.t("dev.signFailed"), error)) }
let app = derived + "/Build/Products/Release-iphoneos/DmIOS.app"
@@ -1170,9 +1177,17 @@ final class BuildModel: ObservableObject {
self.runTool(id: 1002, name: String(format: self.t("dev.installStage"), name),
[xcrun, "devicectl", "device", "install", "app", "--device", device, app], step: Self.installStep) { error in
if let error { return self.finishInstall(String(format: self.t("dev.installFailed"), error)) }
- self.installedOn = device
- self.installedAppPath = app
- self.finishInstall(nil)
+ guard let bundle = NSDictionary(contentsOfFile: app + "/Info.plist")?["CFBundleIdentifier"] as? String else {
+ return self.finishInstall(String(format: self.t("dev.noProject"), self.shortPath(app + "/Info.plist")))
+ }
+ let tid = Self.titleID(self.basePath).map { String(format: "%016llX", $0) } ?? "game"
+ self.runTool(id: 1003, name: String(format: self.t("dev.copyStage"), name),
+ Self.archiveCopy(xcrun: xcrun, device: device, bundle: bundle, archive: archive, titleID: tid), step: Self.installStep) { error in
+ if let error { return self.finishInstall(String(format: self.t("dev.copyFailed"), error)) }
+ self.installedOn = device
+ self.installedAppPath = app
+ self.finishInstall(nil)
+ }
}
}
}
@@ -1186,6 +1201,12 @@ final class BuildModel: ObservableObject {
cleanupStaging()
}
+ /// The archive into the installed app's Documents, where main.m looks for this game's files first.
+ nonisolated static func archiveCopy(xcrun: String, device: String, bundle: String, archive: String, titleID: String) -> [String] {
+ [xcrun, "devicectl", "device", "copy", "to", "--device", device, "--source", archive,
+ "--destination", "Documents/games/\(titleID)/romfs", "--domain-type", "appDataContainer", "--domain-identifier", bundle]
+ }
+
/// The scheme the script made for the game ("<name> (<profile>)"), from `xcodebuild -list`.
nonisolated static func scheme(of project: String, xcrun: String) -> String? {
let p = Process(), out = Pipe()
@@ -1204,7 +1225,7 @@ final class BuildModel: ObservableObject {
/// What xcodebuild is doing, from the actions it prints.
nonisolated static func xcodeStep(_ line: String) -> (detail: String, percent: Double?)? {
let actions = [("CompileC ", "compiling"), ("SwiftCompile ", "compiling"), ("Ld ", "linking"),
- ("PhaseScriptExecution ", "copying the game files"), ("CodeSign ", "signing"), ("ProcessProductPackaging ", "provisioning")]
+ ("PhaseScriptExecution ", "copying resources"), ("CodeSign ", "signing"), ("ProcessProductPackaging ", "provisioning")]
return actions.first { line.hasPrefix($0.0) }.map { ($0.1, nil) }
}
diff --git a/frontend/Sources/NSPortBuilder/Localization.swift b/frontend/Sources/NSPortBuilder/Localization.swift
index 2e03b257..2d1f4718 100644
--- a/frontend/Sources/NSPortBuilder/Localization.swift
+++ b/frontend/Sources/NSPortBuilder/Localization.swift
@@ -67,9 +67,11 @@ enum L10n {
"dev.refresh": ("\u{5237}\u{65b0}", "Refresh"),
"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 \u{4f1a}\u{4e3a}\u{8fd9}\u{53f0}\u{8bbe}\u{5907}\u{7b7e}\u{540d}\u{5e76}\u{76f4}\u{63a5}\u{5b89}\u{88c5}\u{ff0c}\u{6e38}\u{620f}\u{6587}\u{4ef6}\u{5df2}\u{5305}\u{542b}\u{5728} App \u{4e2d}\u{ff0c}\u{5b89}\u{88c5}\u{53ef}\u{80fd}\u{9700}\u{8981}\u{51e0}\u{5206}\u{949f}\u{3002}\u{7b2c}\u{4e00}\u{6b21}\u{9700}\u{8981}\u{5728}\u{8bbe}\u{5907}\u{4e0a}\u{5f00}\u{542f}\u{5f00}\u{53d1}\u{8005}\u{6a21}\u{5f0f}\u{ff0c}\u{5e76}\u{4fe1}\u{4efb}\u{5f00}\u{53d1}\u{8005}\u{ff08}\u{8bbe}\u{7f6e} \u{2192} \u{901a}\u{7528} \u{2192} VPN \u{4e0e}\u{8bbe}\u{5907}\u{7ba1}\u{7406}\u{ff09}\u{3002}", "Xcode signs the game for this device and installs it there, with the game files inside the app; installing can take a few minutes. The first time, turn on Developer Mode on the device and trust the developer (Settings \u{2192} General \u{2192} VPN & Device Management)."),
+ "dev.note": ("Xcode 会为这台设备签名并直接安装,游戏文件以 RomFS 归档复制到 App 的“文稿”中,与侧载相同;第一次复制大型游戏需要几分钟。第一次需要在设备上开启开发者模式,并信任开发者(设置 → 通用 → VPN 与设备管理)。", "Xcode signs the game for this device and installs it there, then copies the game files into the app’s Documents as the RomFS archive, 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)."),
"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 %@"),
+ "dev.copyFailed": ("复制游戏文件失败:%@", "Copying the game files failed: %@"),
"dev.installed": ("\u{5df2}\u{5b89}\u{88c5}\u{5230} %@", "Installed on %@"),
"dev.installedNote": ("\u{6e38}\u{620f}\u{5df2}\u{5728}\u{8bbe}\u{5907}\u{4e0a}\u{ff0c}\u{53ef}\u{4ee5}\u{76f4}\u{63a5}\u{6253}\u{5f00}\u{3002}", "The game is on the device, ready to open."),
"dev.open": ("\u{5728} %@ \u{4e0a}\u{6253}\u{5f00}", "Open on %@"),
diff --git a/frontend/Tests/NSPortBuilderTests/LibraryTests.swift b/frontend/Tests/NSPortBuilderTests/LibraryTests.swift
index 59b68e8c..df9516e8 100644
--- a/frontend/Tests/NSPortBuilderTests/LibraryTests.swift
+++ b/frontend/Tests/NSPortBuilderTests/LibraryTests.swift
@@ -290,8 +290,9 @@ final class LibraryTests: XCTestCase {
XCTAssertNil(DeviceTools.team(fromSubject: "subject=CN=Something"))
}
- /// An iPhone build with a device and a team: the script prepares the Xcode project, xcodebuild signs it for the
- /// device, devicectl installs it, and the library opens it there. The tools are stand-ins; nothing is signed.
+ /// An iPhone build with a device and a team: the script prepares the Xcode project, the RomFS archive is packed as for
+ /// sideloading, xcodebuild signs the app without the game files for the device, devicectl installs it and copies the
+ /// archive into its Documents, and the library opens it there. The tools are stand-ins; nothing is signed.
@MainActor func testBuildSignsAndInstallsOnTheChosenDevice() throws {
guard FileManager.default.isExecutableFile(atPath: "/usr/bin/python3") else { throw XCTSkip("System Python is required for the process fixture") }
let saved = ["repoPath", "buildTarget", "buildOutputDirectory", "installDevice", "signingTeam"].map { ($0, UserDefaults.standard.object(forKey: $0)) }
@@ -317,11 +318,19 @@ final class LibraryTests: XCTestCase {
open('\(calls.path)', 'a').write('script ' + ' '.join(sys.argv[1:]) + '\\n')
work = pathlib.Path(sys.argv[sys.argv.index('--work-dir') + 1])
(work / 'xcode/DmIOS.xcodeproj').mkdir(parents=True)
+ (work / 'extract/v0/RomFS').mkdir(parents=True); (work / 'extract/v0/RomFS/data.bin').write_bytes(b'game')
def ev(**e): print(json.dumps(e), flush=True)
ev(ev='stage', k=1, n=1, name='prepare Xcode')
ev(ev='say', msg='[12:00:00] app name: Test; version: 1.0; bundle ID: org.nxnative.test')
ev(ev='stage_end', k=1, name='prepare Xcode', ok=True, summary='', elapsed=1)
""".write(to: script, atomically: true, encoding: .utf8)
+ let packer = temporary.appendingPathComponent("dm/tools/romfs_arc.py") // stand-in: pack <RomFS> <base> writes <base>.idx and one shard
+ try FileManager.default.createDirectory(at: packer.deletingLastPathComponent(), withIntermediateDirectories: true)
+ try """
+ import sys
+ open('\(calls.path)', 'a').write('romfs_arc ' + ' '.join(sys.argv[1:]) + '\\n')
+ open(sys.argv[3] + '.idx', 'wb').write(b'idx'); open(sys.argv[3] + '.00', 'wb').write(b'game')
+ """.write(to: packer, atomically: true, encoding: .utf8)
let xcrun = temporary.appendingPathComponent("xcrun")
try """
#!/usr/bin/python3
@@ -337,6 +346,8 @@ final class LibraryTests: XCTestCase {
print('CodeSign ' + str(app), flush=True)
elif a[:3] == ['devicectl', 'device', 'install']:
print('45%', flush=True); print('App installed', flush=True)
+ elif a[:4] == ['devicectl', 'device', 'copy', 'to']:
+ print('60%', flush=True); print('Copied', flush=True)
""".write(to: xcrun, atomically: true, encoding: .utf8)
try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: xcrun.path)
model.xcrunPath = xcrun.path
@@ -354,12 +365,19 @@ final class LibraryTests: XCTestCase {
XCTAssertFalse(log[0].contains(" -o ")) // no IPA: the project goes to the device
let build = try XCTUnwrap(log.first { $0.hasPrefix("xcodebuild -project") })
for part in ["-scheme Test (0100535012974000)", "-destination id=00008150-AAAA", "-derivedDataPath \(work)/xcode-derived-data",
- "-allowProvisioningUpdates", "DEVELOPMENT_TEAM=TEAM123456"] { XCTAssertTrue(build.contains(part), part) }
+ "-allowProvisioningUpdates", "DEVELOPMENT_TEAM=TEAM123456", "DM_COPY_ROMFS=NO"] { XCTAssertTrue(build.contains(part), part) }
let app = work + "/xcode-derived-data/Build/Products/Release-iphoneos/DmIOS.app"
+ let archive = temporary.path + "/games/\(titleID)/romfs"
+ // the archive is packed before signing, the app installed before the archive goes into its Documents
+ let order = ["romfs_arc pack", "xcodebuild -project", "devicectl device install", "devicectl device copy"].map { step in log.firstIndex { $0.hasPrefix(step) } }
+ XCTAssertEqual(order.compactMap { $0 }, order.compactMap { $0 }.sorted())
+ XCTAssertEqual(order.compactMap { $0 }.count, 4)
XCTAssertTrue(log.contains("devicectl device install app --device 00008150-AAAA \(app)"))
+ XCTAssertTrue(log.contains("devicectl device copy to --device 00008150-AAAA --source \(archive) --destination Documents/games/\(titleID)/romfs --domain-type appDataContainer --domain-identifier org.nxnative.test"))
+ XCTAssertTrue(FileManager.default.fileExists(atPath: archive + "/romfs.idx"))
+ XCTAssertEqual(model.archivePath, archive)
XCTAssertEqual(model.installedOn, "00008150-AAAA")
- XCTAssertEqual(model.stages.filter { $0.id >= 1001 }.map(\.state), [.done, .done])
- XCTAssertFalse(model.stages.contains { $0.id == 1000 }) // no RomFS archive: the game files are in the app
+ XCTAssertEqual(model.stages.filter { $0.id >= 1000 }.map(\.state), [.done, .done, .done, .done])
let library = GameLibrary(file: temporary.appendingPathComponent("library.json"))
model.slots[0].paths = [base.path]
let id = try XCTUnwrap(library.rememberInputs(model))