importAppKitimportSparkleimport os/// Sparkle 2 — the only file that imports it.////// Cotton for the Mac is installed from a download, so it updates itself:/// Sparkle over a static appcast, every entry signed with the EdDSA key whose/// public half is `SUPublicEDKey`. Neither `SUFeedURL` nor `SUPublicEDKey` is/// in the committed `Resources/Info.plist`: `build-cotton-mac.sh` stamps both/// into the built bundle when it is given the public key, so the private half/// stays a secret in the vault.////// **A build with no feed has no updater at all.** [`Updates.hasFeed`] reads/// the bundle, and without an https feed and a key nothing here is/// constructed: an updater pointed at nothing would show Sparkle's own/// "could not check" alert about a channel that does not exist.////// **Nothing asks the person to install.** `SUEnableAutomaticChecks`,/// `SUScheduledCheckInterval` (hourly, Sparkle's floor) and/// `SUAutomaticallyUpdate` are on in `Info.plist`, and the app has no Dock/// icon and no window to hold a dialog. A downloaded build is installed NOW/// rather than on a quit a menu-bar importer never makes ([`InstallNow`]): a/// run in flight is cut short, which loses nothing, because a reader's cursor/// moves only after the object took the batch. And a Mac that wakes asks the/// feed at once, since a scheduled check that came while it slept was missed.@MainActorfinalclassUpdates {privatelet controller: SPUStandardUpdaterController?privatelet installNow = InstallNow()privatestaticlet log = Logger(subsystem: "com.decemberfm.cotton.mac", category: "updates")init(bundle: Bundle = .main) {guardUpdates.hasFeed(bundle.infoDictionary ?? [:]) else { controller = nilreturn } controller = SPUStandardUpdaterController( startingUpdater: true, updaterDelegate: installNow, userDriverDelegate: nil ) NSWorkspace.shared.notificationCenter.addObserver( forName: NSWorkspace.didWakeNotification, object: nil, queue: .main ) { [weakself] _ inTask { @MainActor [weakself] inself?.checkInBackground() } } }/// Whether this bundle can verify an update: an https `SUFeedURL` and a/// non-empty `SUPublicEDKey`. Pure, so a test reads it without Sparkle. nonisolated staticfunc hasFeed(_ info: [String: Any]) -> Bool {guardlet feed = info["SUFeedURL"] as? String,let url = URL(string: feed), url.scheme == "https",let key = info["SUPublicEDKey"] as? String, !key.trimmingCharacters(in: .whitespaces).isEmptyelse { returnfalse }returntrue }/// Whether this build can update itself (it has a feed).var available: Bool { controller != nil }/// Check for updates, asked on the panel: Sparkle says what it found.func checkNow() { NSApp.activate() controller?.checkForUpdates(nil) }privatefunc checkInBackground() {guardlet controller, controller.updater.automaticallyChecksForUpdates else { return }Updates.log.info("update: checking the feed — the Mac woke") controller.updater.checkForUpdatesInBackground() }}/// The one delegate: "install on quit" answered by installing now.privatefinalclassInstallNow: NSObject, SPUUpdaterDelegate {func updater( _ updater: SPUUpdater, willInstallUpdateOnQuit item: SUAppcastItem, immediateInstallationBlock immediateInstallHandler: @escaping () -> Void ) -> Bool {let version = item.displayVersionString// The watcher goes out FIRST: once the handler runs this process is on// its way out, and nothing after it is promised to happen. Sparkle// calls this delegate on the main thread.MainActor.assumeIsolated { ComeBack.arm(version: version) } immediateInstallHandler()returntrue }}/// The app comes back whether or not Sparkle brings it: a detached `/bin/sh`/// left behind before the install, which opens the app again if it is not/// running [`graceSeconds`] later (CottonDB's 0.15 → 0.16 night, when every/// Mac installed and stayed quit). Copied from CottonDB's `Updates.swift`.enumComeBack {staticlet graceSeconds = 90staticvar bundleIdentifier: String { Bundle.main.bundleIdentifier ?? "com.decemberfm.cotton.mac" }staticvar executableName: String { (Bundle.main.object(forInfoDictionaryKey: "CFBundleExecutable") as? String) ?? "Cotton" }staticlet logPath = "~/Library/Logs/Cotton/relaunch.log"/// Sleep, look, open if absent, and say so. `pgrep -x` matches the/// process name exactly.staticfunc script( version: String, grace: Int = graceSeconds, bundleIdentifier: String = ComeBack.bundleIdentifier, executable: String = ComeBack.executableName ) -> String {let log = NSString(string: logPath).expandingTildeInPathreturn"sleep \(grace); " + "if ! pgrep -x \(executable) >/dev/null 2>&1; then " + "mkdir -p \"$(dirname '\(log)')\"; " + "echo \"$(date -u +%Y-%m-%dT%H:%M:%SZ) \(executable) was not running \(grace)s after installing \(version) — opening \(bundleIdentifier)\" >> '\(log)'; " + "open -b '\(bundleIdentifier)'; " + "fi" }/// Leave the watcher behind. Never throws and never blocks: the install/// is the thing that must not wait on it. @MainActorstaticfunc arm(version: String) {let watcher = Process() watcher.executableURL = URL(fileURLWithPath: "/bin/sh") watcher.arguments = ["-c", script(version: version)] watcher.standardInput = FileHandle.nullDevice watcher.standardOutput = FileHandle.nullDevice watcher.standardError = FileHandle.nullDevicetry? watcher.run() }}