Skip to content

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

Merge PR #62 by hand: the launcher installs its own updates, and keeps the sheet

LNPANDYb50cef128df2
diff --cc frontend/Sources/NSPortBuilder/AppUpdate.swift
index da2e72ec,00000000..07634fd1
mode 100644,000000..100644
--- a/frontend/Sources/NSPortBuilder/AppUpdate.swift
+++ b/frontend/Sources/NSPortBuilder/AppUpdate.swift
@@@ -1,149 -1,0 +1,152 @@@
+import Foundation
+import CryptoKit
+
+// The launcher's self-update, the parts that decide what may be installed and when. BuildModel drives it
+// (checkAppUpdate, stageAppUpdate, installStagedUpdate); everything here works on paths it is given, so the
+// tests run it on bundles in a temporary folder, never on the running app or the network.
+//
+// The rules:
+// - What is installed is what GitHub says the release is: the zip's SHA-256 matches the asset's `digest`
+// ("sha256:<hex>", in the release API since 2025), and the app inside it carries the running app's bundle
+// identifier, an executable and the release's version. An automatic install also needs the digest to be
+// there; the Update button, pressed by hand, still installs a release without one (older releases have none).
+// - Only a released copy replaces itself: a launcher built from the repository (swift run, a bundle assembled in
+// frontend/, an Xcode build) keeps the developer's build in place.
+// - Never while a build runs: the swap ends with a relaunch (exit), and a build is a process group of the app's.
+
+enum AppUpdate {
+ /// The latest release, as the check found it.
+ struct Release: Equatable {
+ let tag: String
+ let url: String
+ let digest: String? // "sha256:<hex>"; nil when the API gave none
++ /// The release body, shown by the update sheet before anything is downloaded: "a new version
++ /// is out" alone told a user nothing about what they would get.
++ var notes: String = ""
+ }
+
+ /// A release downloaded, verified and unpacked, waiting to be swapped in.
+ struct Staged: Equatable {
+ let release: Release
+ let app: URL
+ }
+
+ // ---- What was downloaded ----
+
+ enum DigestCheck: Equatable { case match, mismatch, missing }
+
+ /// The SHA-256 of a file, as lowercase hex, read in pieces (the zip is tens of megabytes).
+ static func sha256(of file: URL) -> String? {
+ guard let handle = try? FileHandle(forReadingFrom: file) else { return nil }
+ defer { try? handle.close() }
+ var hasher = SHA256()
+ while true {
+ let chunk = handle.readData(ofLength: 1 << 20)
+ if chunk.isEmpty { break }
+ hasher.update(data: chunk)
+ }
+ return hasher.finalize().map { String(format: "%02x", $0) }.joined()
+ }
+
+ /// The file against the asset's digest. A digest in any other algorithm, or none, counts as missing: there is
+ /// nothing to compare with, which an automatic install refuses.
+ static func checkDigest(_ file: URL, expected: String?) -> DigestCheck {
+ guard let expected, expected.lowercased().hasPrefix("sha256:") else { return .missing }
+ let want = expected.dropFirst("sha256:".count).trimmingCharacters(in: .whitespaces).lowercased()
+ guard want.count == 64, let have = sha256(of: file) else { return want.isEmpty ? .missing : .mismatch }
+ return have == want ? .match : .mismatch
+ }
+
+ enum BundleProblem: Error, Equatable { case noInfo, wrongIdentifier, noExecutable, wrongVersion }
+
+ /// Whether `app` is an NX2Apple launcher of the release `tag`: the running app's bundle identifier (a zip of
+ /// something else must not take its place), an executable where its Info.plist says, and the release's version
+ /// (the release workflow writes the tag into the plist; another number would be a different build).
+ static func bundleProblem(_ app: URL, expectedID: String, tag: String) -> BundleProblem? {
+ let contents = app.appendingPathComponent("Contents")
+ guard let data = try? Data(contentsOf: contents.appendingPathComponent("Info.plist")),
+ let info = try? PropertyListSerialization.propertyList(from: data, format: nil) as? [String: Any]
+ else { return .noInfo }
+ guard !expectedID.isEmpty, info["CFBundleIdentifier"] as? String == expectedID else { return .wrongIdentifier }
+ guard let exe = info["CFBundleExecutable"] as? String, !exe.isEmpty, !exe.contains("/"),
+ FileManager.default.isExecutableFile(atPath: contents.appendingPathComponent("MacOS/" + exe).path)
+ else { return .noExecutable }
+ let version = tag.hasPrefix("v") ? String(tag.dropFirst()) : tag
+ guard info["CFBundleShortVersionString"] as? String == version else { return .wrongVersion }
+ return nil
+ }
+
+ // ---- What may replace itself ----
+
+ enum Installability: Equatable {
+ case ok
+ case developer // built from the repository: never replaces itself
+ case readOnly // a released copy that cannot be replaced where it is (translocated, or a folder without write access)
+ }
+
+ /// Whether the launcher at `bundle` may replace itself. A released copy is an `.app` whose Info.plist has a bundle
+ /// identifier and, as its version, this binary's own release number (the release workflow stops when the two
+ /// differ), and which is not where a developer's build sits: in SwiftPM's .build, Xcode's DerivedData, or beside
+ /// the Package.swift it was built from (frontend/NX2Apple.app, which the README's own recipe makes). `swift run`
+ /// runs a bare executable with no bundle at all.
+ static func installability(_ bundle: URL, appVersion: String) -> Installability {
+ let path = bundle.standardizedFileURL.path
+ guard bundle.pathExtension == "app" else { return .developer }
+ let parts = bundle.standardizedFileURL.pathComponents
+ if parts.contains(".build") || parts.contains("DerivedData") { return .developer }
+ let parent = bundle.standardizedFileURL.deletingLastPathComponent()
+ if FileManager.default.fileExists(atPath: parent.appendingPathComponent("Package.swift").path) { return .developer }
+ guard isReleaseVersion(appVersion),
+ let data = try? Data(contentsOf: bundle.appendingPathComponent("Contents/Info.plist")),
+ let info = try? PropertyListSerialization.propertyList(from: data, format: nil) as? [String: Any],
+ let id = info["CFBundleIdentifier"] as? String, !id.isEmpty,
+ info["CFBundleShortVersionString"] as? String == appVersion
+ else { return .developer }
+ // Gatekeeper runs a quarantined app opened from Downloads from a read-only copy: the swap cannot reach the real one
+ if path.contains("/AppTranslocation/") { return .readOnly }
+ if !FileManager.default.isWritableFile(atPath: parent.path) { return .readOnly }
+ return .ok
+ }
+
+ /// "1.2.3": digits and dots, nothing else (a dev build might say "dev", "0.0.0-local" or nothing).
+ static func isReleaseVersion(_ v: String) -> Bool {
+ let parts = v.split(separator: ".", omittingEmptySubsequences: false)
+ return parts.count >= 2 && parts.allSatisfy { !$0.isEmpty && $0.allSatisfy(\.isASCII) && $0.allSatisfy(\.isNumber) }
+ }
+
+ // ---- When ----
+
+ enum InstallError: Error, Equatable { case buildRunning, failed(String) }
+
+ /// Swap `staged` in at `current`: copied in beside it first (from there on every step stays on one volume), then
+ /// exchanged with it in one replace, so a failure anywhere leaves a working app at `current`. The old bundle goes
+ /// to the Trash (`trashOld`; the tests remove it instead), and the new one loses the quarantine flag, so its first
+ /// launch shows no Gatekeeper prompt (the release is ad-hoc signed, not notarized).
+ ///
+ /// Refused while a build runs: the caller relaunches (or the app is quitting), and either ends the build's process group.
+ static func install(_ staged: URL, over current: URL, buildRunning: Bool, trashOld: Bool = true) throws {
+ guard !buildRunning else { throw InstallError.buildRunning }
+ let fm = FileManager.default
+ let dir = current.deletingLastPathComponent()
+ let name = current.deletingPathExtension().lastPathComponent
+ let incoming = dir.appendingPathComponent(name + " (new).app")
+ let backupName = name + " (old).app"
+ try? fm.removeItem(at: incoming)
+ try? fm.removeItem(at: dir.appendingPathComponent(backupName))
+ do {
+ try fm.copyItem(at: staged, to: incoming)
+ let placed = try fm.replaceItemAt(current, withItemAt: incoming, backupItemName: backupName, options: [.withoutDeletingBackupItem])
+ let backup = dir.appendingPathComponent(backupName)
+ if fm.fileExists(atPath: backup.path) {
+ if trashOld { try? fm.trashItem(at: backup, resultingItemURL: nil) } else { try? fm.removeItem(at: backup) }
+ }
+ let x = Process()
+ x.executableURL = URL(fileURLWithPath: "/usr/bin/xattr")
+ x.arguments = ["-dr", "com.apple.quarantine", (placed ?? current).path]
+ try? x.run(); x.waitUntilExit()
+ } catch {
+ try? fm.removeItem(at: incoming)
+ throw InstallError.failed(error.localizedDescription)
+ }
+ }
+}
diff --cc frontend/Sources/NSPortBuilder/ContentView.swift
index 5d43310b,aa7b7270..48fa702e
--- a/frontend/Sources/NSPortBuilder/ContentView.swift
+++ b/frontend/Sources/NSPortBuilder/ContentView.swift
@@@ -438,27 -472,25 +478,39 @@@ final class BuildModel: ObservableObjec
}
// ---- App self-update (GitHub Releases) ----
+ // The rules (what is verified, which copies replace themselves, never during a build) are in AppUpdate.swift.
/// Bump together with each release tag; the update check compares it with the latest release.
- static let appVersion = "0.4.7"
+ static let appVersion = "0.4.8"
- /// The update found by checkAppUpdate: its tag, the asset to download, and the release notes the
- /// sheet shows. The notes are why the sheet exists — "update available" alone told a user nothing
- /// about what they would get (the 0.4.x releases each changed a lot).
- @Published var appUpdate: (tag: String, url: String, notes: String)?
++ /// The update checkAppUpdate found: the tag, the asset to download, its digest, and the release
++ /// notes the sheet shows. The notes are why the sheet exists — "update available" alone told a
++ /// user nothing about what they would get.
+ @Published var appUpdate: AppUpdate.Release?
@Published var appBusy = false
+ /// Whether the "a new version is out" sheet is up: opened by the launch check and by Check for
+ /// updates, so a user learns what changed before deciding, not after downloading.
+ @Published var showUpdateSheet = false
@Published var appStatus = ""
+ /// Download a new release by itself and install it when the app quits (Settings; on by default). Off, the
+ /// Update button in Settings works as before: download, swap in, relaunch.
+ @Published var autoUpdateApp = UserDefaults.standard.object(forKey: "autoUpdateApp") as? Bool ?? true {
+ didSet {
+ UserDefaults.standard.set(autoUpdateApp, forKey: "autoUpdateApp")
+ if autoUpdateApp, appStaged == nil, let u = appUpdate { stageAppUpdate(u, automatic: true) }
+ }
+ }
+ /// The release that is downloaded, verified and unpacked: it goes in when the app quits, or with Restart now.
+ @Published var appStaged: AppUpdate.Staged?
+ /// Whether this copy may replace itself; a launcher built from the repository never does (tests set it).
+ var appInstallability = AppUpdate.installability(Bundle.main.bundleURL, appVersion: BuildModel.appVersion)
+ private var quitObserver: NSObjectProtocol?
+ /// The download names this build accepts, newest first. Every release must carry at least one of
+ /// them or an install from that era cannot update itself: NX2Apple is current, nxnative is for
+ /// installs from before the rename to NX2Apple, NS-Port-Builder for installs before that.
+ nonisolated static let appAssetNames = ["NX2Apple-macOS-arm64.zip", "nxnative-macOS-arm64.zip",
+ "NS-Port-Builder-macOS-arm64.zip"]
+
nonisolated static func isNewer(_ tag: String, than current: String) -> Bool {
func nums(_ s: String) -> [Int] { s.split(separator: ".").map { Int($0.filter { $0.isNumber }) ?? 0 } }
let a = nums(tag), b = nums(current)
@@@ -490,25 -508,43 +542,49 @@@
appBusy = true
if !silent { appStatus = t("app.checking") }
URLSession.shared.dataTask(with: URL(string: "https://api.github.com/repos/LNPANDY/NX2Apple/releases/latest")!) { data, _, _ in
- var found: (String, String, String)?
+ var found: AppUpdate.Release?
- if let d = data, let obj = try? JSONSerialization.jsonObject(with: d) as? [String: Any],
- let r = Self.appRelease(fromJSON: obj), Self.isNewer(r.tag, than: Self.appVersion) {
- found = r
+ // A newer release whose download this build cannot name is NOT "up to date". That
+ // distinction is the difference between a user who updates and one who sits on 0.4.6
+ // for ever: 0.4.6 and 0.4.7 look for exactly "NS-Port-Builder-macOS-arm64.zip", and if a
- // release ever ships without that name they report "已是最新" and stop. Keep the name and
- // report the mismatch honestly.
++ // release ever ships without that name they report "已是最新" and stop.
+ var newerTag: String?
+ if let d = data, let obj = try? JSONSerialization.jsonObject(with: d) as? [String: Any] {
+ let tag = obj["tag_name"] as? String ?? ""
+ if Self.isNewer(tag, than: Self.appVersion) {
+ newerTag = tag
- if let assets = obj["assets"] as? [[String: Any]] {
- let notes = (obj["body"] as? String) ?? ""
- for name in Self.appAssetNames where found == nil {
- for a in assets where (a["name"] as? String) == name {
- if let u = a["browser_download_url"] as? String { found = (tag, u, notes) }
- }
- }
++ if var r = Self.appRelease(fromJSON: obj) {
++ r.notes = (obj["body"] as? String) ?? ""
++ found = r
+ }
+ }
}
DispatchQueue.main.async {
self.appBusy = false
if let f = found {
- self.appUpdate = (tag: f.0, url: f.1, notes: f.2)
- self.appStatus = String(format: self.t("app.found"), f.0)
- self.showUpdateSheet = true // the sheet names what the new version does
+ self.appUpdate = f
+ switch self.appInstallability {
+ case .developer: self.appStatus = String(format: self.t("app.devBuild"), f.tag)
+ case .readOnly: self.appStatus = String(format: self.t("app.readOnly"), f.tag)
+ case .ok:
+ if self.appStaged?.release == f { self.appStatus = String(format: self.t("app.ready"), f.tag) }
+ else if self.autoUpdateApp { self.stageAppUpdate(f, automatic: true) }
+ else { self.appStatus = String(format: self.t("app.found"), f.tag) }
++ // The sheet opens either way: it is the only place the release notes appear,
++ // and "a new version is out" without saying what changed is what made people
++ // press Update blindly or not at all. In automatic mode it is also where
++ // Restart now lives, and it says the download is already running.
++ self.showUpdateSheet = true
+ }
} else if !silent {
- self.appStatus = data == nil ? self.t("app.netFail") : self.t("app.upToDate")
+ if data == nil {
+ self.appStatus = self.t("app.netFail")
+ } else if let tag = newerTag {
+ // The release exists; this app just cannot find its own asset name in it.
+ self.appStatus = String(format: self.t("app.noAsset"), tag)
+ self.appUpdate = nil
+ } else {
+ self.appStatus = self.t("app.upToDate")
+ }
}
}
}.resume()
diff --cc frontend/Sources/NSPortBuilder/LauncherView.swift
index fbe15ee1,75569649..3fcd6c63
--- a/frontend/Sources/NSPortBuilder/LauncherView.swift
+++ b/frontend/Sources/NSPortBuilder/LauncherView.swift
@@@ -455,16 -463,12 +463,21 @@@ struct ContentView: View
} else {
Image(systemName: "desktopcomputer").foregroundStyle(.secondary)
Text(m.t("library.localNote")).font(.manrope(13)).foregroundStyle(.secondary)
+ if let n = m.autoPulled, n > 0 {
+ // The automatic update when the app opened (BuildModel.autoPull): the build tools are the current ones
+ Circle().fill(LauncherPalette.ready).frame(width: 6, height: 6).padding(.leading, 10)
+ Text(String(format: m.t("library.toolsUpdated"), n)).font(.manrope(13)).foregroundStyle(.secondary)
+ }
Spacer()
+ if let staged = m.appStaged {
+ // A downloaded, verified update (BuildModel.stageAppUpdate): it goes in when the app quits, or now.
+ // This branch only shows with no build running, and restartToUpdate checks again.
+ HStack(spacing: 10) {
+ Circle().fill(LauncherPalette.ready).frame(width: 6, height: 6)
+ Text(String(format: m.t("library.appReady"), staged.release.tag)).font(.manrope(13)).foregroundStyle(.secondary)
+ }
+ Button(m.t("app.restartNow")) { m.restartToUpdate() }.buttonStyle(LauncherSecondaryButtonStyle())
+ }
if gamepad.connected {
// The buttons a controller has here, named as the game names them (A on the right)
HStack(spacing: 18) {
diff --cc frontend/Sources/NSPortBuilder/Localization.swift
index 57b1f77d,163da946..f4323d17
--- a/frontend/Sources/NSPortBuilder/Localization.swift
+++ b/frontend/Sources/NSPortBuilder/Localization.swift
@@@ -188,24 -188,15 +188,31 @@@ enum L10n
"app.checking": ("正在检查 App 更新…", "Checking for a new app version…"),
"app.upToDate": ("App 已是最新版本", "The app is up to date"),
"app.found": ("App 有新版本 %@,点右上角按钮更新", "A new version %@ is out — update from the top-right button"),
+ "app.noAsset": ("发现新版本 %@,但这个版本找不到对应的安装包——请到发布页手动下载", "Version %@ is out, but this build cannot find its own download in it — get it from the release page"),
"app.updateBtn": ("更新到 %@", "Update to %@"),
+ "app.downloading": ("正在下载 %@…", "Downloading %@…"),
+ "app.staging": ("正在后台下载 %@…", "Downloading %@ in the background…"),
+ "app.ready": ("%@ 已下载并校验:退出 App 时安装,或点「立即重启」", "%@ is downloaded and verified: it installs when you quit, or Restart now"),
+ "app.restartNow": ("立即重启", "Restart now"),
+ "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"),
+ "app.digestMismatch": ("%@ 的下载与校验值不符,已丢弃", "The download of %@ did not match its checksum and was discarded"),
+ "app.unpackFail": ("%@ 的下载无法解压,已丢弃", "The download of %@ could not be unpacked and was discarded"),
+ "app.notOurApp": ("%@ 的下载不是 NX2Apple,已丢弃", "The download of %@ is not an NX2Apple app and was discarded"),
+ "app.devBuild": ("%@ 已发布。这个启动器是从仓库构建的,不会替换自己", "%@ is out. This launcher was built from the repository and does not replace itself"),
+ "app.readOnly": ("%@ 已发布,但 App 无法在当前位置替换自己——请把它移到「应用程序」文件夹", "%@ is out, but the app cannot replace itself where it is — move it to Applications"),
+ "app.auto": ("自动安装更新", "Install updates automatically"),
+ "app.autoNote": ("在后台下载并校验,退出 App 时安装;构建进行中绝不安装", "Downloaded and verified in the background, installed when you quit; never during a build"),
+ "app.autoDev": ("从仓库构建的启动器不会自动更新", "Not for a launcher built from the repository"),
+ "app.autoReadOnly": ("App 所在的文件夹不可写,无法自动更新", "The app's folder is not writable, so it cannot update itself"),
+ "library.appReady": ("NX2Apple %@ 已就绪", "NX2Apple %@ is ready"),
+ "update.title": ("有新版本可用", "A new version is out"),
+ "update.fromTo": ("当前 %@ → 新版本 %@", "You have %@ — the new version is %@"),
+ "update.noNotes": ("这一版没有写更新说明,可以打开发布页查看。", "This release has no notes; open the release page to see it."),
+ "update.now": ("现在更新", "Update now"),
+ "update.later": ("稍后", "Later"),
+ "update.openPage": ("打开发布页", "Open the release page"),
- "app.downloading": ("正在下载新版本…", "Downloading the new version…"),
"app.installing": ("正在安装…(旧版本会进废纸篓)", "Installing… (the old version goes to the Trash)"),
"app.relaunching": ("已更新到 %@,正在重启 App…", "Updated to %@ — restarting…"),
"app.installFail": ("安装失败:%@——新版本已下载,可手动替换", "Install failed: %@ — the new version was downloaded; replace by hand"),
diff --cc frontend/Sources/NSPortBuilder/UpdateSheet.swift
index 00000000,efc7ad9e..719be73c
mode 000000,100644..100644
--- a/frontend/Sources/NSPortBuilder/UpdateSheet.swift
+++ b/frontend/Sources/NSPortBuilder/UpdateSheet.swift
@@@ -1,0 -1,144 +1,147 @@@
+ import SwiftUI
+
+ /// "A new version is out", with what it changes, shown when the app opens or Check for updates finds
+ /// one. The app already had the update machinery (checkAppUpdate / performAppUpdate); what it lacked
+ /// was a reason to press the button: the status line said a tag name and nothing else, and a user who
+ /// was working fine had no way to tell whether the new version mattered to them.
+ ///
+ /// The notes come from the release body, which this project writes in both languages (see
+ /// docs/RELEASE-NOTES-GUIDE.md). The sheet does not try to translate them; it shows the lines that
+ /// match the interface language and falls back to the whole body when it cannot tell them apart.
+ struct UpdateSheet: View {
+ @ObservedObject var m: BuildModel
+ @Environment(\.dismiss) private var dismiss
+
- private var update: (tag: String, url: String, notes: String)? { m.appUpdate }
++ private var update: AppUpdate.Release? { m.appUpdate }
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 0) {
+ VStack(alignment: .leading, spacing: 6) {
+ Text(m.t("update.title"))
+ .font(.manrope(24, .heavy)).tracking(-0.5)
+ Text(String(format: m.t("update.fromTo"), BuildModel.appVersion, update?.tag ?? ""))
+ .font(.manrope(13)).foregroundStyle(.secondary)
+ }
+ .padding(.horizontal, 28).padding(.top, 26).padding(.bottom, 18)
+
+ ScrollView {
+ VStack(alignment: .leading, spacing: 10) {
+ if let notes = update?.notes, !notes.isEmpty {
+ ForEach(Array(Self.lines(notes, for: m.lang).enumerated()), id: \.offset) { _, line in
+ Text(line)
+ .font(.manrope(13))
+ .fixedSize(horizontal: false, vertical: true)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ }
+ } else {
+ Text(m.t("update.noNotes")).font(.manrope(13)).foregroundStyle(.secondary)
+ }
+ }
+ .padding(.horizontal, 28).padding(.bottom, 20)
+ }
+ .frame(maxHeight: 340)
+
+ Divider().opacity(0.3)
+ HStack(spacing: 12) {
+ if let u = update {
+ Link(m.t("update.openPage"), destination: URL(string: "https://github.com/LNPANDY/NX2Apple/releases/tag/\(u.tag)")!)
+ .font(.manrope(12.5))
+ }
+ Spacer(minLength: 8)
+ Button(m.t("update.later")) { dismiss() }
+ .buttonStyle(LauncherSecondaryButtonStyle())
+ .keyboardShortcut(.cancelAction)
+ Button {
- m.performAppUpdate()
++ // Automatic mode has already downloaded and staged the release, so the action is
++ // to swap it in now; otherwise this downloads, verifies and installs as before.
++ if m.appStaged != nil { m.installStagedUpdate(relaunch: true) } else { m.performAppUpdate() }
+ dismiss()
+ } label: {
- Text(m.t("update.now")).font(.manrope(13.5, .bold)).foregroundStyle(.black)
++ Text(m.t(m.appStaged != nil ? "app.restartNow" : "update.now"))
++ .font(.manrope(13.5, .bold)).foregroundStyle(.black)
+ .padding(.horizontal, 20).padding(.vertical, 9)
+ .background(LauncherPalette.cream, in: Capsule())
+ }
+ .buttonStyle(.plain)
+ .disabled(m.appBusy)
+ .keyboardShortcut(.defaultAction)
+ }
+ .padding(.horizontal, 28).padding(.vertical, 16)
+ }
+ .frame(width: 560)
+ .background(LauncherPalette.background)
+ .preferredColorScheme(.dark)
+ .tint(LauncherPalette.cream)
+ }
+
+ /// The release body's lines for one language.
+ ///
+ /// Two shapes are in the wild, both described in docs/RELEASE-NOTES-GUIDE.md:
+ ///
+ /// * **Current**: English written out in full, `---`, then Chinese in full. The `---` is the
+ /// split, so the two halves are read straight through and neither reader sees the other's text.
+ /// * **Older releases (0.4.7 and before)**: `**中文** …` and `**English** …` paragraphs with the
+ /// bullet lists interleaved one line each. Those are split on the markers.
+ ///
+ /// A body with neither is shown whole — splitting it by guesswork is how the first version gave
+ /// an English reader the Chinese paragraph (that line contains both scripts).
+ static func lines(_ notes: String, for lang: Lang) -> [String] {
+ // Shape 1: two halves around a `---` line.
+ let halves = notes.components(separatedBy: "\n---\n")
+ if halves.count == 2 {
+ let first = clean(halves[0]), second = clean(halves[1])
+ // The English half first, as the guide requires; pick by which half is which, not by order
+ // alone, so a body written the other way round still reads correctly.
+ let firstIsEnglish = !containsHan(first.joined())
+ let english = firstIsEnglish ? first : second
+ let chinese = firstIsEnglish ? second : first
+ if !english.isEmpty && !chinese.isEmpty { return lang == .zh ? chinese : english }
+ }
+
+ // Shape 2: `**中文**` / `**English**` markers.
+ var zh: [String] = [], en: [String] = []
+ var marked = 0
+ for raw in notes.split(separator: "\n", omittingEmptySubsequences: false) {
+ var s = raw.trimmingCharacters(in: .whitespaces)
+ if s.isEmpty || s.hasPrefix("---") { continue }
+ if s.hasPrefix("#") {
+ while s.hasPrefix("#") { s.removeFirst() }
+ s = s.trimmingCharacters(in: .whitespaces)
+ if !s.isEmpty { zh.append(s); en.append(s) }
+ continue
+ }
+ if let r = s.range(of: "**中文**") {
+ marked += 1
+ zh.append(s[r.upperBound...].replacingOccurrences(of: "**", with: "").trimmingCharacters(in: .whitespaces))
+ } else if let r = s.range(of: "**English**") {
+ marked += 1
+ en.append(s[r.upperBound...].replacingOccurrences(of: "**", with: "").trimmingCharacters(in: .whitespaces))
+ } else {
+ s = s.replacingOccurrences(of: "**", with: "")
+ if containsHan(s) { zh.append(s) } else { en.append(s) }
+ }
+ }
+ if marked > 0, !zh.isEmpty, !en.isEmpty { return lang == .zh ? zh : en }
+
+ // Neither shape: show it as it is.
+ return clean(notes)
+ }
+
+ /// One half of a body as display lines: heading marks and bold marks stripped, blanks dropped.
+ private static func clean(_ half: String) -> [String] {
+ half.split(separator: "\n", omittingEmptySubsequences: false).compactMap { raw in
+ var s = raw.trimmingCharacters(in: .whitespaces)
+ if s.isEmpty || s.hasPrefix("---") { return nil }
+ while s.hasPrefix("#") { s.removeFirst() }
+ s = s.replacingOccurrences(of: "**中文**", with: "")
+ .replacingOccurrences(of: "**English**", with: "")
+ .replacingOccurrences(of: "**", with: "")
+ .trimmingCharacters(in: .whitespaces)
+ return s.isEmpty ? nil : s
+ }
+ }
+
+ private static func containsHan(_ s: String) -> Bool {
+ s.unicodeScalars.contains { (0x4e00...0x9fff).contains($0.value) }
+ }
+ }
diff --cc frontend/Tests/NSPortBuilderTests/AppUpdateTests.swift
index b008a4c3,26ec04f1..0c9adb46
--- a/frontend/Tests/NSPortBuilderTests/AppUpdateTests.swift
+++ b/frontend/Tests/NSPortBuilderTests/AppUpdateTests.swift
@@@ -1,226 -1,28 +1,252 @@@
import XCTest
+import CryptoKit
@testable import NSPortBuilder
+/// The self-update's rules on bundles in a temporary folder: never the running app, never the network.
+final class AppUpdateTests: XCTestCase {
+ private var temporary: URL!
+ private let bundleID = "org.nxnative.NSPortBuilder"
+
+ override func setUpWithError() throws {
+ temporary = FileManager.default.temporaryDirectory.appendingPathComponent("nxnative-update-tests-" + UUID().uuidString)
+ try FileManager.default.createDirectory(at: temporary, withIntermediateDirectories: true)
+ }
+
+ override func tearDownWithError() throws {
+ try FileManager.default.removeItem(at: temporary)
+ }
+
+ /// A launcher bundle as the release workflow assembles it.
+ @discardableResult
+ private func makeApp(_ name: String = "NX2Apple", in dir: URL? = nil, id: String? = nil, version: String = "0.4.8",
+ executable: Bool = true, marker: String = "new") throws -> URL {
+ let app = (dir ?? temporary).appendingPathComponent(name + ".app")
+ let macOS = app.appendingPathComponent("Contents/MacOS")
+ try FileManager.default.createDirectory(at: macOS, withIntermediateDirectories: true)
+ let exe = macOS.appendingPathComponent("NSPortBuilder")
+ try Data(marker.utf8).write(to: exe)
+ try FileManager.default.setAttributes([.posixPermissions: executable ? 0o755 : 0o644], ofItemAtPath: exe.path)
+ let info: [String: Any] = ["CFBundleIdentifier": id ?? bundleID, "CFBundleExecutable": "NSPortBuilder",
+ "CFBundleShortVersionString": version, "CFBundlePackageType": "APPL"]
+ try PropertyListSerialization.data(fromPropertyList: info, format: .xml, options: 0)
+ .write(to: app.appendingPathComponent("Contents/Info.plist"))
+ return app
+ }
+
+ private func digest(_ file: URL) throws -> String {
+ "sha256:" + SHA256.hash(data: try Data(contentsOf: file)).map { String(format: "%02x", $0) }.joined()
+ }
+
+ /// The app zipped as the release workflow does (ditto -c -k --keepParent).
+ private func zip(_ app: URL) throws -> URL {
+ let out = temporary.appendingPathComponent("download-" + UUID().uuidString + ".zip")
+ let p = Process()
+ p.executableURL = URL(fileURLWithPath: "/usr/bin/ditto")
+ p.arguments = ["-c", "-k", "--keepParent", app.path, out.path]
+ try p.run(); p.waitUntilExit()
+ XCTAssertEqual(p.terminationStatus, 0)
+ return out
+ }
+
+ private func marker(_ app: URL) throws -> String {
+ String(decoding: try Data(contentsOf: app.appendingPathComponent("Contents/MacOS/NSPortBuilder")), as: UTF8.self)
+ }
+
+ // ---- digest ----
+
+ func testDigestMatches() throws {
+ let file = temporary.appendingPathComponent("a.zip")
+ try Data("release".utf8).write(to: file)
+ XCTAssertEqual(AppUpdate.checkDigest(file, expected: try digest(file)), .match)
+ XCTAssertEqual(AppUpdate.checkDigest(file, expected: try digest(file).uppercased().replacingOccurrences(of: "SHA256:", with: "sha256:")), .match)
+ }
+
+ func testDigestMismatch() throws {
+ let file = temporary.appendingPathComponent("a.zip")
+ try Data("release".utf8).write(to: file)
+ let other = temporary.appendingPathComponent("b.zip")
+ try Data("something else".utf8).write(to: other)
+ XCTAssertEqual(AppUpdate.checkDigest(file, expected: try digest(other)), .mismatch)
+ XCTAssertEqual(AppUpdate.checkDigest(file, expected: "sha256:1234"), .mismatch) // malformed: never a match
+ }
+
+ func testDigestMissing() throws {
+ let file = temporary.appendingPathComponent("a.zip")
+ try Data("release".utf8).write(to: file)
+ XCTAssertEqual(AppUpdate.checkDigest(file, expected: nil), .missing)
+ XCTAssertEqual(AppUpdate.checkDigest(file, expected: ""), .missing)
+ XCTAssertEqual(AppUpdate.checkDigest(file, expected: "sha512:abcd"), .missing) // nothing to compare with
+ }
+
+ // ---- the app inside ----
+
+ func testBundleValidation() throws {
+ let good = try makeApp("Good")
+ XCTAssertNil(AppUpdate.bundleProblem(good, expectedID: bundleID, tag: "v0.4.8"))
+ XCTAssertEqual(AppUpdate.bundleProblem(try makeApp("Other", id: "com.example.Other"), expectedID: bundleID, tag: "v0.4.8"), .wrongIdentifier)
+ XCTAssertEqual(AppUpdate.bundleProblem(good, expectedID: "", tag: "v0.4.8"), .wrongIdentifier) // the running app has no identifier
+ XCTAssertEqual(AppUpdate.bundleProblem(try makeApp("NoExe", executable: false), expectedID: bundleID, tag: "v0.4.8"), .noExecutable)
+ XCTAssertEqual(AppUpdate.bundleProblem(good, expectedID: bundleID, tag: "v0.4.9"), .wrongVersion)
+ XCTAssertEqual(AppUpdate.bundleProblem(temporary.appendingPathComponent("Missing.app"), expectedID: bundleID, tag: "v0.4.8"), .noInfo)
+ }
+
+ func testStagingVerifiesDigestAndBundle() throws {
+ let source = temporary.appendingPathComponent("source", isDirectory: true)
+ let archive = try zip(try makeApp(in: source))
+ let release = AppUpdate.Release(tag: "v0.4.8", url: "https://example.invalid/NX2Apple-macOS-arm64.zip", digest: try digest(archive))
+ let root = temporary.appendingPathComponent("stage-ok", isDirectory: true)
+ try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
+ let staged = try BuildModel.stage(zip: archive, release: release, in: root, expectedID: bundleID, requireDigest: true).get()
+ XCTAssertEqual(staged.release, release)
+ XCTAssertEqual(staged.app.lastPathComponent, "NX2Apple.app")
+ XCTAssertEqual(try marker(staged.app), "new")
+ }
+
+ func testStagingRefusesMismatchMissingDigestAndWrongApp() throws {
+ let source = temporary.appendingPathComponent("source", isDirectory: true)
+ func attempt(_ digest: String?, automatic: Bool, id: String? = nil) throws -> Result<AppUpdate.Staged, BuildModel.StageFailure> {
+ let dir = source.appendingPathComponent(UUID().uuidString)
+ let archive = try zip(try makeApp(in: dir, id: id))
+ let root = temporary.appendingPathComponent("stage-" + UUID().uuidString, isDirectory: true)
+ try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
+ let release = AppUpdate.Release(tag: "v0.4.8", url: "https://example.invalid/a.zip", digest: digest == "self" ? try self.digest(archive) : digest)
+ return BuildModel.stage(zip: archive, release: release, in: root, expectedID: bundleID, requireDigest: automatic)
+ }
+ let wrong = "sha256:" + String(repeating: "0", count: 64)
+ XCTAssertEqual(try attempt(wrong, automatic: true).failure, .mismatch)
+ XCTAssertEqual(try attempt(wrong, automatic: false).failure, .mismatch) // a wrong digest is refused by hand too
+ XCTAssertEqual(try attempt(nil, automatic: true).failure, .noDigest)
+ XCTAssertNil(try attempt(nil, automatic: false).failure) // by hand, a release without one installs as before
+ XCTAssertEqual(try attempt("self", automatic: true, id: "com.example.Other").failure, .notOurApp)
+ }
+
+ // ---- which copies replace themselves ----
+
+ func testReleaseInstallIsUpdatable() throws {
+ let apps = temporary.appendingPathComponent("Applications", isDirectory: true)
+ let app = try makeApp(in: apps, version: "0.4.7")
+ XCTAssertEqual(AppUpdate.installability(app, appVersion: "0.4.7"), .ok)
+ }
+
+ func testDeveloperBuildsDoNotUpdate() throws {
+ // swift run: a bare executable's folder, no bundle
+ let release = temporary.appendingPathComponent("frontend/.build/arm64-apple-macosx/release", isDirectory: true)
+ try FileManager.default.createDirectory(at: release, withIntermediateDirectories: true)
+ XCTAssertEqual(AppUpdate.installability(release, appVersion: "0.4.7"), .developer)
+ // a bundle under .build or DerivedData
+ XCTAssertEqual(AppUpdate.installability(try makeApp(in: release, version: "0.4.7"), appVersion: "0.4.7"), .developer)
+ let derived = temporary.appendingPathComponent("DerivedData/NX2Apple/Build/Products/Release", isDirectory: true)
+ XCTAssertEqual(AppUpdate.installability(try makeApp(in: derived, version: "0.4.7"), appVersion: "0.4.7"), .developer)
+ // frontend/NX2Apple.app, assembled beside the Package.swift it was built from
+ let frontend = temporary.appendingPathComponent("frontend", isDirectory: true)
+ try Data().write(to: frontend.appendingPathComponent("Package.swift"))
+ XCTAssertEqual(AppUpdate.installability(try makeApp(in: frontend, version: "0.4.7"), appVersion: "0.4.7"), .developer)
+ // a bundle whose plist does not carry this binary's release number, or a binary without one
+ let elsewhere = temporary.appendingPathComponent("elsewhere", isDirectory: true)
+ XCTAssertEqual(AppUpdate.installability(try makeApp("Stale", in: elsewhere, version: "0.4.6"), appVersion: "0.4.7"), .developer)
+ XCTAssertEqual(AppUpdate.installability(try makeApp("Dev", in: elsewhere, version: "dev"), appVersion: "dev"), .developer)
+ XCTAssertEqual(AppUpdate.installability(try makeApp("NoID", in: elsewhere, id: "", version: "0.4.7"), appVersion: "0.4.7"), .developer)
+ }
+
+ func testReleaseVersions() {
+ XCTAssertTrue(AppUpdate.isReleaseVersion("0.4.7"))
+ XCTAssertTrue(AppUpdate.isReleaseVersion("1.0"))
+ for v in ["", "dev", "1", "0.4.7-local", "0..7", "v0.4.7", "0.4"] { XCTAssertFalse(AppUpdate.isReleaseVersion(v), v) }
+ }
+
+ func testReleaseParsingTakesTheDigest() {
+ let json: [String: Any] = ["tag_name": "v0.4.8", "assets": [
+ ["name": "nxnative-macOS-arm64.zip", "browser_download_url": "https://example.invalid/old.zip", "digest": "sha256:aa"],
+ ["name": "NX2Apple-macOS-arm64.zip", "browser_download_url": "https://example.invalid/new.zip", "digest": "sha256:bb"],
+ ]]
+ XCTAssertEqual(BuildModel.appRelease(fromJSON: json), AppUpdate.Release(tag: "v0.4.8", url: "https://example.invalid/new.zip", digest: "sha256:bb"))
+ let legacy: [String: Any] = ["tag_name": "v0.4.8", "assets": [["name": "NS-Port-Builder-macOS-arm64.zip", "browser_download_url": "https://example.invalid/legacy.zip"]]]
+ XCTAssertEqual(BuildModel.appRelease(fromJSON: legacy)?.digest, nil)
+ XCTAssertNil(BuildModel.appRelease(fromJSON: ["tag_name": "v0.4.8", "assets": []]))
+ }
+
+ // ---- when ----
+
+ func testInstallSwapsTheBundle() throws {
+ let current = try makeApp("Current", in: temporary.appendingPathComponent("Applications"), marker: "old")
+ let staged = try makeApp("Staged", in: temporary.appendingPathComponent("staged"), marker: "new")
+ try AppUpdate.install(staged, over: current, buildRunning: false, trashOld: false)
+ XCTAssertEqual(try marker(current), "new")
+ let left = try FileManager.default.contentsOfDirectory(atPath: current.deletingLastPathComponent().path)
+ XCTAssertEqual(left, ["Current.app"]) // no "(new)" or "(old)" copy beside it
+ }
+
+ func testInstallRefusedWhileBuildRuns() throws {
+ let current = try makeApp("Current", in: temporary.appendingPathComponent("Applications"), marker: "old")
+ let staged = try makeApp("Staged", in: temporary.appendingPathComponent("staged"), marker: "new")
+ XCTAssertThrowsError(try AppUpdate.install(staged, over: current, buildRunning: true, trashOld: false)) {
+ XCTAssertEqual($0 as? AppUpdate.InstallError, .buildRunning)
+ }
+ XCTAssertEqual(try marker(current), "old")
+ }
+
+ func testModelWaitsForTheBuild() throws {
+ let current = try makeApp("Current", in: temporary.appendingPathComponent("Applications"), marker: "old")
+ let staged = try makeApp("Staged", in: temporary.appendingPathComponent("staged"), marker: "new")
+ let model = BuildModel()
+ model.lang = .en
+ model.appInstallability = .ok
+ model.appStaged = AppUpdate.Staged(release: AppUpdate.Release(tag: "v0.4.8", url: "", digest: nil), app: staged)
+ model.running = true
+ XCTAssertFalse(model.mayInstallAppUpdate)
+ XCTAssertFalse(model.installStagedUpdate(relaunch: false, at: current))
+ model.restartToUpdate() // refused before it gets as far as a relaunch
+ XCTAssertEqual(try marker(current), "old")
+ XCTAssertNotNil(model.appStaged) // still waiting for the quit
+ XCTAssertEqual(model.appStatus, L10n.string("app.waitForBuild", .en))
+ }
+
+ func testDeveloperModelNeverInstalls() throws {
+ let current = try makeApp("Current", in: temporary.appendingPathComponent("Applications"), marker: "old")
+ let staged = try makeApp("Staged", in: temporary.appendingPathComponent("staged"), marker: "new")
+ let model = BuildModel()
+ model.appInstallability = .developer
+ model.appStaged = AppUpdate.Staged(release: AppUpdate.Release(tag: "v0.4.8", url: "", digest: nil), app: staged)
+ XCTAssertFalse(model.installStagedUpdate(relaunch: false, at: current))
+ XCTAssertEqual(try marker(current), "old")
+ }
+
+ 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"] {
+ XCTAssertNotNil(L10n.table[key], key)
+ }
+ XCTAssertTrue(L10n.selfCheck().isEmpty)
+ }
+}
+
+private extension Result {
+ var failure: Failure? { if case .failure(let f) = self { return f }; return nil }
+}
++
+ /// The update check's three outcomes must be distinguishable: a newer release with a download, a
+ /// newer release whose download this build cannot name, and genuinely being current.
+ ///
+ /// The middle one used to be reported as "已是最新" (issue: an installed 0.4.6 said it was current
+ /// while 0.4.8 was out). A build that looks for one exact asset name and does not find it has not
+ /// established that it is up to date — it has established that it cannot tell, and saying "up to
+ /// date" leaves that install stuck for ever.
-final class AppUpdateTests: XCTestCase {
++final class UpdateCheckTests: XCTestCase {
+ func testAVersionComparisonReadsTheNumbers() {
+ XCTAssertTrue(BuildModel.isNewer("v0.4.8", than: "0.4.6"))
+ XCTAssertTrue(BuildModel.isNewer("v0.4.10", than: "0.4.8"), "0.4.10 is newer than 0.4.8, not older")
+ XCTAssertFalse(BuildModel.isNewer("v0.4.8", than: "0.4.8"))
+ XCTAssertFalse(BuildModel.isNewer("v0.4.6", than: "0.4.8"))
+ }
+
+ /// The asset names this app will accept, oldest first. A release that carries any of them can
+ /// update every install back to 0.4.5; one that carries none leaves those installs stuck, which
+ /// is why checkAppUpdate has to say so rather than report "up to date".
+ func testTheAssetNamesCoverEveryInstallThatCanStillUpdate() {
+ let names = BuildModel.appAssetNames
+ XCTAssertTrue(names.contains("NX2Apple-macOS-arm64.zip"), "the current name")
+ XCTAssertTrue(names.contains("nxnative-macOS-arm64.zip"), "installs from before the rename to NX2Apple")
+ XCTAssertTrue(names.contains("NS-Port-Builder-macOS-arm64.zip"), "installs from before the rename to nxnative")
+ }
+ }