Skip to content

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

Uninstaller: state, engine trees and the launcher's own checkout go; games and keys stay

LNPANDY71fc6f99b0ac
diff --git a/frontend-qt/nspb_qt/localization.py b/frontend-qt/nspb_qt/localization.py
index 662e33aa..d165aa0f 100644
--- a/frontend-qt/nspb_qt/localization.py
+++ b/frontend-qt/nspb_qt/localization.py
@@ -512,6 +512,12 @@ TABLE: dict[str, tuple[str, str, str, str]] = {
'update.pill': ('更新 v%@', 'Update v%@', 'Uppdatera v%@', 'Update v%@'),
'update.pillHelp': ('查看这个版本更新了什么,并下载。', 'See what changed in this release and download it.', 'Se vad den här versionen ändrar och hämta den.', 'Was diese Version ändert und sie laden.'),
'update.readOnlyHint': ('这个副本所在的位置无法自我更新。把 NX2Apple.app 移到「应用程序」文件夹后再更新。', 'This copy cannot update where it is. Move NX2Apple.app into Applications first.', 'Den här kopian kan inte uppdatera där den är. Flytta NX2Apple.app till Program-programmen först.', 'Diese Kopie kann sich nicht dort aktualisieren. Lege NX2Apple.app zuerst in Programme.'),
+ 'uninstall.title': ('卸载 NX2Apple', 'Uninstall NX2Apple', 'Avinstallera NX2Apple', 'NX2Apple deinstallieren'),
+ 'uninstall.note': ('删除设置、内置引擎副本与启动器自己克隆的仓库。游戏文件夹、存档和 prod.keys 保留,应用本体移到废纸篓。', 'Removes settings, the installed engine trees and the launcher’s own repository clone. Your games folder, saves and prod.keys stay; the app itself goes to the Trash.', 'Tar bort inställningar, installerade engine-träd och startarens egen klon av arkivet. Dina spelmappar, sparfiler och prod.keys stannar; själva appen läggs i papperskorgen.', 'Entfernt Einstellungen, installierte Engine-Bäume und den eigenen Klon des Archivs. Dein Spieleordner, Spielstände und prod.keys bleiben. Die App selbst kommt in den Papierkorb.'),
+ 'uninstall.button': ('卸载…', 'Uninstall…', 'Avinstallera…', 'Deinstallieren…'),
+ 'uninstall.confirm': ('输入 NX2Apple 确认卸载。这会删除设置与引擎副本,应用本体移到废纸篓。', 'Type NX2Apple to confirm. Settings and the engine trees are removed, and the app itself goes to the Trash.', 'Skriv NX2Apple för att bekräfta. Inställningar och engine-träd tas bort och själva appen läggs i papperskorgen.', 'Tippe NX2Apple zur Bestätigung. Einstellungen und Engine-Bäume werden entfernt, die App selbst kommt in den Papierkorb.'),
+ 'uninstall.done': ('已卸载 %ld 项。现在可以退出应用。', 'Removed %ld items. You can quit the app now.', 'Tog bort %ld poster. Du kan avsluta appen nu.', '%ld Einträge entfernt. Du kannst die App jetzt beenden.'),
+ 'uninstall.failed': ('有未能删除的项目:', 'Some items could not be removed:', 'Några poster kunde inte tas bort:', 'Einige Einträge konnten nicht entfernt werden:'),
'app.waitForBuild': ('构建进行中:更新会等构建结束', 'A build is running: the update waits until it is done', 'Ett bygge körs. Uppdateringen väntar tills det är klart.', 'Ein Build läuft: Das Update wartet, bis er fertig ist'),
'app.stageNetFail': ('%@ 下载失败(GitHub 不通?下次打开时再试)', 'Could not download %@ (GitHub unreachable? it tries again next launch)', 'Kunde inte hämta %@ (kan inte nå GitHub?). Ett nytt försök görs nästa gång appen startas.', '%@ konnte nicht geladen werden (GitHub nicht erreichbar? Beim nächsten Start wird es erneut versucht)'),
'app.noDigest': ('%@ 已发布,但 GitHub 没有提供校验值,所以不会自动安装——可以手动更新', '%@ is out, but GitHub gave no checksum for it, so it is not installed automatically — update by hand', '%@ finns, men GitHub gav ingen kontrollsumma. Den installeras därför inte automatiskt. Uppdatera manuellt.', '%@ ist da, aber GitHub hat keine Prüfsumme dafür geliefert, daher wird es nicht automatisch installiert. Aktualisiere von Hand'),
diff --git a/frontend/Sources/NSPortBuilder/ContentView.swift b/frontend/Sources/NSPortBuilder/ContentView.swift
index fd1447a3..ef59e468 100644
--- a/frontend/Sources/NSPortBuilder/ContentView.swift
+++ b/frontend/Sources/NSPortBuilder/ContentView.swift
@@ -628,6 +628,8 @@ final class BuildModel: ObservableObject {
/// updates, so a user learns what changed before deciding, not after downloading.
@Published var showUpdateSheet = false
@Published var showConvertSheet = false
+ /// The uninstall row's dialog: computed when the row is pressed, run when the phrase matches.
+ @Published var uninstallPlan: Uninstall.Plan?
@Published var appStatus = ""
/// Set when the last update attempt was refused (a release this macOS cannot open, a bad download); the update sheet shows it.
@Published var appUpdateBlocked: String?
@@ -3493,6 +3495,19 @@ struct BuilderView: View {
}
}
divider
+ if m.appInstallability == .ok {
+ // The uninstaller (Uninstall.swift): state folders and the launcher's own checkout go; the
+ // games folder and prod.keys stay; the app itself goes to the Trash. Typed confirmation.
+ row(m.t("uninstall.title"), detail: m.t("uninstall.note")) {
+ Button(m.t("uninstall.button")) {
+ m.uninstallPlan = Uninstall.plan(home: NSHomeDirectory(), gamesFolder: library.folder,
+ checkouts: [m.repoPath])
+ }
+ .disabled(m.running)
+ .padTarget("set.uninstall", scope: "main") { if !m.running { m.uninstallPlan = Uninstall.plan(home: NSHomeDirectory(), gamesFolder: library.folder, checkouts: [m.repoPath]) } }
+ }
+ divider
+ }
// A launcher built from the repository never replaces itself (AppUpdate.installability): the switch says so and stays off
row(m.t("app.auto"), detail: m.t(m.appInstallability == .ok ? "app.autoNote" : m.appInstallability == .developer ? "app.autoDev" : "app.autoReadOnly")) {
Toggle("", isOn: Binding(get: { m.autoUpdateApp && m.appInstallability == .ok }, set: { m.autoUpdateApp = $0 }))
diff --git a/frontend/Sources/NSPortBuilder/LauncherView.swift b/frontend/Sources/NSPortBuilder/LauncherView.swift
index cb4bd2ac..eed647cb 100644
--- a/frontend/Sources/NSPortBuilder/LauncherView.swift
+++ b/frontend/Sources/NSPortBuilder/LauncherView.swift
@@ -235,6 +235,22 @@ struct ContentView: View {
.onChange(of: freeSpaceFor) { id in padFocus.scope = id != nil ? "free" : currentPadScope }
.sheet(isPresented: $m.showUpdateSheet) { UpdateSheet(m: m) }
.sheet(isPresented: $m.showConvertSheet) { ConvertView(m: m) }
+ .typeToConfirm(
+ isPresented: Binding(get: { m.uninstallPlan != nil }, set: { if !$0 { m.uninstallPlan = nil } }),
+ phrase: "NX2Apple",
+ title: m.t("uninstall.title"),
+ message: m.t("uninstall.confirm"),
+ buttonTitle: m.t("uninstall.button")) {
+ if let plan = m.uninstallPlan {
+ let result = Uninstall.run(plan)
+ m.uninstallPlan = nil
+ if result.failures.isEmpty {
+ m.appStatus = String(format: m.t("uninstall.done"), result.removed.count)
+ } else {
+ m.appStatus = m.t("uninstall.failed") + "\n" + result.failures.joined(separator: "\n")
+ }
+ }
+ }
.sheet(isPresented: Binding(get: { savesFor != nil }, set: { if !$0 { savesFor = nil } })) {
if let id = savesFor { SavesView(m: m, library: library, gameID: id).environmentObject(padFocus) }
}
diff --git a/frontend/Sources/NSPortBuilder/Localization.swift b/frontend/Sources/NSPortBuilder/Localization.swift
index acbdfbfc..8332fcde 100644
--- a/frontend/Sources/NSPortBuilder/Localization.swift
+++ b/frontend/Sources/NSPortBuilder/Localization.swift
@@ -573,6 +573,12 @@ enum L10n {
"update.pill": ("更新 v%@", "Update v%@"),
"update.pillHelp": ("查看这个版本更新了什么,并下载。", "See what changed in this release and download it."),
"update.readOnlyHint": ("这个副本所在的位置无法自我更新。把 NX2Apple.app 移到「应用程序」文件夹后再更新。", "This copy cannot update where it is. Move NX2Apple.app into Applications first."),
+ "uninstall.title": ("卸载 NX2Apple", "Uninstall NX2Apple"),
+ "uninstall.note": ("删除设置、内置引擎副本与启动器自己克隆的仓库。游戏文件夹、存档和 prod.keys 保留,应用本体移到废纸篓。", "Removes settings, the installed engine trees and the launcher\u{2019}s own repository clone. Your games folder, saves and prod.keys stay; the app itself goes to the Trash."),
+ "uninstall.button": ("卸载…", "Uninstall…"),
+ "uninstall.confirm": ("输入 NX2Apple 确认卸载。这会删除设置与引擎副本,应用本体移到废纸篓。", "Type NX2Apple to confirm. Settings and the engine trees are removed, and the app itself goes to the Trash."),
+ "uninstall.done": ("已卸载 %ld 项。现在可以退出应用。", "Removed %ld items. You can quit the app now."),
+ "uninstall.failed": ("有未能删除的项目:", "Some items could not be removed:"),
"app.waitForBuild": ("构建进行中:更新会等构建结束", "A build is running: the update waits until it is done"),
"app.stageNetFail": ("%@ 下载失败(GitHub 不通?下次打开时再试)", "Could not download %@ (GitHub unreachable? it tries again next launch)"),
"app.noDigest": ("%@ 已发布,但 GitHub 没有提供校验值,所以不会自动安装——可以手动更新", "%@ is out, but GitHub gave no checksum for it, so it is not installed automatically — update by hand"),
@@ -1433,7 +1439,12 @@ enum L10n {
"app.staging": "Hämtar %@ i bakgrunden …",
"app.ready": "%@ är hämtad och verifierad. Den installeras när du avslutar eller när du väljer Starta om nu.",
"app.restartNow": "Starta om nu",
- "update.pill": "Uppdatera v%@",
+ "uninstall.title": "Avinstallera NX2Apple",
+ "uninstall.note": "Tar bort inställningar, installerade engine-träd och startarens egen klon av arkivet. Dina spelmappar, sparfiler och prod.keys stannar; själva appen läggs i papperskorgen.",
+ "uninstall.button": "Avinstallera…",
+ "uninstall.confirm": "Skriv NX2Apple för att bekräfta. Inställningar och engine-träd tas bort och själva appen läggs i papperskorgen.",
+ "uninstall.done": "Tog bort %ld poster. Du kan avsluta appen nu.",
+ "uninstall.failed": "Några poster kunde inte tas bort:", "update.pill": "Uppdatera v%@",
"update.pillHelp": "Se vad den här versionen ändrar och hämta den.",
"update.readOnlyHint": "Den här kopian kan inte uppdatera där den är. Flytta NX2Apple.app till Program-programmen först.",
"app.waitForBuild": "Ett bygge körs. Uppdateringen väntar tills det är klart.",
@@ -2301,7 +2312,12 @@ enum L10n {
"app.staging": "%@ wird im Hintergrund geladen …",
"app.ready": "%@ ist geladen und geprüft: Es wird beim Beenden installiert, oder klicke auf „Jetzt neu starten“",
"app.restartNow": "Jetzt neu starten",
- "update.pill": "Update v%@",
+ "uninstall.title": "NX2Apple deinstallieren",
+ "uninstall.note": "Entfernt Einstellungen, installierte Engine-Bäume und den eigenen Klon des Archivs. Dein Spieleordner, Spielstände und prod.keys bleiben. Die App selbst kommt in den Papierkorb.",
+ "uninstall.button": "Deinstallieren…",
+ "uninstall.confirm": "Tippe NX2Apple zur Bestätigung. Einstellungen und Engine-Bäume werden entfernt, die App selbst kommt in den Papierkorb.",
+ "uninstall.done": "%ld Einträge entfernt. Du kannst die App jetzt beenden.",
+ "uninstall.failed": "Einige Einträge konnten nicht entfernt werden:", "update.pill": "Update v%@",
"update.pillHelp": "Was diese Version ändert und sie laden.",
"update.readOnlyHint": "Diese Kopie kann sich nicht dort aktualisieren. Lege NX2Apple.app zuerst in Programme.",
"app.waitForBuild": "Ein Build läuft: Das Update wartet, bis er fertig ist",
diff --git a/frontend/Sources/NSPortBuilder/Uninstall.swift b/frontend/Sources/NSPortBuilder/Uninstall.swift
new file mode 100644
index 00000000..7f60d4db
--- /dev/null
+++ b/frontend/Sources/NSPortBuilder/Uninstall.swift
@@ -0,0 +1,73 @@
+import AppKit
+
+/// Uninstalling the launcher (NX Play's Uninstall): everything the app put outside its bundle, with the
+/// player's games and keys left alone. What goes:
+///
+/// - the state folder `~/Library/Application Support/NS Port Builder/` (settings, the venv, library file)
+/// - engine trees this launcher installed (`~/Library/Application Support/NX2Apple/engine/`)
+/// - the project checkout the launcher itself cloned (`~/NX2Apple`, only when it is the launcher's own
+/// download; a checkout the player made by hand is not touched)
+///
+/// What stays: the games folder and everything in it, `prod.keys`, Homebrew, and the app itself, which
+/// goes to the Trash when the player confirms — never deleted.
+enum Uninstall {
+ struct Plan: Equatable {
+ var stateFolders: [String] = []
+ var checkouts: [String] = []
+ /// Where the app lives now (goes to the Trash, not deleted).
+ var app: String = Bundle.main.bundlePath
+ }
+
+ /// The paths this install would remove, computed before anything is offered: the launcher's state
+ /// folders that exist, and a checkout that is the launcher's own download (the clone destination
+ /// `cloneRepo` uses) rather than one the player picked from anywhere on disk.
+ /// `home` is passed in (NSHomeDirectory() at the call site): a computed home is not testable.
+ nonisolated static func plan(home: String, gamesFolder: String, checkouts: [String]) -> Plan {
+ let fm = FileManager.default
+ var p = Plan()
+ let state = home + "/Library/Application Support/NS Port Builder"
+ if fm.fileExists(atPath: state) { p.stateFolders.append(state) }
+ let engine = home + "/Library/Application Support/NX2Apple"
+ if fm.fileExists(atPath: engine) { p.stateFolders.append(engine) }
+ let own = home + "/NX2Apple"
+ for checkout in checkouts where fm.fileExists(atPath: checkout) {
+ // The launcher's own clone sits at ~/NX2Apple and is a git checkout with origin = this repo.
+ // A folder the player picked from anywhere else stays: we cannot know what else lives there.
+ guard checkout == own else { continue }
+ if let origin = gitOrigin(checkout), origin.contains("LNPANDY/NX2Apple") { p.checkouts.append(checkout) }
+ }
+ return p
+ }
+
+ nonisolated static func gitOrigin(_ checkout: String) -> String? {
+ guard let git = BuildModel.gitBinary() else { return nil }
+ let r = BuildModel.runQuiet([git, "-C", checkout, "remote", "get-url", "origin"], env: BuildModel.gitEnv())
+ let url = r.out.trimmingCharacters(in: .whitespacesAndNewlines)
+ return r.ok && !url.isEmpty ? url : nil
+ }
+
+ /// Remove the plan's folders. The games folder and the app are never touched here. Returns what was
+ /// removed and what failed (in use, permissions), so the confirmation can say so honestly.
+ nonisolated static func run(_ plan: Plan, movingAppToTrash: Bool = true) -> (removed: [String], failures: [String]) {
+ let fm = FileManager.default
+ var removed: [String] = [], failures: [String] = []
+ for folder in plan.stateFolders + plan.checkouts {
+ do { try fm.removeItem(atPath: folder); removed.append(folder) }
+ catch { failures.append(folder + ": " + error.localizedDescription) }
+ }
+ if movingAppToTrash, plan.app.hasSuffix(".app"), plan.app.contains("/Applications/") {
+ if !fm.fileExists(atPath: plan.app) { failures.append(plan.app + ": not found") }
+ else if !trash(plan.app) { failures.append(plan.app + ": could not move to the Trash") }
+ }
+ return (removed, failures)
+ }
+
+ /// To the Trash, like the Finder's delete: recoverable, never `removeItem`.
+ nonisolated static func trash(_ path: String) -> Bool {
+ var url: NSURL?
+ do {
+ try FileManager.default.trashItem(at: URL(fileURLWithPath: path), resultingItemURL: &url)
+ return true
+ } catch { return false }
+ }
+}
diff --git a/frontend/Tests/NSPortBuilderTests/UninstallTests.swift b/frontend/Tests/NSPortBuilderTests/UninstallTests.swift
new file mode 100644
index 00000000..ca971c7d
--- /dev/null
+++ b/frontend/Tests/NSPortBuilderTests/UninstallTests.swift
@@ -0,0 +1,77 @@
+import XCTest
+@testable import NSPortBuilder
+
+/// The uninstall plan (Uninstall.swift): what goes, what stays. The removal runs in a temporary folder,
+/// so the real state and checkout are never touched.
+final class UninstallTests: XCTestCase {
+ private var home: URL!
+ private var games: URL!
+
+ override func setUpWithError() throws {
+ home = FileManager.default.temporaryDirectory.appendingPathComponent("uninstall-" + UUID().uuidString)
+ games = home.appendingPathComponent("Games")
+ guard let home, let games else { throw XCTSkip("temporary folder unavailable") }
+ for dir in [games, home.appendingPathComponent("Library/Application Support/NS Port Builder"),
+ home.appendingPathComponent("Library/Application Support/NX2Apple/engine/aaaaaaa"),
+ home.appendingPathComponent("NX2Apple")] {
+ try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
+ }
+ try Data("k".utf8).write(to: home.appendingPathComponent("prod.keys"))
+ try Data("save".utf8).write(to: games.appendingPathComponent("save.dat"))
+ setHome(home.path)
+ }
+
+ override func tearDownWithError() throws {
+ setHome(NSHomeDirectory())
+ try? FileManager.default.removeItem(at: home)
+ }
+
+ /// Uninstall computes from NSHomeDirectory: the tests point it at the temporary folder.
+ private func setHome(_ path: String) {
+ UserDefaults.standard.set(path, forKey: "NSGlobalDomain_home") // not read by the app; the env below is
+ setenv("HOME", path, 1)
+ }
+
+ private func originFixture(checkout: URL) throws {
+ let git = "/usr/bin/git"
+ _ = BuildModel.runQuiet([git, "-C", checkout.path, "init", "-b", "main"], env: BuildModel.gitEnv())
+ _ = BuildModel.runQuiet([git, "-C", checkout.path, "remote", "add", "origin", "https://github.com/LNPANDY/NX2Apple.git"], env: BuildModel.gitEnv())
+ }
+
+ func testThePlanTakesStateAndItsOwnCheckoutAndLeavesGamesAndKeys() throws {
+ let checkout = home.appendingPathComponent("NX2Apple").path
+ try originFixture(checkout: URL(fileURLWithPath: checkout))
+ let plan = Uninstall.plan(home: home.path, gamesFolder: games.path, checkouts: [checkout])
+ XCTAssertEqual(plan.stateFolders.contains(home.path + "/Library/Application Support/NS Port Builder"), true)
+ XCTAssertEqual(plan.stateFolders.contains(home.path + "/Library/Application Support/NX2Apple"), true)
+ XCTAssertEqual(plan.checkouts, [checkout])
+
+ let result = Uninstall.run(plan, movingAppToTrash: false)
+ XCTAssertTrue(result.failures.isEmpty, result.failures.joined(separator: "\n"))
+ XCTAssertTrue(FileManager.default.fileExists(atPath: games.appendingPathComponent("save.dat").path), "the games folder stays")
+ XCTAssertTrue(FileManager.default.fileExists(atPath: home.appendingPathComponent("prod.keys").path), "the keys stay")
+ XCTAssertFalse(FileManager.default.fileExists(atPath: checkout), "the launcher's own checkout goes")
+ }
+
+ /// A checkout the player picked from somewhere else is not removed: we cannot know what else it holds.
+ func testACheckoutFromAnotherFolderIsNotTouched() throws {
+ let picked = home.appendingPathComponent("Elsewhere/NX2Apple")
+ try FileManager.default.createDirectory(at: picked, withIntermediateDirectories: true)
+ try originFixture(checkout: picked)
+ let plan = Uninstall.plan(home: home.path, gamesFolder: games.path, checkouts: [picked.path])
+ XCTAssertTrue(plan.checkouts.isEmpty, "not the launcher's own ~/NX2Apple clone")
+ XCTAssertTrue(FileManager.default.fileExists(atPath: picked.path))
+ }
+
+ func testARepoWithoutOurOriginIsNotTouched() throws {
+ let checkout = home.appendingPathComponent("NX2Apple").path
+ let git = "/usr/bin/git"
+ _ = BuildModel.runQuiet([git, "-C", checkout, "remote", "add", "origin", "https://github.com/someone/else.git"], env: BuildModel.gitEnv())
+ let plan = Uninstall.plan(home: home.path, gamesFolder: games.path, checkouts: [checkout])
+ XCTAssertTrue(plan.checkouts.isEmpty, "a fork with another origin is the player's own work")
+ }
+
+ func testThePercentTextAndTrashAreHonestAboutFailures() {
+ XCTAssertFalse(Uninstall.trash("/nonexistent/" + UUID().uuidString), "a missing path reports failure")
+ }
+}