Something went wrong. Try again.
An auto tiler for macOS
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352import AppKitimport Darwinimport Foundationimport OSLogimport ParcelConfigimport ParcelIPC
@MainActorfinal class AppDelegate: NSObject, NSApplicationDelegate { private var composition: AppComposition? private var runtime: NativeAppRuntime? private var startup: Task<Void, Never>? private let termination = AppTermination() private var signals: AppSignals? private let logger = Logger(subsystem: "dev.vinnymac.parcel", category: "lifecycle")
func applicationDidFinishLaunching(_ notification: Notification) { let environment = ProcessInfo.processInfo.environment do { let settings = try AppLaunchSettings( environment: environment, arguments: Array(CommandLine.arguments.dropFirst())) do { if try AppRelaunchFailureNotice.consume(configURL: settings.configURL) { NSApplication.shared.presentError( AppText.failure( "Parcel could not restart last time. It is running now with your saved language.")) } } catch { logger.error("Restart notice could not be read: \(error.localizedDescription, privacy: .public)") NSApplication.shared.presentError(error) } let store = ConfigStore(fileURL: settings.configURL) let runtime = NativeAppRuntime( store: store, socketPath: settings.socketPath, defaults: try settings.preferences(), fixtureOnly: settings.fixtureOnly, workspaceStateStore: NativeAppRuntime.workspaceStore( configURL: settings.configURL, fixtureOnly: settings.isolated), isolatedStorage: settings.isolatedStorage != nil) let composition = AppComposition(source: AppConfigStore(store: store), runtime: runtime) self.runtime = runtime self.composition = composition runtime.services.composition = composition runtime.services.quit = { [weak self] in self?.requestQuit() } runtime.configureLanguage( domain: settings.preferencesDomain(regularDomain: Bundle.main.bundleIdentifier ?? "dev.vinnymac.parcel") ) { [weak self] in self?.requestQuit(relaunch: true) } let signals = AppSignals( termination: termination, cleanup: { [weak self] in await self?.shutdown() }, terminate: { NSApplication.shared.terminate(nil) }) try signals.start() self.signals = signals startup = Task { @MainActor in do { if try await !composition.start() { self.logger.notice("Another Parcel instance holds the instance lock; this launch is quitting.") let running = NSWorkspace.shared.runningApplications.first { $0.bundleIdentifier == "dev.vinnymac.parcel" && $0.processIdentifier != getpid() } if running?.activate() != true { NSApplication.shared.presentError( AppText.failure("Parcel is already running. Open its menu bar item to continue.")) } self.requestQuit() } else { try runtime.updater.start() } } catch is CancellationError { return } catch { self.logger.error("Startup failed: \(error.localizedDescription, privacy: .public)") NSApplication.shared.presentError(error) self.requestQuit() } } } catch { logger.error("Startup failed: \(error.localizedDescription, privacy: .public)") NSApplication.shared.presentError(error) requestQuit() } }
func applicationShouldHandleReopen(_ sender: NSApplication, hasVisibleWindows flag: Bool) -> Bool { composition?.reopen() return true }
func applicationShouldTerminate(_ sender: NSApplication) -> NSApplication.TerminateReply { switch termination.request( cleanup: { [weak self] in await self?.shutdown() }, reply: { sender.reply(toApplicationShouldTerminate: true) }) { case .terminateNow: return .terminateNow case .terminateLater: return .terminateLater } }
private func requestQuit(relaunch: Bool = false) { // Calling terminate from a main-queue task blocks the async cleanup in AppKit's nested quit loop. let terminate = { @MainActor in NSApplication.shared.terminate(nil) } if relaunch { termination.requestRestart( cleanup: { [weak self] in await self?.shutdown() }, prepare: { try await AppRelaunch.prepare() }, terminate: terminate, report: { [weak self] error in self?.runtime?.languageRestartFailed(error) NSApplication.shared.presentError(error) }) return } if termination.requestQuit(cleanup: { [weak self] in await self?.shutdown() }, terminate: terminate) == .terminateNow { terminate() } }
private func shutdown() async { startup?.cancel() await startup?.value await composition?.stop() signals?.stop() if termination.didTimeOut { logger.error("Shutdown exceeded its restoration budget.") } }}
struct AppIsolatedStorage { let directory: URL let preferencesDomain: String private let token: UUID private let inode: UInt64 private let device: Int32
init(token: String?, path: String?) throws { guard let token, let id = UUID(uuidString: token), let path, path.hasPrefix("/"), !path.utf8.contains(0) else { throw CocoaError(.fileReadInvalidFileName) } let supplied = URL(fileURLWithPath: path, isDirectory: true).standardizedFileURL guard !supplied.pathComponents.contains("Application Support"), !supplied.pathComponents.contains("Preferences"), !supplied.pathComponents.contains(".config") else { throw CocoaError(.fileReadInvalidFileName) } let resolved = supplied.resolvingSymlinksInPath() guard supplied == resolved, supplied.lastPathComponent == "parcel-reality-\(id.uuidString)", !resolved.pathComponents.contains("Application Support"), !resolved.pathComponents.contains("Preferences"), !resolved.pathComponents.contains(".config") else { throw CocoaError(.fileReadInvalidFileName) } let attributes = try FileManager.default.attributesOfItem(atPath: supplied.path) guard attributes[.type] as? FileAttributeType == .typeDirectory, attributes[.ownerAccountID] as? UInt32 == getuid(), attributes[.posixPermissions] as? Int == 0o700 else { throw CocoaError(.fileReadNoPermission) } var identity = stat() guard supplied.path.withCString({ lstat($0, &identity) }) == 0 else { throw NSError(domain: NSPOSIXErrorDomain, code: Int(errno)) } self.token = id inode = identity.st_ino device = identity.st_dev directory = resolved preferencesDomain = "dev.vinnymac.parcel.reality.\(id.uuidString)" let entries = Set(try FileManager.default.contentsOfDirectory(atPath: directory.path)) for name in Self.files { let file = fileURL(name) if entries.contains(name) { let attributes = try FileManager.default.attributesOfItem(atPath: file.path) guard file.resolvingSymlinksInPath() == file, attributes[.type] as? FileAttributeType == .typeRegular, attributes[.ownerAccountID] as? UInt32 == getuid(), attributes[.referenceCount] as? Int == 1 else { throw CocoaError(.fileReadInvalidFileName) } } } }
static let files = [ "parcel.toml", "workspace-state.json", "minimum-sizes.json", "room-reminders.json", "rule-space-moves.json", "activity.json", "setups.json", "restart-failure.json", ]
func fileURL(_ name: String) -> URL { precondition(Self.files.contains(name)) return directory.appendingPathComponent(name) }
func validate() throws { let current = try Self(token: token.uuidString, path: directory.path) guard current.inode == inode, current.device == device else { throw CocoaError(.fileReadInvalidFileName) } }
func requireEvidenceOverride(_ path: String?, file name: String) throws { guard let path else { return } let supplied = URL(fileURLWithPath: path).standardizedFileURL let expected = directory.deletingLastPathComponent().appendingPathComponent(name) guard path.hasPrefix("/"), !path.utf8.contains(0), supplied == expected, supplied.resolvingSymlinksInPath() == supplied else { throw CocoaError(.fileReadInvalidFileName) } let parent = try FileManager.default.attributesOfItem(atPath: expected.deletingLastPathComponent().path) guard parent[.ownerAccountID] as? UInt32 == getuid(), parent[.posixPermissions] as? Int == 0o700 else { throw CocoaError(.fileReadNoPermission) } if FileManager.default.fileExists(atPath: supplied.path) { let attributes = try FileManager.default.attributesOfItem(atPath: supplied.path) guard attributes[.type] as? FileAttributeType == .typeRegular, attributes[.ownerAccountID] as? UInt32 == getuid(), attributes[.referenceCount] as? Int == 1 else { throw CocoaError(.fileReadInvalidFileName) } } }
func requireOverride(_ path: String?, file name: String) throws { guard let path else { return } guard path.hasPrefix("/"), !path.utf8.contains(0), URL(fileURLWithPath: path).standardizedFileURL.resolvingSymlinksInPath() == fileURL(name) else { throw CocoaError(.fileReadInvalidFileName) } }}
struct AppLaunchSettings { let configURL: URL let socketPath: String let fixtureOnly: Bool let fixtureFirstRun: Bool let isolatedStorage: AppIsolatedStorage? private let fixturePreferencesID: UUID? var isolated: Bool { fixtureOnly || isolatedStorage != nil }
init(environment: [String: String], arguments: [String] = []) throws { let requested = environment["PARCEL_REALITY"] == "1" || environment.keys.contains { $0.hasPrefix("PARCEL_REALITY_") } || arguments.contains("--reality-isolated") #if DEBUG && PARCEL_REALITY if requested { guard environment["PARCEL_REALITY"] == "1", arguments == ["--reality-isolated"] else { throw CocoaError(.fileReadInvalidFileName) } isolatedStorage = try AppIsolatedStorage( token: environment["PARCEL_REALITY_ISOLATION_TOKEN"], path: environment["PARCEL_REALITY_STATE_DIRECTORY"]) } else { isolatedStorage = nil } #else guard !requested, !arguments.contains("--reality-driver-host") else { throw CocoaError(.featureUnsupported) } isolatedStorage = nil #endif if let isolatedStorage { try isolatedStorage.requireOverride(environment["PARCEL_CONFIG_PATH"], file: "parcel.toml") try isolatedStorage.requireOverride(environment["PARCEL_ACTIVITY_PATH"], file: "activity.json") try isolatedStorage.requireOverride(environment["PARCEL_SETUPS_PATH"], file: "setups.json") #if DEBUG && PARCEL_REALITY try isolatedStorage.requireEvidenceOverride( environment["PARCEL_REALITY_RELAUNCH_RECEIPT"], file: "language-relaunch.json") #endif configURL = isolatedStorage.fileURL("parcel.toml") } else if let path = environment["PARCEL_CONFIG_PATH"] { guard path.hasPrefix("/"), !path.contains("\0") else { throw AppText.failure("The configuration path must be an absolute file path.") } configURL = URL(fileURLWithPath: path) } else { configURL = ConfigStore.defaultFileURL } var socketEnvironment = environment if let path = environment["PARCEL_SOCKET_PATH"] { socketEnvironment["PARCEL_SOCKET"] = path } socketPath = try ParcelIPC.IPCSocketPath.resolve(environment: socketEnvironment) fixtureOnly = environment["PARCEL_E2E"] == "1" fixtureFirstRun = fixtureOnly && environment["PARCEL_E2E_FIRST_RUN"] == "1" if fixtureOnly, let token = environment["PARCEL_E2E_TOKEN"] { guard let id = UUID(uuidString: token) else { throw AppText.failure("The test app's preferences could not be opened.") } fixturePreferencesID = id } else { fixturePreferencesID = nil } }
func preferencesDomain( regularDomain: String = "dev.vinnymac.parcel", fixtureSuite: String = "dev.vinnymac.parcel.e2e" ) -> String { if let isolatedStorage { return isolatedStorage.preferencesDomain } guard fixtureOnly else { return regularDomain } return fixturePreferencesID.map { "\(fixtureSuite).\($0.uuidString)" } ?? fixtureSuite }
@MainActor func preferences(regular: UserDefaults? = nil, fixtureSuite: String = "dev.vinnymac.parcel.e2e") throws -> UserDefaults { guard isolated else { return regular ?? .standard } try isolatedStorage?.validate() let suite = preferencesDomain(fixtureSuite: fixtureSuite) guard let defaults = UserDefaults(suiteName: suite) else { throw AppText.failure("The test app's preferences could not be opened.") } guard isolatedStorage == nil else { return defaults } if defaults.object(forKey: "guidedTour.v2.completed") == nil || !fixtureFirstRun && fixturePreferencesID == nil { defaults.set(true, forKey: "automaticTilingEnabled") defaults.set(!fixtureFirstRun, forKey: "onboardingCompleted") defaults.set(!fixtureFirstRun, forKey: "guidedTour.v2.completed") } return defaults }}
@mainstruct ParcelApplication { @MainActor static func main() { run(arguments: CommandLine.arguments) { let environment = ProcessInfo.processInfo.environment if AppRelaunch.runIfRequested(arguments: CommandLine.arguments) { return } #if DEBUG && PARCEL_REALITY if AppRealityDriverHost.runIfRequested( environment: environment, arguments: Array(CommandLine.arguments.dropFirst())) { return } #endif do { let settings = try AppLaunchSettings( environment: environment, arguments: Array(CommandLine.arguments.dropFirst())) try AppLocalizationLaunch.configure(settings: settings, environment: environment) try AppStandardStreams.redirect(environment: environment) } catch { // Launch Services discards stderr, so also log why launch was refused. Logger(subsystem: "dev.vinnymac.parcel", category: "lifecycle").fault( "Launch refused: \(String(describing: error), privacy: .public)") FileHandle.standardError.write(Data("\(error.localizedDescription)\n".utf8)) exit(EXIT_FAILURE) } let application = NSApplication.shared let delegate = AppDelegate() application.delegate = delegate application.setActivationPolicy(.accessory) withExtendedLifetime(delegate) { application.run() } } }
@MainActor static func run(arguments: [String], startApplication: () -> Void) { guard !arguments.dropFirst().contains("--smoke") else { return } startApplication() }}