Something went wrong. Try again.
An auto tiler for macOS
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169import AppKitimport Darwinimport Foundationimport OSLog
@MainActorenum AppRelaunch { static let option = "--relaunch-after-exit" static let ready: UInt8 = 1
static func prepare(bundle: Bundle = .main, parent: Int32 = getpid()) async throws -> (@MainActor () -> Void) { try Task.checkCancellation() guard bundle.bundleURL.pathExtension == "app", let executable = bundle.executableURL else { throw SettingsRestartFailure.notBundled } let environment = ProcessInfo.processInfo.environment.filter { $0.key.hasPrefix("PARCEL_") } _ = try replacementSettings(environment: environment) let helper = Process() helper.environment = environment let output = Pipe() helper.executableURL = executable helper.arguments = [option, String(parent)] helper.standardInput = FileHandle.nullDevice helper.standardOutput = output helper.standardError = FileHandle.nullDevice try helper.run() output.fileHandleForWriting.closeFile() defer { output.fileHandleForReading.closeFile() } do { try await withTaskCancellationHandler { try await confirmReadiness(descriptor: output.fileHandleForReading.fileDescriptor) try Task.checkCancellation() guard helper.isRunning else { throw SettingsRestartFailure.helperUnavailable } #if DEBUG && PARCEL_REALITY if let receipt = AppRelaunchReceipt.url { try AppRelaunchReceipt( parent: parent, helper: helper.processIdentifier, bundlePath: bundle.bundleURL.resolvingSymlinksInPath().path ).write(to: receipt) } #endif } onCancel: { if helper.isRunning { helper.terminate() } } } catch { if helper.isRunning { helper.terminate() } throw error } return { if helper.isRunning { helper.terminate() } } }
static func confirmReadiness(descriptor: Int32, timeoutMilliseconds: Int32 = 5_000) async throws { let owned = dup(descriptor) guard owned >= 0 else { throw SettingsRestartFailure.helperUnavailable } let expected = ready try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, any Error>) in Thread.detachNewThread { defer { close(owned) } let deadline = DispatchTime.now().uptimeNanoseconds + UInt64(max(0, timeoutMilliseconds)) * 1_000_000 var source = pollfd(fd: owned, events: Int16(POLLIN), revents: 0) var status: Int32 repeat { let now = DispatchTime.now().uptimeNanoseconds let remaining = now < deadline ? Int32((deadline - now) / 1_000_000) : 0 status = poll(&source, 1, remaining) } while status == -1 && errno == EINTR var byte: UInt8 = 0 guard status > 0, source.revents & Int16(POLLIN) != 0, read(owned, &byte, 1) == 1, byte == expected else { continuation.resume(throwing: SettingsRestartFailure.helperUnavailable) return } continuation.resume() } } }
static func parent(arguments: [String]) throws -> Int32? { guard arguments.dropFirst().contains(option) else { return nil } guard arguments.count == 3, arguments[1] == option, let pid = Int32(arguments[2]), pid > 1 else { throw SettingsRestartFailure.invalidParent } return pid }
static func replacementSettings(environment: [String: String]) throws -> AppLaunchSettings { let isolated = environment["PARCEL_REALITY"] == "1" || environment.keys.contains { $0.hasPrefix("PARCEL_REALITY_") } return try AppLaunchSettings(environment: environment, arguments: isolated ? ["--reality-isolated"] : []) }
static func runIfRequested(arguments: [String]) -> Bool { do { guard let parent = try parent(arguments: arguments) else { return false } guard Bundle.main.bundleURL.pathExtension == "app" else { throw SettingsRestartFailure.notBundled } guard getppid() == parent || (getppid() == 1 && kill(parent, 0) == -1 && errno == ESRCH) else { throw SettingsRestartFailure.invalidParent } let environment = ProcessInfo.processInfo.environment.filter { $0.key.hasPrefix("PARCEL_") } let settings = try replacementSettings(environment: environment) FileHandle.standardOutput.write(Data([ready])) Task { @MainActor in await waitForExit(parent) let configuration = NSWorkspace.OpenConfiguration() configuration.createsNewApplicationInstance = true configuration.arguments = settings.isolatedStorage == nil ? [] : ["--reality-isolated"] configuration.environment = environment do { try settings.isolatedStorage?.validate() _ = try replacementSettings(environment: environment) let application = try await NSWorkspace.shared.openApplication( at: Bundle.main.bundleURL, configuration: configuration) #if DEBUG && PARCEL_REALITY try AppRelaunchReceipt.recordReplacement(application, parent: parent) #else _ = application #endif exit(EXIT_SUCCESS) } catch { reportHelperFailure(error) exit(EXIT_FAILURE) } } dispatchMain() } catch { Logger(subsystem: "dev.vinnymac.parcel", category: "lifecycle") .error("Relaunch helper failed: \(error.localizedDescription, privacy: .public)") exit(EXIT_FAILURE) } }
private static func reportHelperFailure(_ error: any Error) { let logger = Logger(subsystem: "dev.vinnymac.parcel", category: "lifecycle") logger.error("Relaunch failed: \(error.localizedDescription, privacy: .public)") do { let settings = try replacementSettings(environment: ProcessInfo.processInfo.environment) try AppRelaunchFailureNotice.record(configURL: settings.configURL) } catch { logger.error("Relaunch failure notice could not be saved: \(error.localizedDescription, privacy: .public)") } }
private static func waitForExit(_ pid: Int32) async { guard kill(pid, 0) == 0 else { return } await withCheckedContinuation { continuation in let source = DispatchSource.makeProcessSource(identifier: pid, eventMask: .exit, queue: .main) source.setEventHandler { source.cancel() continuation.resume() } source.resume() } }}
private enum SettingsRestartFailure: Error, LocalizedError { case notBundled, invalidParent, helperUnavailable
var errorDescription: String? { switch self { case .notBundled: AppText.string("Restart requires a bundled application.") case .invalidParent: AppText.string("Restart requires its original parent process.") case .helperUnavailable: AppText.string("Parcel could not prepare to restart. It is still running. Try again.") } }}