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
Restart now: open the new copy from a helper once the old process has exited
v0lumehied797e16befb
diff --git a/frontend-qt/nspb_qt/localization.py b/frontend-qt/nspb_qt/localization.pyindex f34caa9a..4813e214 100644--- a/frontend-qt/nspb_qt/localization.py+++ b/frontend-qt/nspb_qt/localization.py@@ -512,6 +512,7 @@ TABLE: dict[str, tuple[str, str, str, str]] = {'update.openPage': ('打开发布页', 'Open the release page', 'Öppna releasesidan', 'Release-Seite öffnen'),'app.installing': ('正在安装…(旧版本会进废纸篓)', 'Installing… (the old version goes to the Trash)', 'Installerar … Den gamla versionen flyttas till papperskorgen.', 'Wird installiert … (die alte Version kommt in den Papierkorb)'),'app.relaunching': ('已更新到 %@,正在重启 App…', 'Updated to %@ — restarting…', 'Uppdaterad till %@. Startar om …', 'Auf %@ aktualisiert. Neustart …'),+ 'app.relaunchFail': ('已更新到 %@,但无法自动重启,请手动重新打开 App', 'Updated to %@, but it could not restart. Open the app again by hand.', 'Uppdaterad till %@, men appen kunde inte startas om. Öppna den igen manuellt.', 'Auf %@ aktualisiert, aber der Neustart ging nicht. Öffne die App bitte selbst noch einmal.'),'app.installFail': ('安装失败:%@——新版本已下载,可手动替换', 'Install failed: %@ — the new version was downloaded, so replace it by hand', 'Installationen misslyckades: %@. Den nya versionen hämtades, ersätt manuellt.', 'Installation fehlgeschlagen: %@. Die neue Version wurde geladen, ersetze sie von Hand'),'app.netFail': ('网络失败(GitHub 不通?稍后再试)', 'Network failed (GitHub unreachable? try again later)', 'Nätverksfel (kan inte nå GitHub?). Försök igen senare.', 'Netzwerkfehler (GitHub nicht erreichbar? Versuche es später erneut)'),'repo.destBusy': ('%@ 已存在且不是本项目——换个位置,或点「选择仓库…」', '%@ already exists and is not this project — use another place, or Choose repository…', '%@ finns redan och är inte projektet. Välj en annan plats eller använd ”Välj förråd …”.', '%@ existiert bereits und ist nicht dieses Projekt. Nutze einen anderen Ort oder „Repository wählen …“'),diff --git a/frontend/Sources/NSPortBuilder/AppUpdate.swift b/frontend/Sources/NSPortBuilder/AppUpdate.swiftindex ce917d00..1666ebf5 100644--- a/frontend/Sources/NSPortBuilder/AppUpdate.swift+++ b/frontend/Sources/NSPortBuilder/AppUpdate.swift@@ -206,6 +206,31 @@ enum AppUpdate {}}+ /// The shell script behind `relaunch`: wait until `$1` (a pid) has exited, at most `$3` ticks of 0.2 s,+ /// then open `$2` with `$4`. The paths arrive as arguments, never spliced into the script, so spaces and+ /// quotes in them are safe.+ static let relaunchScript = """+ n=0+ while kill -0 "$1" 2>/dev/null && [ "$n" -lt "$3" ]; do sleep 0.2; n=$((n+1)); done+ sleep 0.5+ exec "$4" "$2"+ """++ /// Start the new copy once this one is gone. `NSWorkspace.openApplication` cannot do it while the old+ /// instance runs: LaunchServices finds the same bundle id and only activates that instance. So a detached+ /// shell waits for the pid to exit, then runs `open`. The caller terminates the app right after.+ @discardableResult+ static func relaunch(_ app: URL, afterExitOf pid: Int32 = ProcessInfo.processInfo.processIdentifier,+ timeout: TimeInterval = 30, opener: String = "/usr/bin/open") -> Bool {+ let p = Process()+ p.executableURL = URL(fileURLWithPath: "/bin/sh")+ p.arguments = ["-c", relaunchScript, "sh", String(pid), app.path, String(Int(timeout / 0.2)), opener]+ p.standardInput = FileHandle.nullDevice+ p.standardOutput = FileHandle.nullDevice+ p.standardError = FileHandle.nullDevice+ do { try p.run(); return true } catch { return false }+ }+private static func clearQuarantine(_ app: URL) {let x = Process()x.executableURL = URL(fileURLWithPath: "/usr/bin/xattr")diff --git a/frontend/Sources/NSPortBuilder/ContentView.swift b/frontend/Sources/NSPortBuilder/ContentView.swiftindex dbd473bd..6f3cd9b3 100644--- a/frontend/Sources/NSPortBuilder/ContentView.swift+++ b/frontend/Sources/NSPortBuilder/ContentView.swift@@ -866,8 +866,14 @@ final class BuildModel: ObservableObject {}if relaunch {appStatus = String(format: t("app.relaunching"), staged.release.tag)- NSWorkspace.shared.openApplication(at: placed, configuration: NSWorkspace.OpenConfiguration())- DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) { exit(0) }+ // The old instance is still running, so opening the same bundle now would only activate it:+ // a helper opens the new copy once this process has exited.+ if AppUpdate.relaunch(placed) {+ NSApp.terminate(nil)+ DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) { exit(0) }+ } else {+ appStatus = String(format: t("app.relaunchFail"), staged.release.tag)+ }}return true}diff --git a/frontend/Sources/NSPortBuilder/Localization.swift b/frontend/Sources/NSPortBuilder/Localization.swiftindex d2fa2248..9d5f8a99 100644--- a/frontend/Sources/NSPortBuilder/Localization.swift+++ b/frontend/Sources/NSPortBuilder/Localization.swift@@ -573,6 +573,7 @@ enum L10n {"update.openPage": ("打开发布页", "Open the release page"),"app.installing": ("正在安装…(旧版本会进废纸篓)", "Installing… (the old version goes to the Trash)"),"app.relaunching": ("已更新到 %@,正在重启 App…", "Updated to %@ — restarting…"),+ "app.relaunchFail": ("已更新到 %@,但无法自动重启,请手动重新打开 App", "Updated to %@, but it could not restart. Open the app again by hand."),"app.installFail": ("安装失败:%@——新版本已下载,可手动替换", "Install failed: %@ — the new version was downloaded, so replace it by hand"),"app.netFail": ("网络失败(GitHub 不通?稍后再试)", "Network failed (GitHub unreachable? try again later)"),"repo.destBusy": ("%@ 已存在且不是本项目——换个位置,或点「选择仓库…」",@@ -1423,6 +1424,7 @@ enum L10n {"update.openPage": "Öppna releasesidan","app.installing": "Installerar … Den gamla versionen flyttas till papperskorgen.","app.relaunching": "Uppdaterad till %@. Startar om …",+ "app.relaunchFail": "Uppdaterad till %@, men appen kunde inte startas om. Öppna den igen manuellt.","app.installFail": "Installationen misslyckades: %@. Den nya versionen hämtades, ersätt manuellt.","app.netFail": "Nätverksfel (kan inte nå GitHub?). Försök igen senare.","repo.update": "Kontrollera och uppdatera",@@ -2269,6 +2271,7 @@ enum L10n {"update.openPage": "Release-Seite öffnen","app.installing": "Wird installiert … (die alte Version kommt in den Papierkorb)","app.relaunching": "Auf %@ aktualisiert. Neustart …",+ "app.relaunchFail": "Auf %@ aktualisiert, aber der Neustart ging nicht. Öffne die App bitte selbst noch einmal.","app.installFail": "Installation fehlgeschlagen: %@. Die neue Version wurde geladen, ersetze sie von Hand","app.netFail": "Netzwerkfehler (GitHub nicht erreichbar? Versuche es später erneut)","repo.destBusy": "%@ existiert bereits und ist nicht dieses Projekt. Nutze einen anderen Ort oder „Repository wählen …“",diff --git a/frontend/Tests/NSPortBuilderTests/AppUpdateTests.swift b/frontend/Tests/NSPortBuilderTests/AppUpdateTests.swiftindex a63adc8c..f67c7312 100644--- a/frontend/Tests/NSPortBuilderTests/AppUpdateTests.swift+++ b/frontend/Tests/NSPortBuilderTests/AppUpdateTests.swift@@ -294,13 +294,70 @@ final class AppUpdateTests: XCTestCase {func testEveryUpdateStringHasBothLanguages() {for key in ["app.staging", "app.ready", "app.restartNow", "app.waitForBuild", "app.stageNetFail", "app.noDigest","app.digestMismatch", "app.unpackFail", "app.notOurApp", "app.devBuild", "app.readOnly", "app.auto",- "app.autoNote", "app.autoDev", "app.autoReadOnly", "library.appReady"] {+ "app.autoNote", "app.autoDev", "app.autoReadOnly", "library.appReady", "app.relaunchFail"] {XCTAssertNotNil(L10n.table[key], key)}XCTAssertTrue(L10n.selfCheck().isEmpty)}}+/// Restart now: a detached shell waits for the old process to exit, then opens the new copy.+final class RelaunchTests: XCTestCase {+ private var dir: URL!++ override func setUpWithError() throws {+ dir = FileManager.default.temporaryDirectory.appendingPathComponent("nxnative-relaunch-tests-" + UUID().uuidString)+ try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)+ }++ override func tearDownWithError() throws {+ try FileManager.default.removeItem(at: dir)+ }++ /// An opener that records its argument instead of launching anything.+ private func fakeOpener(into log: URL) throws -> String {+ let script = dir.appendingPathComponent("fake open.sh")+ try "#!/bin/sh\nprintf '%s' \"$1\" > \"\(log.path)\"\n".write(to: script, atomically: true, encoding: .utf8)+ try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: script.path)+ return script.path+ }++ private func wait(for url: URL, seconds: TimeInterval) -> String? {+ let end = Date().addingTimeInterval(seconds)+ while Date() < end {+ if let text = try? String(contentsOf: url, encoding: .utf8) { return text }+ Thread.sleep(forTimeInterval: 0.05)+ }+ return nil+ }++ func testTheNewCopyOpensOnlyAfterTheOldProcessHasExited() throws {+ let log = dir.appendingPathComponent("opened.txt")+ let app = dir.appendingPathComponent("My Games & \"Apps\"/NX2Apple.app")+ let old = Process()+ old.executableURL = URL(fileURLWithPath: "/bin/sleep")+ old.arguments = ["1.5"]+ try old.run()+ XCTAssertTrue(AppUpdate.relaunch(app, afterExitOf: old.processIdentifier, opener: try fakeOpener(into: log)))+ Thread.sleep(forTimeInterval: 0.8)+ XCTAssertFalse(FileManager.default.fileExists(atPath: log.path), "the old process is still running")+ old.waitUntilExit()+ XCTAssertEqual(wait(for: log, seconds: 5), app.path, "a path with spaces, an ampersand and quotes arrives whole")+ }++ func testItOpensAnywayWhenTheOldProcessDoesNotExit() throws {+ let log = dir.appendingPathComponent("opened.txt")+ let app = dir.appendingPathComponent("NX2Apple.app")+ let old = Process()+ old.executableURL = URL(fileURLWithPath: "/bin/sleep")+ old.arguments = ["30"]+ try old.run()+ defer { old.terminate() }+ XCTAssertTrue(AppUpdate.relaunch(app, afterExitOf: old.processIdentifier, timeout: 1, opener: try fakeOpener(into: log)))+ XCTAssertEqual(wait(for: log, seconds: 5), app.path, "the wait ends at the timeout")+ }+}+private extension Result {var failure: Failure? { if case .failure(let f) = self { return f }; return nil }}