import AppKit import Foundation import ParcelEngine @MainActor final class AppSetupApplications { struct Application { let pid: Int32 let bundleID: String? let bundleURL: URL? let launchDate: TimeInterval? let activationPolicy: NSApplication.ActivationPolicy let isTerminated: @MainActor () -> Bool let isHidden: @MainActor () -> Bool let hide: @MainActor () -> Bool let unhide: @MainActor () -> Bool init(_ application: NSRunningApplication) { pid = application.processIdentifier bundleID = application.bundleIdentifier bundleURL = application.bundleURL launchDate = application.launchDate?.timeIntervalSince1970 activationPolicy = application.activationPolicy isTerminated = { application.isTerminated } isHidden = { application.isHidden } hide = { application.hide() } unhide = { application.unhide() } } init( pid: Int32, bundleID: String?, bundleURL: URL?, launchDate: TimeInterval?, activationPolicy: NSApplication.ActivationPolicy, isTerminated: @escaping @MainActor () -> Bool, isHidden: @escaping @MainActor () -> Bool, hide: @escaping @MainActor () -> Bool, unhide: @escaping @MainActor () -> Bool ) { self.pid = pid self.bundleID = bundleID self.bundleURL = bundleURL self.launchDate = launchDate self.activationPolicy = activationPolicy self.isTerminated = isTerminated self.isHidden = isHidden self.hide = hide self.unhide = unhide } } enum Failure: Error, LocalizedError { case invalidBundleID(String) case applicationUnavailable(String) case invalidReceipt(String) case unhideRefused(String) case hideRefused(bundleID: String, hiddenBundleIDs: [String]) var errorDescription: String? { switch self { case .invalidBundleID: AppText.string("A setup app has an invalid identifier.") case .applicationUnavailable(let bundleID): AppText.detail("Setup application is not installed: %@.", bundleID).message case .invalidReceipt(let bundleID): AppText.detail("Setup application did not return a matching live launch: %@.", bundleID).message case .unhideRefused(let bundleID): AppText.detail("Setup application could not be unhidden: %@.", bundleID).message case .hideRefused(let bundleID, _): AppText.detail("Application refused to hide for the setup: %@.", bundleID).message } } } private let applications: @MainActor () -> [Application] private let applicationURL: @MainActor (String) -> URL? private let openApplication: @MainActor (URL, NSWorkspace.OpenConfiguration) async throws -> Application private let selfPID: Int32 private let selfBundleID: String? private let createsNewInstances: Bool private var hiddenApplications: [Application] = [] private let hideEligible: @MainActor (Application) throws -> Bool private let timing: AppSetupVisibilityTiming var onHidden: (@MainActor (Set) -> Void)? func displayName(for bundleID: String) -> String { guard let url = applicationURL(bundleID) else { return AppText.string("Unavailable app") } return FileManager.default.displayName(atPath: url.path) } convenience init(createsNewInstances: Bool = false) { self.init( applications: { NSWorkspace.shared.runningApplications.map(Application.init) }, applicationURL: { NSWorkspace.shared.urlForApplication(withBundleIdentifier: $0) }, openApplication: { url, configuration in let application = try await NSWorkspace.shared.openApplication(at: url, configuration: configuration) return Application(application) }, selfPID: ProcessInfo.processInfo.processIdentifier, selfBundleID: Bundle.main.bundleIdentifier, createsNewInstances: createsNewInstances, hideEligible: { application in #if DEBUG && PARCEL_REALITY if ProcessInfo.processInfo.environment["PARCEL_REALITY"] == "1" { let allowlist = try AppSetupHideAllowlist( ProcessInfo.processInfo.environment["PARCEL_REALITY_SETUP_HIDE_ALLOWLIST"]) return allowlist.contains(pid: application.pid, launchDate: application.launchDate) } #endif return true }) } init( applications: @escaping @MainActor () -> [Application], applicationURL: @escaping @MainActor (String) -> URL?, openApplication: @escaping @MainActor (URL, NSWorkspace.OpenConfiguration) async throws -> Application, selfPID: Int32, selfBundleID: String?, createsNewInstances: Bool = false, hideEligible: @escaping @MainActor (Application) throws -> Bool = { _ in true }, timing: AppSetupVisibilityTiming = .live ) { self.applications = applications self.applicationURL = applicationURL self.openApplication = openApplication self.selfPID = selfPID self.selfBundleID = selfBundleID self.createsNewInstances = createsNewInstances self.hideEligible = hideEligible self.timing = timing } var runningBundleIDs: Set { Set(applications().filter { $0.pid > 0 && !$0.isTerminated() }.compactMap(\.bundleID)) } func launch(bundleID: String) async throws -> SetupApplicationReceipt? { try Task.checkCancellation() guard Self.validBundleID(bundleID) else { throw Failure.invalidBundleID(bundleID) } let running = applications().filter { $0.pid > 0 && !$0.isTerminated() } let matching = running.filter { $0.bundleID == bundleID } if !matching.isEmpty { let hidden = matching.filter { $0.isHidden() } for application in hidden { _ = application.unhide() } guard try await confirm(hidden, hidden: false) else { throw Failure.unhideRefused(displayName(for: bundleID)) } return nil } guard let url = applicationURL(bundleID), url.isFileURL else { throw Failure.applicationUnavailable(displayName(for: bundleID)) } let configuration = NSWorkspace.OpenConfiguration() configuration.activates = false configuration.addsToRecentItems = false configuration.promptsUserIfNeeded = false configuration.createsNewApplicationInstance = createsNewInstances try Task.checkCancellation() let application = try await openApplication(url, configuration) // Return the actual launch even if cancellation arrived while Launch Services was opening it. // The caller needs this receipt to account for that irreversible action. guard application.pid > 0, application.bundleID == bundleID, !application.isTerminated(), application.bundleURL?.isFileURL == true, application.bundleURL?.resolvingSymlinksInPath().standardizedFileURL == url.resolvingSymlinksInPath().standardizedFileURL, application.launchDate.map(\.isFinite) != false else { throw Failure.invalidReceipt(displayName(for: bundleID)) } return SetupApplicationReceipt( requestedBundleID: bundleID, applicationURL: url, preexistingPIDs: running.map(\.pid).sorted(), pid: application.pid, bundleID: application.bundleID, bundleURL: application.bundleURL, launchDate: application.launchDate, isTerminated: application.isTerminated()) } func hideOtherApps(keeping: Set) async throws -> [String] { try Task.checkCancellation() let targets = try applications().sorted(by: { $0.pid < $1.pid }).filter { application in guard application.pid > 0, application.pid != selfPID, application.activationPolicy == .regular, !application.isTerminated(), !application.isHidden(), let bundleID = application.bundleID, Self.validBundleID(bundleID) else { return false } return try bundleID != selfBundleID && !keeping.contains(bundleID) && !Self.isProtected(application) && hideEligible(application) } var requested: [Application] = [] do { for application in targets { try Task.checkCancellation() // A false native status can still produce a delayed hide; retain every attempted identity for recovery. requested.append(application) _ = application.hide() } let confirmed = try await confirm(requested, hidden: true) let hidden = requested.filter { $0.isHidden() }.compactMap(\.bundleID).reduce(into: [String]()) { if !$0.contains($1) { $0.append($1) } } guard confirmed else { let failed = requested.first { !$0.isHidden() } throw Failure.hideRefused( bundleID: failed?.bundleID.map(displayName(for:)) ?? AppText.string("Unavailable app"), hiddenBundleIDs: hidden) } hiddenApplications = requested return hidden } catch { do { try await restore(requested) } catch let recovery { throw AppFailure(message: "\(error.localizedDescription) \(recovery.localizedDescription)") } throw error } } func unhideApps(_ bundles: Set) async throws { let targets = hiddenApplications.filter { $0.bundleID.map(bundles.contains) == true } hiddenApplications.removeAll { $0.bundleID.map(bundles.contains) == true } try await restore(targets) } private func restore(_ targets: [Application]) async throws { guard !targets.isEmpty else { return } // A pending hide can still have a visible cached flag; let it arrive before requesting its reversal. try await timing.pause(timing.now().advanced(by: .milliseconds(10)), false) let live = targets.filter { !$0.isTerminated() } for application in live { _ = application.unhide() } guard try await confirm(live, hidden: false, cancellable: false) else { throw Failure.unhideRefused( live.first?.bundleID.map(displayName(for:)) ?? AppText.string("Unavailable app")) } } private func confirm(_ targets: [Application], hidden: Bool, cancellable: Bool = true) async throws -> Bool { let deadline = timing.now().advanced(by: .milliseconds(500)) guard !targets.isEmpty else { return true } try await timing.pause(min(deadline, timing.now().advanced(by: .milliseconds(10))), cancellable) var published: Set = [] while true { if cancellable { try Task.checkCancellation() } if hidden { let confirmed = Set(targets.filter { !$0.isTerminated() && $0.isHidden() }.map(\.pid)) let fresh = confirmed.subtracting(published) if !fresh.isEmpty { onHidden?(fresh); published.formUnion(fresh) } } if targets.allSatisfy({ !$0.isTerminated() && $0.isHidden() == hidden }) { return true } if timing.now() >= deadline { return false } try await timing.pause(min(deadline, timing.now().advanced(by: .milliseconds(10))), cancellable) } } private static func validBundleID(_ value: String) -> Bool { !value.isEmpty && value.utf8.count <= 255 && value.split(separator: ".", omittingEmptySubsequences: false).allSatisfy { component in !component.isEmpty && component.utf8.allSatisfy { (65...90).contains($0) || (97...122).contains($0) || (48...57).contains($0) || $0 == 45 || $0 == 95 } } } private static func isProtected(_ application: Application) -> Bool { guard let bundleID = application.bundleID else { return true } if bundleID == "dev.vinnymac.parcel" || bundleID.hasPrefix("dev.vinnymac.parcel.") { return true } if systemBundleIDs.contains(bundleID.lowercased()) { return true } guard let url = application.bundleURL, url.isFileURL else { return true } let path = url.resolvingSymlinksInPath().path return path == "/System/Library" || path.hasPrefix("/System/Library/") } private static let systemBundleIDs: Set = [ "com.apple.finder", "com.apple.dock", "com.apple.loginwindow", "com.apple.systemuiserver", "com.apple.controlcenter", "com.apple.notificationcenterui", "com.apple.windowmanager", "com.apple.universalcontrol", "com.apple.screencaptureui", "com.apple.screensaver.engine", "com.apple.securityagent", "com.apple.systemevents", ] }