Skip to content

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

Launcher: never save the shell root at the root of a volume (#492)

LNPANDY30c2d2887464
diff --git a/frontend/Sources/NX2Apple/ContentView.swift b/frontend/Sources/NX2Apple/ContentView.swift
index 7726b355..6c161fc8 100644
--- a/frontend/Sources/NX2Apple/ContentView.swift
+++ b/frontend/Sources/NX2Apple/ContentView.swift
@@ -121,10 +121,7 @@ final class BuildModel: ObservableObject {
private var chainNoteShown = false // the shader-chain notice shows once per build
@Published var running = false
@Published var staleFrameworks: [StaleFrameworks.Entry] = [] // the prompt of StaleFrameworksPrompt.swift (#449)
- /// The shell folder the cache row shows: the frameworks' mirror, shell.json and the banner cache live here.
- var shellCachePath: String { shellRoot }
- /// The shell folder of the install and of the cache row: the saved one, else next to the output folder (or the game's folder).
- var shellRoot: String { ShellLibrary.resolveRoot(parent: outDir.isEmpty ? (basePath as NSString).deletingLastPathComponent : outDir) }
+ // The shell folder (shellCachePath, shellRoot): ShellRoot.swift.
@Published var stopping = false
@Published var logTail = ""
@Published var done = false
@@ -1312,6 +1309,9 @@ final class BuildModel: ObservableObject {
fail(failureWhat(failure!))
return
}
+ // The shared app's own folder is decided before the long steps too: one on a read-only volume (a saved
+ // /NX2Apple-shell, a DMG chosen as Save to) failed at the last step after the whole build (#492).
+ if target != BuildTarget.mac, let why = shellRootProblem() { fail(why); return }
var inputDir = baseDir
if dirs.count > 1 || !unpicked.isEmpty {
// A stable folder per game (#132): the script's fingerprints name its files and its profile path.
diff --git a/frontend/Sources/NX2Apple/ShellInstall.swift b/frontend/Sources/NX2Apple/ShellInstall.swift
index 7ac83d5d..43eaf8b3 100644
--- a/frontend/Sources/NX2Apple/ShellInstall.swift
+++ b/frontend/Sources/NX2Apple/ShellInstall.swift
@@ -52,11 +52,31 @@ struct ShellLibrary: Codable, Equatable {
try encoder.encode(self).write(to: URL(fileURLWithPath: Self.stateFile(root: root)), options: .atomic)
}
+ /// The folder a shell root may live in: an absolute path that is not the root of a volume. `""` (no game or output
+ /// folder chosen yet) and `/` both gave `/NX2Apple-shell` on the read-only system volume (#492); `home` stands in.
+ static func parentFolder(_ parent: String, home: String = NSHomeDirectory()) -> String {
+ let path = (parent as NSString).expandingTildeInPath
+ return path.hasPrefix("/") && path != "/" ? path : home
+ }
+
+ /// Whether a saved root can be used as it is: an absolute path below a volume root. `/NX2Apple-shell` came from an
+ /// empty parent and is repaired instead of used (#492).
+ static func rootIsUsable(_ root: String) -> Bool {
+ root.hasPrefix("/") && (root as NSString).pathComponents.filter { $0 != "/" }.count >= 2
+ }
+
+ /// The root the next install would use, without saving it. The Settings page shows it before any game is chosen,
+ /// and that look must not decide where builds save (#492).
+ static func previewRoot(defaults: UserDefaults = .standard, parent: String, home: String = NSHomeDirectory()) -> String {
+ if let saved = defaults.string(forKey: "shellRoot"), rootIsUsable(saved) { return saved }
+ return parentFolder(parent, home: home) + "/NX2Apple-shell"
+ }
+
/// The shell root: the saved one (`shellRoot` in `defaults`), else `<parent>/NX2Apple-shell`, which is then saved so the shell
- /// stays where it was first made, whatever output folder a later build uses.
- static func resolveRoot(defaults: UserDefaults = .standard, parent: String) -> String {
- if let saved = defaults.string(forKey: "shellRoot"), !saved.isEmpty { return saved }
- let root = parent + "/NX2Apple-shell"
+ /// stays where it was first made, whatever output folder a later build uses. A saved root at a volume root is repaired.
+ static func resolveRoot(defaults: UserDefaults = .standard, parent: String, home: String = NSHomeDirectory()) -> String {
+ if let saved = defaults.string(forKey: "shellRoot"), rootIsUsable(saved) { return saved }
+ let root = parentFolder(parent, home: home) + "/NX2Apple-shell"
defaults.set(root, forKey: "shellRoot")
return root
}
@@ -69,6 +89,17 @@ enum ShellInstall {
static let projectName = "DmShell.xcodeproj"
static func projectFolder(root: String) -> String { root + "/project" }
+
+ /// Whether the shell root can be written, checked before an hour of building: a folder on a read-only volume (or a
+ /// file where the folder goes) only failed at the last step otherwise (#492).
+ static func canWriteRoot(_ root: String, fm: FileManager = .default) -> Bool {
+ var isDir: ObjCBool = false
+ if fm.fileExists(atPath: root, isDirectory: &isDir) { return isDir.boolValue && fm.isWritableFile(atPath: root) }
+ let parent = (root as NSString).deletingLastPathComponent
+ guard fm.fileExists(atPath: parent, isDirectory: &isDir), isDir.boolValue else { return false }
+ return fm.isWritableFile(atPath: parent)
+ }
+
static func derivedData(root: String) -> String { root + "/derived-data" }
static func appPath(root: String) -> String { derivedData(root: root) + "/Build/Products/Release-iphoneos/" + appName }
diff --git a/frontend/Sources/NX2Apple/ShellRoot.swift b/frontend/Sources/NX2Apple/ShellRoot.swift
new file mode 100644
index 00000000..e68f33ab
--- /dev/null
+++ b/frontend/Sources/NX2Apple/ShellRoot.swift
@@ -0,0 +1,21 @@
+import Foundation
+
+// Where the shared app's folder lives (#492). The Settings row shows it before a game or output folder is chosen, so a
+// look only previews the root; a build saves it. An empty parent, "/" or a relative one would have put it at
+// /NX2Apple-shell, the root of the read-only system volume, where the write failed after the whole build; a saved value
+// like that is repaired. A build also checks the folder before its long steps, not at the end.
+
+extension BuildModel {
+ /// The shell folder the cache row shows: the frameworks' mirror, shell.json and the banner cache live here.
+ var shellCachePath: String { ShellLibrary.previewRoot(parent: shellRootParent) }
+ /// The folder a first shell root would sit in: the output folder, else the game's folder.
+ var shellRootParent: String { outDir.isEmpty ? (basePath as NSString).deletingLastPathComponent : outDir }
+ /// The shell folder of the install: the saved one, else next to the output folder (or the game's folder).
+ var shellRoot: String { ShellLibrary.resolveRoot(parent: shellRootParent) }
+
+ /// Why the shell folder cannot be written (`nil`: it can), before an hour of building rather than at the last step.
+ func shellRootProblem() -> String? {
+ let root = shellRoot
+ return ShellInstall.canWriteRoot(root) ? nil : String(format: t("shell.rootUnwritable"), shortPath(root))
+ }
+}
diff --git a/frontend/Sources/NXCore/Localization.swift b/frontend/Sources/NXCore/Localization.swift
index 25ed7a4e..db491d3f 100644
--- a/frontend/Sources/NXCore/Localization.swift
+++ b/frontend/Sources/NXCore/Localization.swift
@@ -269,6 +269,7 @@ package enum L10n {
"shell.noSpace": ("%@ 上空间不足:游戏数据需要 %.1f GB,设备只剩 %.1f GB。请先释放空间再安装", "Not enough space on %@: the game data needs %.1f GB and the device has %.1f GB free. Free up space, then install again"),
"shell.noFramework": ("没有找到游戏的框架:%@", "The game's framework was not found: %@"),
"shell.needsDevice": ("共用应用需要一台设备和一个签名团队。请先在“安装到”里选择。", "The shared app needs a device and a signing team. Choose them under Install on first."),
+ "shell.rootUnwritable": ("共用应用要保存在 %@,但那里无法写入(只读卷或没有权限)。请先在“保存到”里换一个目录。", "The shared app is saved to %@, and that folder cannot be written (a read-only volume or no permission). Choose another folder under Save to first."),
"shell.copySize": ("要复制的游戏数据:%@,共 %d 个文件。", "Game data to copy: %@ in %d files."),
"shell.copyWired": ("复制完成前请保持 %@ 解锁。", "Keep %@ unlocked until the copy finishes."),
"shell.copyWifi": ("已通过 Wi-Fi 连接:复制 %@ 大约需要 %d 到 %d 分钟。用数据线会更快。", "Connected over Wi-Fi: copying %@ takes about %d to %d minutes. A cable is faster."),
@@ -300,10 +301,8 @@ package enum L10n {
"dev.noDevices": ("\u{6ca1}\u{6709}\u{4e0e}\u{8fd9}\u{53f0} Mac \u{914d}\u{5bf9}\u{7684} iPhone \u{6216} iPad\u{ff08}\u{9700}\u{8981} Xcode\u{ff09}\u{3002}", "No iPhone or iPad paired with this Mac (needs Xcode)."),
"dev.refresh": ("\u{5237}\u{65b0}", "Refresh"),
"dev.team": ("\u{7b7e}\u{540d}\u{56e2}\u{961f}", "Signing team"),
- "dev.noTeam": ("Xcode 里没有 Apple ID,也没有开发证书。打开 Xcode → Settings → Apple Accounts(Xcode 菜单没有中文),登录 Apple ID 后选 Personal Team → Download Manual Profiles。证书不会立刻出现——等 30 秒左右再按「重新检测」。如果等了还没有,在 Manage Certificates 里点 + 手动创建一个 Apple Development 证书。",
- "No Apple ID in Xcode and no development certificate. Open Xcode → Settings → Apple Accounts (Xcode menus are English-only), sign in with your Apple ID, select Personal Team → Download Manual Profiles. The certificate does not appear immediately — wait ~30 seconds and press Check again. If it still does not appear, click + in Manage Certificates to create an Apple Development certificate manually."),
- "dev.teamNoCert": ("这个团队还没有开发证书:第一次安装时 Xcode 会自动创建(Mac 需要联网)。",
- "This team has no development certificate yet: Xcode creates it at the first install (the Mac needs to be online)."),
+ "dev.noTeam": ("Xcode 里没有 Apple ID,也没有开发证书。打开 Xcode → Settings → Apple Accounts(Xcode 菜单没有中文),登录 Apple ID 后选 Personal Team → Download Manual Profiles。证书不会立刻出现——等 30 秒左右再按「重新检测」。如果等了还没有,在 Manage Certificates 里点 + 手动创建一个 Apple Development 证书。", "No Apple ID in Xcode and no development certificate. Open Xcode → Settings → Apple Accounts (Xcode menus are English-only), sign in with your Apple ID, select Personal Team → Download Manual Profiles. The certificate does not appear immediately — wait ~30 seconds and press Check again. If it still does not appear, click + in Manage Certificates to create an Apple Development certificate manually."),
+ "dev.teamNoCert": ("这个团队还没有开发证书:第一次安装时 Xcode 会自动创建(Mac 需要联网)。", "This team has no development certificate yet: Xcode creates it at the first install (the Mac needs to be online)."),
"dev.personalTeam": ("个人团队", "Personal team"),
"dev.note": ("Xcode 会为这台设备签名共用应用并安装,然后把游戏数据(romfs.img)复制到应用的“文稿”中。第一次复制大型游戏需要几分钟。第一次需要在设备上开启开发者模式,并信任开发者(设置 → 通用 → VPN 与设备管理)。", "Xcode signs the shared app for this device and installs it there, then copies the game data (romfs.img) into the app’s Documents. 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) ----
@@ -570,8 +569,7 @@ package enum L10n {
"repo.title": ("项目仓库", "Project repository"),
"repo.note": ("App 调用这里的构建脚本", "the app runs the build scripts from here"),
"repo.choose": ("选择仓库…", "Choose repository…"),
- "repo.notFound": ("未找到本项目——下载,或点右侧选择 clone 的位置",
- "Project not found — download it, or pick your clone with the button"),
+ "repo.notFound": ("未找到本项目——下载,或点右侧选择 clone 的位置", "Project not found — download it, or pick your clone with the button"),
"repo.notRepo": ("不是本项目的仓库:%@", "Not this project's repository: %@"),
"repo.pickMessage": ("选择本项目(含 dm/tools/nx_extract/Program.cs)的文件夹",
"Pick this project's folder (the one holding dm/tools/nx_extract/Program.cs)"),
@@ -579,8 +577,7 @@ package enum L10n {
"repo.downloading": ("正在下载到 ~/nxnative…(进度见下方日志,约一分钟)",
"Downloading to ~/nxnative… (progress in the log below, about a minute)"),
"repo.downloadDone": ("仓库已下载到 %@", "Repository downloaded to %@"),
- "repo.downloadFail": ("下载失败——网络不顺?用下面的手动方法",
- "Download failed — flaky network? Use the manual route below"),
+ "repo.downloadFail": ("下载失败——网络不顺?用下面的手动方法", "Download failed — flaky network? Use the manual route below"),
"repo.manualHint": ("网络不顺也可以手动:打开", "Flaky network? Do it by hand: open"),
"repo.manualHint2": ("→ 点绿色 Code 按钮 → Download ZIP,解压后点「选择仓库…」选中解压出的文件夹",
"→ the green Code button → Download ZIP, unzip, then pick the unzipped folder with Choose repository…"),
@@ -1368,6 +1365,7 @@ package enum L10n {
"shell.noSpace": "Inte tillräckligt med utrymme på %@: speldatan behöver %.1f GB och enheten har %.1f GB ledigt. Frigör utrymme och installera igen",
"shell.noFramework": "Spelets ramverk hittades inte: %@",
"shell.needsDevice": "Den gemensamma appen behöver en enhet och ett signeringsteam. Välj dem först under Installera på.",
+ "shell.rootUnwritable": "Den gemensamma appen sparas i %@, och mappen går inte att skriva i (skrivskyddad volym eller ingen behörighet). Välj en annan mapp under Spara till först.",
"shell.copySize": "Speldata att kopiera: %@ i %d filer.",
"shell.copyWired": "Låt %@ vara olåst tills kopieringen är klar.",
"shell.copyWifi": "Ansluten via Wi-Fi: att kopiera %@ tar ungefär %d till %d minuter. En kabel går fortare.",
@@ -3085,6 +3083,7 @@ package enum L10n {
"shell.noSpace": "Nicht genug Platz auf %@: Die Spieldaten brauchen %.1f GB und auf dem Gerät sind %.1f GB frei. Gib Speicher frei und installiere dann erneut",
"shell.noFramework": "Das Framework des Spiels wurde nicht gefunden: %@",
"shell.needsDevice": "Die gemeinsame App braucht ein Gerät und ein Signier-Team. Wähle sie zuerst unter Installieren auf.",
+ "shell.rootUnwritable": "Die gemeinsame App wird in %@ gespeichert, und dieser Ordner ist nicht beschreibbar (schreibgeschütztes Volume oder keine Berechtigung). Wähle zuerst unter Speichern unter einen anderen Ordner.",
"shell.copySize": "Zu kopierende Spieldaten: %@ in %d Dateien.",
"shell.copyWired": "Lass %@ entsperrt, bis das Kopieren fertig ist.",
"shell.copyWifi": "Über WLAN verbunden: %@ zu kopieren dauert etwa %d bis %d Minuten. Mit Kabel geht es schneller.",
@@ -4144,6 +4143,7 @@ package enum L10n {
"shell.noSpace": "Pas assez d’espace sur %@\u{a0}: les données du jeu demandent %.1f\u{a0}Go et l’appareil en a %.1f\u{a0}Go de libres. Libérez de l’espace, puis réinstallez",
"shell.noFramework": "Le framework du jeu est introuvable\u{a0}: %@",
"shell.needsDevice": "L’app partagée a besoin d’un appareil et d’une équipe de signature. Choisissez-les d’abord sous Installer sur.",
+ "shell.rootUnwritable": "L’app partagée est enregistrée dans %@, et ce dossier n’est pas accessible en écriture (volume en lecture seule ou autorisation manquante). Choisissez d’abord un autre dossier sous Enregistrer dans.",
"shell.copySize": "Données du jeu à copier\u{a0}: %@ dans %d fichiers.",
"shell.copyWired": "Gardez %@ déverrouillé jusqu’à la fin de la copie.",
"shell.copyWifi": "Connecté en Wi-Fi\u{a0}: la copie de %@ prend environ %d à %d minutes. Un câble est plus rapide.",
diff --git a/frontend/Tests/NX2AppleTests/ShellInstallTests.swift b/frontend/Tests/NX2AppleTests/ShellInstallTests.swift
index 5c156e96..34480a7b 100644
--- a/frontend/Tests/NX2AppleTests/ShellInstallTests.swift
+++ b/frontend/Tests/NX2AppleTests/ShellInstallTests.swift
@@ -63,6 +63,46 @@ final class ShellInstallTests: XCTestCase {
XCTAssertEqual(ShellLibrary.resolveRoot(defaults: defaults, parent: "/Volumes/B"), "/Volumes/A/NX2Apple-shell")
}
+ /// #492: the Settings page reads the path before a game is chosen; the empty parent put the shell at the root of the
+ /// read-only system volume, where the write failed after the whole build.
+ func testAnEmptyOrRootParentNeverSavesTheShellAtTheVolumeRoot() {
+ let defaults = UserDefaults(suiteName: "nspb-shell-" + UUID().uuidString)!
+ let home = "/Users/tester"
+ XCTAssertEqual(ShellLibrary.resolveRoot(defaults: defaults, parent: "", home: home), "/Users/tester/NX2Apple-shell")
+ XCTAssertEqual(defaults.string(forKey: "shellRoot"), "/Users/tester/NX2Apple-shell")
+ defaults.removeObject(forKey: "shellRoot")
+ XCTAssertEqual(ShellLibrary.resolveRoot(defaults: defaults, parent: "/", home: home), "/Users/tester/NX2Apple-shell")
+ defaults.removeObject(forKey: "shellRoot")
+ XCTAssertEqual(ShellLibrary.resolveRoot(defaults: defaults, parent: "relative/games", home: home), "/Users/tester/NX2Apple-shell")
+ }
+
+ func testASavedRootAtTheVolumeRootIsRepaired() {
+ let defaults = UserDefaults(suiteName: "nspb-shell-" + UUID().uuidString)!
+ defaults.set("/NX2Apple-shell", forKey: "shellRoot")
+ XCTAssertEqual(ShellLibrary.resolveRoot(defaults: defaults, parent: "/Users/tester/games"),
+ "/Users/tester/games/NX2Apple-shell")
+ XCTAssertEqual(defaults.string(forKey: "shellRoot"), "/Users/tester/games/NX2Apple-shell") // the bad value is replaced
+ }
+
+ func testThePreviewDoesNotSaveARoot() {
+ let defaults = UserDefaults(suiteName: "nspb-shell-" + UUID().uuidString)!
+ XCTAssertEqual(ShellLibrary.previewRoot(defaults: defaults, parent: "/Volumes/A"), "/Volumes/A/NX2Apple-shell")
+ XCTAssertNil(defaults.string(forKey: "shellRoot"))
+ defaults.set("/Volumes/A/NX2Apple-shell", forKey: "shellRoot")
+ XCTAssertEqual(ShellLibrary.previewRoot(defaults: defaults, parent: "/Volumes/B"), "/Volumes/A/NX2Apple-shell")
+ }
+
+ func testRootNeedsAWritableParent() throws {
+ let parent = NSTemporaryDirectory() + "nspb-shell-parent-" + UUID().uuidString
+ try FileManager.default.createDirectory(atPath: parent, withIntermediateDirectories: true)
+ defer { try? FileManager.default.removeItem(atPath: parent) }
+ XCTAssertTrue(ShellInstall.canWriteRoot(parent + "/NX2Apple-shell"))
+ XCTAssertFalse(ShellInstall.canWriteRoot(NSTemporaryDirectory() + "nspb-missing-" + UUID().uuidString + "/NX2Apple-shell"))
+ try FileManager.default.setAttributes([.posixPermissions: 0o555], ofItemAtPath: parent)
+ defer { try? FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: parent) }
+ XCTAssertFalse(ShellInstall.canWriteRoot(parent + "/NX2Apple-shell"))
+ }
+
// ---- the commands ----
// ---- the iOS shell package (DM_SHELL_PACKAGE) ----