Something went wrong. Try again.
An auto tiler for macOS
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468import CryptoKitpublic import Foundationimport Observationimport ParcelConfigpublic import ParcelCorepublic import ParcelPlatform
public enum SetupOperationError: Error, LocalizedError, Sendable { case engineUnavailable, busy, unknownSetup, invalidShortcut, invalidPosition, storageUnavailable, destinationsUnavailable, visibilityRecoveryUnavailable
public var errorDescription: String? { switch self { case .engineUnavailable: String(localized: "Start Parcel before saving or opening a setup.", bundle: .module) case .destinationsUnavailable: String( localized: "A saved display is waiting for macOS. Open the setup again after its desktop is ready.", bundle: .module) case .visibilityRecoveryUnavailable: String(localized: "Hidden apps could not be restored. Unhide them from the Dock.", bundle: .module) case .busy: String(localized: "A setup operation is already in progress.", bundle: .module) case .unknownSetup: String(localized: "That setup no longer exists.", bundle: .module) case .invalidShortcut: String(localized: "Choose a valid shortcut with at least one modifier.", bundle: .module) case .invalidPosition: String(localized: "That setup position is no longer available.", bundle: .module) case .storageUnavailable: String(localized: "Setups need attention. Repair the saved file before making changes.", bundle: .module) } }}
@MainActor @Observablepublic final class SetupCoordinator { public private(set) var setups: [SavedSetup] = [] public private(set) var loading: SetupLoading? public private(set) var failure: String? public private(set) var recoveryURL: URL? private var mutationInProgress: UUID? public var isBusy: Bool { mutationInProgress != nil || loading != nil || operation != nil } public var canUndoDelete: Bool { deleted != nil } public let fileURL: URL public var onChange: (@MainActor () -> Void)? public var onFailure: (@MainActor (any Error) -> Void)? public private(set) var launches: [SetupApplicationReceipt] = [] @ObservationIgnored public var runningBundleIDs: (@MainActor () throws -> Set<String>)? @ObservationIgnored private let store: SetupStore @ObservationIgnored private let engine: @MainActor () -> ParcelEngine? @ObservationIgnored private let launch: @MainActor (String) async throws -> SetupApplicationReceipt? @ObservationIgnored private let hide: @MainActor (Set<String>) async throws -> [String] @ObservationIgnored private let requireReady: @MainActor () throws -> Void @ObservationIgnored private var loaded = false @ObservationIgnored private var openedID: UUID? @ObservationIgnored private var deleted: (setup: SavedSetup, index: Int)? @ObservationIgnored private var operation: UUID? @ObservationIgnored private var state = State() @ObservationIgnored private var stateRevision: UInt64 = 0 @ObservationIgnored private var statusCache: [UUID: (revision: UInt64, status: SetupStatus)] = [:] @ObservationIgnored private var launchTask: Task<Void, Never>? @ObservationIgnored private var launchReply: AsyncThrowingStream<Void, any Error>.Continuation? @ObservationIgnored private var hidingTask: Task<Void, Never>? @ObservationIgnored private var launchesReady = false @ObservationIgnored private var hiddenBundleIDs: Set<String> = [] @ObservationIgnored private var hiddenUndoHistory: UndoHistory? @ObservationIgnored private var undoBeforeFinishing: UndoHistory? @ObservationIgnored private let unhide: @MainActor (Set<String>) async throws -> Void @ObservationIgnored public var applicationName: @MainActor (String) -> String = { _ in String(localized: "Unavailable app", bundle: .module) } @ObservationIgnored public var displayName: @MainActor (DisplayID) -> String = { _ in String(localized: "Disconnected display", bundle: .module) } public var isLoaded: Bool { loaded }
public func updateState(_ state: State) { self.state = state stateRevision += 1 }
public init( store: SetupStore, engine: @escaping @MainActor () -> ParcelEngine?, launch: @escaping @MainActor (String) async throws -> SetupApplicationReceipt?, hide: @escaping @MainActor (Set<String>) async throws -> [String], unhide: @escaping @MainActor (Set<String>) async throws -> Void = { if !$0.isEmpty { throw SetupOperationError.visibilityRecoveryUnavailable } }, requireReady: @escaping @MainActor () throws -> Void = {} ) { self.store = store fileURL = store.fileURL self.engine = engine self.launch = launch self.hide = hide self.unhide = unhide self.requireReady = requireReady }
public func load() async throws { try await mutate { let value = try await Self.read(self.store) self.setups = value.setups self.statusCache.removeAll() self.updateState(self.engine()?.snapshot.state ?? self.state) self.loaded = true self.recoveryURL = nil } }
public func status(for id: UUID) -> SetupStatus { guard let setup = setups.first(where: { $0.id == id }) else { return .saved } let revision = stateRevision + (engine()?.snapshot.revision ?? 0) if let cached = statusCache[id], cached.revision == revision { return cached.status } let currentEngine = engine() var observed = state if let engine = currentEngine, engine.isRunning { observed = engine.snapshot.state for id in observed.windows.keys { observed.frames[id] = engine.actualFrames[id] ?? engine.snapshot.readbackFrames[id] ?? observed.frames[id] } } let status: SetupStatus = setup.matches(observed) ? .onScreen : openedID == id ? .changed : .saved statusCache[id] = (revision, status) return status }
public func attach(to engine: ParcelEngine) { updateState(engine.snapshot.state) engine.onSetupUndo = { [weak self] target, current in guard let self, !self.hiddenBundleIDs.isEmpty, let expected = self.hiddenUndoHistory, expected.hasSameLatestOperation(as: current, for: target), !expected.hasSameLatestOperation(as: self.undoBeforeFinishing ?? UndoHistory(), for: target) else { return } self.restoreHiddenApps() } engine.onSetupProgress = { [weak self, weak engine] opening, timedOut in guard let self, let engine else { return } self.updateState(engine.snapshot.state) if let opening, !opening.isFinished { self.loading = SetupLoading( id: opening.setup.id, name: opening.setup.name, pendingBundleIDs: opening.pendingBundleIDs, pendingApplicationNames: opening.pendingBundleIDs.map(self.applicationName)) self.finishWhenReady() } else { self.loading = nil if timedOut || opening?.phase == .cancelled { self.cancelOpening() } else { self.operation = nil let history = engine.snapshot.state.undoHistory self.hiddenUndoHistory = history != self.undoBeforeFinishing ? history : nil } if timedOut, let opening { let apps = Set(opening.missingWindows.map { self.applicationName($0.window.bundleID) }).sorted() let destinations = opening.missingWorkspaces.map { self.displayName($0.workspace.display) } let missing = (apps + destinations).formatted(.list(type: .and)) let message = String( localized: "The setup timed out. Apps or saved destinations did not appear: %@", bundle: .module ) self.failure = missing.isEmpty ? String(localized: "The setup timed out while confirming app visibility.", bundle: .module) : String(format: message, missing) self.onFailure?(SetupNotice(message: self.failure ?? message)) self.operation = nil } } self.onChange?() } onChange?() }
public func save(name: String, emoji: String? = nil, hideOtherApps: Bool = true, shortcut: String? = nil) async throws { try await mutate { try self.requireLoaded() let engine = try self.runningEngine() engine.flushSetupState() try self.validateShortcut(shortcut, excluding: nil) let memory = try self.captureMemory(preserving: engine.rememberedWorkspaces, state: engine.snapshot.state) let setup = SavedSetup( name: name, emoji: emoji, shortcut: shortcut, hideOtherApps: hideOtherApps, memory: memory) try await self.persist(self.setups + [setup]) } }
public func update(_ id: UUID) async throws { try await mutate { try self.requireLoaded() let index = try self.index(id) let old = self.setups[index] let engine = try self.runningEngine() engine.flushSetupState() let memory = try self.captureMemory(preserving: old.memory, state: engine.snapshot.state) var updated = self.setups updated[index] = SavedSetup( id: old.id, name: old.name, emoji: old.emoji, shortcut: old.shortcut, hideOtherApps: old.hideOtherApps, memory: memory) try await self.persist(updated) } }
public func edit(_ id: UUID, name: String, emoji: String?, shortcut: String?, hideOtherApps: Bool) async throws { try await mutate { try self.requireLoaded() let index = try self.index(id) try self.validateShortcut(shortcut, excluding: id) let old = self.setups[index] var updated = self.setups updated[index] = SavedSetup( id: id, name: name, emoji: emoji, shortcut: shortcut, hideOtherApps: hideOtherApps, memory: old.memory) try await self.persist(updated) } }
public func delete(_ id: UUID) async throws { try await mutate { try self.requireLoaded() let index = try self.index(id) let setup = self.setups[index] var updated = self.setups updated.remove(at: index) try await self.persist(updated) self.deleted = (setup, index) if self.openedID == id { self.openedID = nil } } }
public func undoDelete() async throws { try await mutate { guard let deleted = self.deleted else { return } var updated = self.setups updated.insert(deleted.setup, at: min(deleted.index, updated.count)) try await self.persist(updated) self.deleted = nil } }
public func move(_ id: UUID, to index: Int) async throws { try await mutate { guard self.setups.indices.contains(index) else { throw SetupOperationError.invalidPosition } let previous = try self.index(id) var updated = self.setups let setup = updated.remove(at: previous) updated.insert(setup, at: index) try await self.persist(updated) } }
public func open(_ id: UUID) async throws { try await mutate { try self.requireLoaded() let setup = self.setups[try self.index(id)] let engine = try self.runningEngine() let ticket = UUID() try engine.beginSetupOpening(setup) self.operation = ticket self.openedID = id self.launches = [] self.launchesReady = false self.hiddenBundleIDs = [] let reply = AsyncThrowingStream<Void, any Error>.makeStream() self.launchReply = reply.continuation self.launchTask = Task { [weak self] in guard let self else { reply.continuation.finish(throwing: CancellationError()); return } do { let bundles = Set(setup.memory.records.flatMap { $0.windows.map(\.bundleID) }) for bundle in bundles.sorted() { try Task.checkCancellation() guard self.operation == ticket, engine.isRunning else { throw CancellationError() } let receipt = try await self.launch(bundle) guard self.operation == ticket, !Task.isCancelled else { throw CancellationError() } if let receipt { self.launches.append(receipt) } } self.launchesReady = true self.finishWhenReady() reply.continuation.finish() } catch { if self.operation == ticket { self.launchReply = nil self.cancelOpening() } reply.continuation.finish(throwing: error) } } do { for try await _ in reply.stream {} try Task.checkCancellation() } catch { if self.operation == ticket { self.cancelOpening() } throw error } } }
public func cancelOpening() { guard operation != nil || loading != nil else { return } operation = nil mutationInProgress = nil launchTask?.cancel() launchTask = nil launchReply?.finish(throwing: CancellationError()) launchReply = nil hidingTask?.cancel() hidingTask = nil engine()?.cancelSetupOpening() loading = nil restoreHiddenApps() onChange?() }
private func finishWhenReady() { guard launchesReady, let ticket = operation, let engine = engine(), let opening = engine.setupOpening, opening.unresolvedCount == 0, hidingTask == nil else { return } guard opening.setup.hideOtherApps else { engine.completeSetupLaunches() return } let bundles = Set(opening.setup.memory.records.flatMap { $0.windows.map(\.bundleID) }) hidingTask = Task { [weak self] in guard let self else { return } do { let hidden = Set(try await self.hide(bundles)) guard self.operation == ticket, !Task.isCancelled else { try await self.unhide(hidden) return } self.hiddenBundleIDs = hidden // The adapter reconciles confirmed process identities; bundle IDs can include visible sibling instances. engine.flushSetupState() self.undoBeforeFinishing = engine.snapshot.state.undoHistory engine.completeSetupLaunches() self.hidingTask = nil } catch is CancellationError { if self.operation == ticket { self.cancelOpening() } } catch { if self.operation == ticket { self.cancelOpening() } self.failure = error.localizedDescription self.onFailure?(error) self.onChange?() } } }
private func restoreHiddenApps() { let hidden = hiddenBundleIDs hiddenBundleIDs = [] hiddenUndoHistory = nil guard !hidden.isEmpty else { return } Task { [weak self] in guard let self else { return } do { try await self.unhide(hidden) } catch { self.failure = error.localizedDescription self.onFailure?(error) self.onChange?() } } }
private func runningEngine() throws -> ParcelEngine { try requireReady() guard let engine = engine(), engine.isRunning else { throw SetupOperationError.engineUnavailable } return engine }
private func index(_ id: UUID) throws -> Int { guard let index = setups.firstIndex(where: { $0.id == id }) else { throw SetupOperationError.unknownSetup } return index }
private func captureMemory(preserving prior: WorkspaceMemory, state: State) throws -> WorkspaceMemory { let running = try runningBundleIDs?() let records = prior.records.map { record in guard state.displays[record.workspace.key.display] != nil, let running else { return record } return record.retainingApplications(running) } let previous = try WorkspaceMemory(records: records, titleSalt: prior.titleSalt) let salt = previous.titleSalt.count == 32 ? previous.titleSalt : Self.salt() return try WorkspaceMemory.capture(state, preserving: previous, titleSalt: salt, maximumCount: Int.max) }
private func validateShortcut(_ shortcut: String?, excluding id: UUID?) throws { guard let shortcut else { return } let chord = try KeyChord(parsing: shortcut) guard !chord.modifiers.isEmpty else { throw SetupOperationError.invalidShortcut } if let engine = engine() { let configuration = engine.configuration let reserved = Array(configuration.keybindings.values) + Array(configuration.defaultModeEntries.values) + configuration.modes.values.flatMap { $0.values } guard !reserved.contains(chord) else { throw SetupOperationError.invalidShortcut } } for setup in setups where setup.id != id { if let stored = setup.shortcut, try KeyChord(parsing: stored) == chord { throw SetupOperationError.invalidShortcut } } }
private func requireLoaded() throws { guard loaded else { throw SetupOperationError.storageUnavailable } }
private func persist(_ setups: [SavedSetup]) async throws { let catalog = try SetupCatalog(setups: setups) try await Self.write(store, catalog: catalog) self.setups = setups updateState(engine()?.snapshot.state ?? state) statusCache.removeAll() }
private func mutate(_ action: @MainActor () async throws -> Void) async throws { guard !isBusy else { throw SetupOperationError.busy } let mutation = UUID() mutationInProgress = mutation defer { if mutationInProgress == mutation { mutationInProgress = nil } onChange?() } do { try await action() failure = nil } catch let cancellation as CancellationError { throw cancellation } catch { if let corruption = error as? SetupStoreCorruptionError { recoveryURL = corruption.backupURL failure = String( format: String( localized: "The setups file is unreadable. Your data was preserved at %@. Repair the file, then reload Setups.", bundle: .module), corruption.backupURL.path) } else if let storage = error as? SetupStoreError, case .unsupportedVersion(let version) = storage { failure = String( format: String( localized: "Unsupported setups format %lld. The file was kept unchanged.", bundle: .module), Int64(version)) } else if let metadata = error as? SavedSetupError { switch metadata { case .invalidName: failure = String(localized: "Enter a setup name of up to 128 characters.", bundle: .module) case .invalidEmoji: failure = String(localized: "Choose one emoji, or leave the emoji empty.", bundle: .module) case .duplicateName: failure = String(localized: "A setup with that name already exists.", bundle: .module) default: failure = error.localizedDescription } } else { failure = error.localizedDescription } onFailure?(SetupNotice(message: failure ?? error.localizedDescription)) throw error } }
@concurrent private static func read(_ store: SetupStore) async throws -> SetupCatalog { try store.load() } @concurrent private static func write(_ store: SetupStore, catalog: SetupCatalog) async throws { try store.save(catalog) } private static func salt() -> Data { SymmetricKey(size: .bits256).withUnsafeBytes { Data($0) } }}
private struct SetupNotice: Error, LocalizedError { let message: String var errorDescription: String? { message }}