Something went wrong. Try again.
An auto tiler for macOS
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871import Foundationpublic import ParcelAnimationpublic import ParcelConfigpublic import ParcelCorepublic import ParcelPlatform
@MainActorpublic final class ParcelEngine { public internal(set) var snapshot: EngineSnapshot { didSet { snapshot.displaySuspensions = displaySuspensions } } public internal(set) var displaySuspensions: [DisplaySuspension] = [] public private(set) var configuration: ParcelConfiguration public private(set) var isRunning = false public private(set) var isAutomaticTilingEnabled = true public private(set) var isWaitingForTour = false public internal(set) var suspendedDisplays: Set<DisplayID> = [] { didSet { if oldValue != suspendedDisplays { publishPlacementState() } } } public internal(set) var systemWindowConflict: SystemWindowConflict? public var onSystemWindowConflictChanged: (@MainActor (SystemWindowConflict?) -> Void)? public var onCallback: (@MainActor (EngineCallbackInvocation) -> Void)? public var activity: ActivityCollector? var planningActivity: [WindowID: ActivityContext] = [:] var activityPlacements: [WindowID: ActivityPlacement] = [:] var activityBatchGenerations: [UInt64: UInt64] = [:] var callbacksPrimed = false public internal(set) var layoutPassCount = 0 public var isIdle: Bool { ruleSpaceOperation == nil && ruleSpaceRetry == nil && !spaceCommandRunning && !isStarting && !isFlushing && !pumping && queue.isEmpty && turn == nil && pumpWake == nil && animators.values.allSatisfy(\.isIdle) && coalescer.pendingCount == 0 && coalescer.inFlightCount == 0 && focusOperations == 0 && windowOperations.isEmpty && pendingMouseCommit == nil } public var writeMetrics: [MotionAppID: AppWriteMetrics] { coalescer.metricsSnapshot } public internal(set) var unmanageableApps: Set<AppID> = [] public internal(set) var wedgedApps: Set<AppID> = [] public internal(set) var classifications: [WindowID: WindowClassification] = [:] public var learnedMinimums: [String: LearnedMinimumSize] { minimumLearning.learned } var minimumLearning = MinimumSizeLearning() let minimumSizeStore: MinimumSizeStore? var minimumPersistence: Task<Result<Void, any Error>, Never>? var minimumResetInFlight: MinimumResetTransaction? public var onFailure: (@MainActor (any Error) -> Void)? public var onSetupProgress: (@MainActor (SetupOpening?, Bool) -> Void)? var onSetupUndo: (@MainActor (WindowID, UndoHistory) -> Void)? var setupOpening: SetupOpening? var setupOpeningReady = false var setupOpeningTimeout: (any EngineCancellation)? let workspaceStateStore: WorkspaceStateStore? public internal(set) var rememberedWorkspaces = WorkspaceMemory() var pendingRestorationMemory = WorkspaceMemory() var workspaceMemoryDirty = false var workspaceMemoryCaptureCount = 0 var workspaceSaveWake: (any EngineCancellation)? var workspaceRestoreWake: (any EngineCancellation)? var workspaceRestoreDeadlines: [WorkspaceKey: Double] = [:] var workspaceRestorationMapping: [WindowID: WindowID] = [:] var workspaceRestorationSeen: Set<WindowID> = [] var departingWorkspaceIdentities: [WorkspaceKey: DepartingWorkspaceIdentity] = [:] var pendingWorkspaceSave: WorkspaceMemory? var workspacePersistence: Task<Result<Void, any Error>, Never>? var workspaceLoading: Task<Void, Never>? var workspaceStorageFailed = false var workspaceStorageIsResetting = false var observations: [WindowID: (window: ManagedWindow, workspace: WorkspaceKey, frame: Rect)] = [:] var manualFloating: [WindowID: Bool] = [:] var settledApps: Set<AppID> = []
struct Pending { var event: Event let reply: CheckedContinuation<EngineCommandResult, any Error>? var commandID: UUID? = nil var activitySource: ActivitySource = .other var detections: [DetectionTrace]? = nil var isConfigurationRefresh = false var permitsRuleSpaceMove = false var isManualRuleReapplication = false var explicitFloatReadback: (window: WindowID, intent: ExplicitFloatPlacement)?
var isManualMovement: Bool { isManualRuleReapplication || event.isManualMovement } } struct Echo { var frame: Rect let transaction: UInt64 let generation: UInt64 var completedAt: Double? } public internal(set) var frameAdjustments: [WindowID: EngineFrameAdjustment] = [:] public internal(set) var frameWriteDiagnostics: [WindowID: AppThreadFrameWriteDiagnostics] = [:] var pendingSizeFitResets: Set<WindowID> = [] var acceptedReadbacks: [WindowID: [EngineFrameAdjustment]] = [:] var initialFloatPlacements: Set<WindowID> = [] var explicitFloatPlacements: [WindowID: ExplicitFloatPlacement] = [:] var echoLatencies: [AppID: Double] = [:] var correctiveWrites: [WindowID: [Double]] = [:] var protrusionAttempts: [WindowID: (target: Rect, count: Int)] = [:] var exhaustedProtrusionTargets: [WindowID: Rect] = [:] var blockedWindows: Set<WindowID> = [] var pointerIsDown = false var dragging: Set<WindowID> = [] var dropping: Set<WindowID> = [] var mouseModel = MouseModel() var pendingMouseCommit: PendingMouseCommit? var usesMouseSamples = false var liveResizeWindows: Set<WindowID> = [] var finalResizeWindows: Set<WindowID> = [] var deferredResizeMinimums: [WindowID: Event] = [:] public var onMouseFeedback: (@MainActor (EngineMouseFeedback) -> Void)? public var onMouseInputChanged: (@MainActor () -> Void)? public var onReport: (@MainActor (Report, State) -> Void)? let world: any EngineWindowWorld let spaceWorld: (any EngineSpaceWorld)? var spaceCommandRunning = false { didSet { if oldValue != spaceCommandRunning { publishPlacementState() } } } var attemptedRuleSpaces: [WindowID: RuleSpaceAssignment] = [:] var eligibleRuleSpaceWindows: Set<WindowID> = [] let startupWindowIDs: (@Sendable () async throws -> Set<WindowID>)? var ruleSpaceStartupWindows: Set<WindowID> = [] var dirtyRuleSpaceWindows: Set<WindowID> = [] var ruleSpaceRetry: (any EngineCancellation)? let ruleSpaceMoveStore: RuleSpaceMoveStore? var ruleSpaceMoveHistory: [RuleSpaceMoveRecord] = [] var appliedRuleLayouts: [WindowID: RuleLayoutAssignment] = [:] var ruleSpaceOperation: Task<Void, Never>? public var onAlwaysFloat: (@MainActor (ManagedWindow) async throws -> Void)? public var onUndoLastRule: (@MainActor () async throws -> Void)? var spaceOperation: Task<SpaceCommandResult, any Error>? public internal(set) var lastSpaceCommandResult: SpaceCommandResult? let clock: any EngineClock let scheduler: any EngineScheduler let makeDisplayLink: @MainActor (DisplayID) throws -> any EngineDisplayLink let announcer: any EngineAnnouncer let log: any EngineLogSink let trace: (any EngineTraceSink)? let emissionTrace: any ParcelTraceSink let recorder: (any EngineEventRecorder)? var traceCounter: UInt64 = 0 var turnTrace: UInt64? var planningTrace: UInt64? var frameTransactions: [WindowID: (generation: UInt64, revision: UInt64, transaction: UInt64)] = [:] let configSource: (any EngineConfigurationSource)? let reduceMotionSource: (any ReduceMotionSource)? var applied: AppliedConfiguration var queue: [Pending] = [] var turn: (any EngineCancellation)? var pumpWake: (any EngineCancellation)? var animators: [DisplayID: Animator] = [:] var motionPlans: [WindowID: EngineFocusMotionPlan] = [:] var nextMotionPlan: UInt64 = 0 var writtenMotionPlans: [WindowID: UInt64] = [:] var finalizedMotionPlans: [WindowID: UInt64] = [:] var dispatchedMotionTimes: [WindowID: Double] = [:] var links: [DisplayID: any EngineDisplayLink] = [:] var coalescer = FrameCoalescer() var pendingFrames: [MotionWindowID: MotionFrame] = [:] var busyApps: Set<MotionAppID> = [] var activeBatches: [MotionAppID: UInt64] = [:] var writesPermitted = true { didSet { if oldValue != writesPermitted { publishPlacementState() } } } var isStarting = false var isFlushing = false var lastDispatch: [MotionAppID: Double] = [:] var actualFrames: [WindowID: Rect] = [:] var nativeMouseFrames: [WindowID: Rect] = [:] var targets: [WindowID: Rect] = [:] var placements: [WindowID: DisplayID] = [:] var echoes: [WindowID: [Echo]] = [:] var intrinsicFloating: [WindowID: Bool] = [:] var minimumCandidates: [WindowID: (size: Size, confirmations: Int)] = [:] var subscribers: [UUID: AsyncStream<EngineSnapshot>.Continuation] = [:] var engineTime: Double = 0 var motionTick: UInt64 = 0 var revision: UInt64 = 0 var lifetime: UInt64 = 0 var focusOperations = 0 struct WindowOperation { let task: Task<Void, Never> let reply: CheckedContinuation<EngineCommandResult, any Error>? let windows: Set<WindowID> } struct RetileWindow { var target: Rect var generation: UInt64? var revision: UInt64? var initialFrame: Rect? var finalFrame: Rect? var confirmedMoved = false } struct RetileCompletion { let order: UInt64 let pending: Pending? let result: EngineCommandResult let timeout: any EngineCancellation var windows: [WindowID: RetileWindow] } static let retileConfirmationDuration = 5.0 var retileCompletionOrder: UInt64 = 0 var retileCompletions: [UUID: RetileCompletion] = [:] var windowOperations: [UUID: WindowOperation] = [:] var operatingWindows: Set<WindowID> { Set(windowOperations.values.flatMap(\.windows)) } var pumping = false var workspaceWriteAttempts: [WindowID: UInt64] = [:] var reduceMotion = false var snapNextPass = false var needsRetile = false let workspaceTransactionOwner = UUID() var workspaceWaiters: [UUID: WorkspaceWaiter] = [:] var manualWorkspaceRestoration: WorkspaceKey? var manualRestorationFrames: [WindowID: Rect] = [:] var tourFrameScope: TourFrameScope? var manualCommandFrames: [WindowID: Rect] = [:] var traced: Set<UInt64> = [] var firstWriteTraces: Set<UInt64> = [] var settlingTraces: Set<UInt64> = [] var openWrites: Set<UInt64> = []
public init( world: any EngineWindowWorld, clock: any EngineClock, scheduler: any EngineScheduler, displayLink: @escaping @MainActor (DisplayID) throws -> any EngineDisplayLink, announcer: any EngineAnnouncer, log: any EngineLogSink, configuration: ParcelConfiguration = .defaults, initialState: State = State(), configSource: (any EngineConfigurationSource)? = nil, trace: (any EngineTraceSink)? = SignpostEngineTrace(), reduceMotionSource: (any ReduceMotionSource)? = SystemEngineReduceMotionSource(), recorder: (any EngineEventRecorder)? = nil, minimumSizeStore: MinimumSizeStore? = nil, spaceWorld: (any EngineSpaceWorld)? = nil, workspaceStateStore: WorkspaceStateStore? = nil, ruleSpaceMoveStore: RuleSpaceMoveStore? = nil, startupWindowIDs: (@Sendable () async throws -> Set<WindowID>)? = nil ) throws { self.world = world self.spaceWorld = spaceWorld ?? (world as? any EngineSpaceWorld) self.minimumSizeStore = minimumSizeStore ?? (world is NativeEngineWorld ? MinimumSizeStore() : nil) self.workspaceStateStore = workspaceStateStore self.ruleSpaceMoveStore = ruleSpaceMoveStore if let startupWindowIDs { self.startupWindowIDs = startupWindowIDs } else if world is NativeEngineWorld { self.startupWindowIDs = { try await Task.detached { Set(try WindowServer().windows().map { WindowID(rawValue: $0.number) }) }.value } } else { self.startupWindowIDs = nil } self.clock = clock self.scheduler = scheduler self.makeDisplayLink = displayLink self.announcer = announcer self.log = log self.configSource = configSource self.trace = trace?.isEnabled == true ? trace : nil self.emissionTrace = trace?.emissionSink ?? SignpostTraceSink.shared self.recorder = recorder self.reduceMotionSource = reduceMotionSource reduceMotion = reduceMotionSource?.isEnabled == true self.configuration = configuration applied = try AppliedConfiguration(configuration) var state = initialState state.hoverFocusEnabled = configuration.mouse.focusFollowsMouse if let name = state.activeMode, configuration.modes[name] == nil { throw EngineError.invalidConfiguration(String(localized: "Unknown binding mode: \(name)", bundle: .module)) } applied.installLayoutDefaults(in: &state) for key in state.workspaces.keys { guard let existing = state.workspaces[key] else { continue } let display = state.displays[key.display] state.workspaces[key] = applied.workspace( key, in: display?.frame, existing: existing, preservingLayout: existing.layoutDefaults == nil && existing != Workspace(key: key), fullFrame: display?.fullFrame) } snapshot = EngineSnapshot(revision: 0, state: state) actualFrames = state.observedFrames.merging(state.frames) { observed, _ in observed } intrinsicFloating = state.windows.mapValues { $0.isFloating && $0.managementReason == .automatic } for window in state.windows.values { guard let key = state.workspace(containing: window.id), let frame = actualFrames[window.id] ?? state.frames[window.id] else { continue } observations[window.id] = (window, key, frame) } reportRatioBounds() }
public func start() async throws { guard !isRunning else { return } guard !isStarting else { throw EngineError.startInProgress } lifetime += 1 let generation = lifetime isStarting = true callbacksPrimed = false writesPermitted = true reduceMotionSource?.start { [weak self] in guard let self else { return } self.setReduceMotion(self.reduceMotionSource?.isEnabled == true) } do { if let ruleSpaceMoveStore { ruleSpaceMoveHistory = try await Task.detached { try ruleSpaceMoveStore.load() }.value guard isStarting, lifetime == generation else { throw EngineError.stopped } } if let minimumSizeStore { let loaded = try await Task.detached { try minimumSizeStore.load() }.value guard isStarting, lifetime == generation else { throw EngineError.stopped } minimumLearning = loaded } if let configSource { let initial = try await configSource.start { [weak self] update in guard let self, self.isStarting || self.isRunning, self.lifetime == generation else { return } do { try self.applyConfigSnapshot(update) } catch { self.log.record(.configuration(String(describing: error))) } } guard isStarting, lifetime == generation else { throw EngineError.stopped } try applyConfiguration(initial) } await loadWorkspaceMemory() ruleSpaceStartupWindows = Set(snapshot.state.windows.keys) if let startupWindowIDs { ruleSpaceStartupWindows.formUnion(try await startupWindowIDs()) } guard isStarting, lifetime == generation else { throw EngineError.stopped } world.setDetectionTracing(trace?.detectionSource) try world.start { [weak self] event in guard let self, self.isStarting || self.isRunning, self.lifetime == generation else { event.dropDetectionTracing() return } self.receive(event) } isStarting = false isRunning = true publishPlacementState() reportCapabilityLimits() needsRetile = true scheduleTurn() } catch { if lifetime == generation { await stop() } throw error } }
public func stop() async { tourFrameScope = nil cancelSetupOpening() isRunning = false ruleSpaceOperation?.cancel() await ruleSpaceOperation?.value ruleSpaceOperation = nil attemptedRuleSpaces.removeAll() eligibleRuleSpaceWindows.removeAll() ruleSpaceStartupWindows.removeAll() dirtyRuleSpaceWindows.removeAll() ruleSpaceRetry?.cancel() ruleSpaceRetry = nil appliedRuleLayouts.removeAll() spaceOperation?.cancel() if let spaceOperation { _ = await spaceOperation.result } spaceOperation = nil isStarting = false lifetime += 1 turn?.cancel() turn = nil pumpWake?.cancel() pumpWake = nil for link in links.values { link.stop() } links.removeAll() animators.removeAll() motionPlans.removeAll() writtenMotionPlans.removeAll() finalizedMotionPlans.removeAll() dispatchedMotionTimes.removeAll() snapshot.focusedMotionPlan = nil coalescer = FrameCoalescer() pendingFrames.removeAll() busyApps.removeAll() activeBatches.removeAll() activityBatchGenerations.removeAll() for transaction in openWrites { trace?.end(.write, transaction: transaction) } openWrites.removeAll() lastDispatch.removeAll() targets.removeAll() manualCommandFrames.removeAll() placements.removeAll() suspendedDisplays.removeAll() displaySuspensions.removeAll() snapshot.displaySuspensions.removeAll() systemWindowConflict = nil onSystemWindowConflictChanged?(nil) echoes.removeAll() unmanageableApps.removeAll() wedgedApps.removeAll() settledApps.removeAll() classifications.removeAll() observations.removeAll() manualFloating.removeAll() frameWriteDiagnostics.removeAll() pendingSizeFitResets.removeAll() acceptedReadbacks.removeAll() initialFloatPlacements.removeAll() explicitFloatPlacements.removeAll() frameTransactions.removeAll() turnTrace = nil planningTrace = nil echoLatencies.removeAll() dragging.removeAll() dropping.removeAll() mouseModel = MouseModel() pendingMouseCommit = nil usesMouseSamples = false liveResizeWindows.removeAll() finalResizeWindows.removeAll() deferredResizeMinimums.removeAll() onMouseFeedback?(.targetChanged(nil)) onMouseFeedback?(.layoutPreview(nil)) pointerIsDown = false focusOperations = 0 for completion in retileCompletions.values { completion.timeout.cancel() completion.pending?.reply?.resume(throwing: EngineError.stopped) } retileCompletions.removeAll() for operation in windowOperations.values { operation.task.cancel() operation.reply?.resume(throwing: EngineError.stopped) } windowOperations.removeAll() for failure in await world.stopRestoringFrameWrites() { log.record(.platform(failure)) } reduceMotionSource?.stop() for pending in queue { pending.reply?.resume(throwing: EngineError.stopped) for detection in pending.detections ?? [] { detection.finish(.dropped) } } queue.removeAll() needsRetile = false finishTracing() for id in workspaceWaiters.keys { finishWorkspaceWaiter(id, result: .failure(EngineError.stopped)) } for subscriber in subscribers.values { subscriber.finish() } subscribers.removeAll() await configSource?.stop() _ = await minimumPersistence?.value minimumPersistence = nil await flushWorkspaceMemoryOnStop() workspacePersistence = nil await workspaceLoading?.value workspaceLoading = nil log.flush() }
isolated deinit { for completion in retileCompletions.values { completion.timeout.cancel() completion.pending?.reply?.resume(throwing: EngineError.stopped) } retileCompletions.removeAll() for operation in windowOperations.values { operation.task.cancel() operation.reply?.resume(throwing: EngineError.stopped) } turn?.cancel() pumpWake?.cancel() workspaceSaveWake?.cancel() workspaceRestoreWake?.cancel() for link in links.values { link.stop() } world.stop() reduceMotionSource?.stop() for pending in queue { pending.reply?.resume(throwing: EngineError.stopped) for detection in pending.detections ?? [] { detection.finish(.dropped) } } for waiter in workspaceWaiters.values { waiter.timeout.cancel() waiter.reply.resume(throwing: EngineError.stopped) } for subscriber in subscribers.values { subscriber.finish() } }
}
extension ParcelEngine { public func snapshots() -> AsyncStream<EngineSnapshot> { let id = UUID() let (stream, continuation) = AsyncStream<EngineSnapshot>.makeStream(bufferingPolicy: .bufferingNewest(1)) subscribers[id] = continuation continuation.yield(snapshot) continuation.onTermination = { [weak self] _ in Task { @MainActor in self?.subscribers[id] = nil } } return stream }
public func send(_ event: Event, activitySource: ActivitySource = .other) { guard isRunning else { return } enqueue(event, activitySource: activitySource) }
public func perform(_ command: Command, in workspace: WorkspaceKey, activitySource: ActivitySource = .other) async throws -> EngineCommandResult { guard isRunning else { throw EngineError.stopped } guard !spaceCommandRunning else { throw spaceFailure(.busy) } try Task.checkCancellation() try requireCommandDisplay(command, display: workspace.display) let id = UUID() return try await withTaskCancellationHandler { try await withCheckedThrowingContinuation { reply in guard !Task.isCancelled else { reply.resume(throwing: CancellationError()) return } queue.append( Pending( event: .workspaceCommandIssued(command, workspace: workspace), reply: reply, commandID: id, activitySource: activitySource)) scheduleTurn() } } onCancel: { Task { @MainActor [weak self] in self?.cancelCommand(id) } } }
public func perform(_ command: Command, activitySource: ActivitySource = .other) async throws -> EngineCommandResult { guard isRunning else { throw EngineError.stopped } guard !spaceCommandRunning else { throw spaceFailure(.busy) } if case .enterMode(let name?) = command, configuration.modes[name] == nil { throw EngineError.invalidConfiguration(String(localized: "Unknown binding mode: \(name)", bundle: .module)) } try Task.checkCancellation() let nativeWindow = try await nativeFocusedWindow(for: command) try requireCommandDisplay( command, display: nativeWindow.flatMap { snapshot.state.workspace(containing: $0.id)?.display } ?? snapshot.state.activeWorkspace?.display, window: nativeWindow?.id, nativeWindow: nativeWindow) if let nativeWindow { if command == .toggleFloat || command == .toggleFocus { return try await perform(command, targeting: nativeWindow.id, activitySource: activitySource) } if command == .alwaysFloat { return try await alwaysFloat(window: nativeWindow.id) } } let nativeEffect = nativeFocusedEffect(for: command, window: nativeWindow) guard isRunning else { throw EngineError.stopped } guard !spaceCommandRunning else { throw spaceFailure(.busy) } let id = UUID() return try await withTaskCancellationHandler { try await withCheckedThrowingContinuation { reply in guard !Task.isCancelled else { reply.resume(throwing: CancellationError()) return } let pending = Pending( event: .commandIssued(command), reply: reply, commandID: id, activitySource: activitySource) if let nativeEffect { finishCommand(pending, effects: [nativeEffect]) } else { if let nativeWindow, snapshot.state.focusedWindow != nativeWindow.id { queue.append(Pending(event: .focusChanged(nativeWindow.id), reply: nil)) } queue.append(pending) scheduleTurn() } } } onCancel: { Task { @MainActor [weak self] in self?.cancelCommand(id) } } }
func cancelCommand(_ id: UUID) { if let completion = retileCompletions.removeValue(forKey: id) { completion.timeout.cancel() completion.pending?.reply?.resume(throwing: CancellationError()) settleIfIdle() return } if let operation = windowOperations[id] { operation.task.cancel() operation.reply?.resume(throwing: CancellationError()) windowOperations[id] = WindowOperation(task: operation.task, reply: nil, windows: operation.windows) return } guard let index = queue.firstIndex(where: { $0.commandID == id }) else { return } let pending = queue.remove(at: index) pending.reply?.resume(throwing: CancellationError()) for detection in pending.detections ?? [] { detection.dequeue(.dropped) } if queue.isEmpty && !needsRetile { turn?.cancel() turn = nil settleIfIdle() } }
public func applyConfigSnapshot(_ snapshot: ConfigSnapshot) throws { if !snapshot.diagnostics.isEmpty { log.record(.config(snapshot.diagnostics)) } try applyConfiguration(snapshot.activeConfiguration) }
public func applyConfiguration(_ configuration: ParcelConfiguration) throws { let updated = try AppliedConfiguration(configuration) guard configuration != self.configuration else { return } let enablingMemory = configuration.memory.enabled && !self.configuration.memory.enabled if configuration.mouse != self.configuration.mouse { cancelMouseGesture() } var state = snapshot.state if configuration.mouse.focusFollowsMouse != self.configuration.mouse.focusFollowsMouse { state.hoverFocusEnabled = configuration.mouse.focusFollowsMouse } let motionChanged = configuration.motion != self.configuration.motion updated.installLayoutDefaults(in: &state) var layoutFeedback: [Effect] = [] let changedWorkspaces = Set( state.workspaces.keys.filter { applied.values(for: $0.display) != updated.values(for: $0.display) }) stopRestoringWorkspaces(changedWorkspaces) if !configuration.memory.enabled { pendingWorkspaceSave = nil workspaceSaveWake?.cancel() workspaceSaveWake = nil stopRestoringWorkspaces(Set(pendingRestorationMemory.records.map { $0.workspace.key })) } for key in changedWorkspaces.sorted() { guard let previous = state.workspaces[key] else { continue } let display = state.displays[key.display] let preserveLayout = applied.defaultLayout(for: key.display, in: display?.fullFrame) == updated.defaultLayout(for: key.display, in: display?.fullFrame) let workspace = updated.workspace( key, in: display?.frame, existing: previous, preservingLayout: preserveLayout, previousValues: applied.values(for: key.display), fullFrame: display?.fullFrame) workspace.announceMergedTiles(since: previous, effects: &layoutFeedback) state.workspaces[key] = workspace } if configuration.floatRules != self.configuration.floatRules || configuration.rules != self.configuration.rules || configuration.classification != self.configuration.classification { for observed in observations.values.sorted(by: { $0.window.id < $1.window.id }) { let facts = observed.window.classificationFacts let before = applied.classifier.classify(facts) let after = updated.classifier.classify(facts) if before.layout != after.layout || before.display != after.display { appliedRuleLayouts[observed.window.id] = nil } if before.space != after.space || before.display != after.display || before.moveToSpace != after.moveToSpace { attemptedRuleSpaces[observed.window.id] = nil dirtyRuleSpaceWindows.insert(observed.window.id) } var window = observed.window window.isFloating = intrinsicFloating[window.id] ?? window.isFloating let frame = actualFrames[window.id] ?? observed.frame queue.append( Pending( event: .windowAppeared(window, workspace: observed.workspace, frame: frame), reply: nil, isConfigurationRefresh: true)) } } applied = updated self.configuration = configuration reconcileQueuedModes(activeMode: state.activeMode) reportRatioBounds() markWorkspaceMemoryChanges(previous: snapshot.state, next: state, events: []) snapshot = EngineSnapshot(revision: revision, state: state, readbackFrames: snapshot.readbackFrames) publishPlacementState() execute(layoutFeedback) if !changedWorkspaces.isEmpty { queue.append(Pending(event: .relayout, reply: nil, isConfigurationRefresh: true)) } if isRunning { reportCapabilityLimits() if enablingMemory { beginWorkspaceMemory() } if motionChanged { updateMotion() for display in animators.keys.sorted() { tick(display, at: animationTime) } } if needsRetile || !queue.isEmpty { scheduleTurn() } } }
func enqueue( _ event: Event, detections: [DetectionTrace]? = nil, activitySource: ActivitySource = .other, explicitFloatReadback: (window: WindowID, intent: ExplicitFloatPlacement)? = nil ) { if case .commandIssued(.enterMode(let name?)) = event, configuration.modes[name] == nil { log.record(.configuration(String(localized: "Unknown binding mode: \(name)", bundle: .module))) for detection in detections ?? [] { detection.dropIfUnowned() } return } let detections = trace == nil ? nil : detections for detection in detections ?? [] { detection.enqueue() } let permitsRuleSpaceMove: Bool if case .windowAppeared(let window, _, _) = event { permitsRuleSpaceMove = !isStarting && callbacksPrimed && !ruleSpaceStartupWindows.contains(window.id) && observations[window.id] == nil && snapshot.state.windows[window.id] == nil } else { permitsRuleSpaceMove = false } queue.append( Pending( event: event, reply: nil, activitySource: activitySource, detections: detections, permitsRuleSpaceMove: permitsRuleSpaceMove, explicitFloatReadback: explicitFloatReadback)) scheduleTurn() }
func scheduleTurn() { guard isRunning, turn == nil else { return } if let trace { traceCounter += 1 let transaction = traceCounter turnTrace = transaction traced.insert(transaction) firstWriteTraces.insert(transaction) trace.begin(.eventToFirstWrite, transaction: transaction) trace.begin(.eventToSettled, transaction: transaction) } turn = scheduler.schedule(after: 0) { [weak self] in self?.turn = nil self?.flush() } }
func settleIfIdle() { finishRetilesIfSettled() resolveWorkspaceWaiters() if !settlingTraces.isEmpty, !pumping, animators.values.allSatisfy(\.isIdle), coalescer.pendingCount == 0, coalescer.inFlightCount == 0 { finishMotionTracing() } guard isIdle else { return } finishTracing() let apps = settledApps settledApps.removeAll() if !apps.isEmpty { world.reconcileFrames(apps) } }
func beginMotionTrace(_ transaction: UInt64) { if settlingTraces.insert(transaction).inserted { trace?.begin(.settle, transaction: transaction) } }
func finishFirstWriteTrace(_ transaction: UInt64) { if firstWriteTraces.remove(transaction) != nil { trace?.end(.eventToFirstWrite, transaction: transaction) } }
func finishMotionTracing() { for transaction in settlingTraces { trace?.end(.settle, transaction: transaction) } settlingTraces.removeAll() }
func finishTracing() { finishMotionTracing() for transaction in firstWriteTraces { trace?.end(.eventToFirstWrite, transaction: transaction) } for transaction in traced { trace?.end(.eventToSettled, transaction: transaction) } firstWriteTraces.removeAll() traced.removeAll() }}
extension ParcelEngine { func reconcileQueuedModes(activeMode: String?) { queue = queue.filter { item in guard case .commandIssued(.enterMode(let name?)) = item.event, configuration.modes[name] == nil else { return true } let message = String(localized: "Unknown binding mode: \(name)", bundle: .module) for detection in item.detections ?? [] { detection.dequeue(.dropped) } if let reply = item.reply { reply.resume(throwing: EngineError.invalidConfiguration(message)) } else { log.record(.configuration(message)) } return false } let resultingMode = queue.reduce(activeMode) { current, item in if case .commandIssued(.enterMode(let mode)) = item.event { return mode } return current } if let resultingMode, configuration.modes[resultingMode] == nil { queue.append(Pending(event: .commandIssued(.enterMode(nil)), reply: nil)) } }
func reportCapabilityLimits() { for key in snapshot.state.workspaces.keys.sorted() { guard let workspace = snapshot.state.workspaces[key], workspace.windowCap != Int.max, workspace.effectiveWindowCap < workspace.windowCap else { continue } deliver(.layoutCapabilityLimit(layout: workspace.layout, maximum: workspace.effectiveWindowCap)) } }
func reportRatioBounds() { for values in [configuration.layout.global] + Array(configuration.layout.displays.values) where !MainRatio.bounds.contains(values.ratio) { log.record(.configuration("Layout ratio \(values.ratio) is clamped to \(MainRatio(values.ratio).value)")) } }
public func setReduceMotion(_ enabled: Bool) { guard reduceMotion != enabled else { return } reduceMotion = enabled updateMotion() }
public func resetWriteMetrics(for app: AppID) { coalescer.resetMetrics(for: app.motionID) }
package var tabViewClassifier: WindowClassifier { applied.classifier }
func publishPlacementState() { world.updatePlacementState( snapshot.state, classifier: applied.classifier, allowsSpeculation: applied.rules.isEmpty && isRunning && isAutomaticTilingEnabled && writesPermitted && suspendedDisplays.isEmpty && !spaceCommandRunning && setupOpening == nil) }
func suspendMotion() { tourFrameScope = nil for window in Array(placements.keys) { cancelMotion(window, remove: false) } pumpWake?.cancel() pumpWake = nil settleIfIdle() }
public func setWaitingForTour(_ waiting: Bool) { guard isWaitingForTour != waiting else { return } tourFrameScope = nil isWaitingForTour = waiting if waiting { workspaceSaveWake?.cancel() workspaceSaveWake = nil workspaceRestoreWake?.cancel() workspaceRestoreWake = nil setAutomaticTilingEnabled(false) // Manual motion can still be queued when automatic placement was already off. suspendMotion() manualCommandFrames.removeAll() } else { // Consent uses current configuration, not a saved arrangement from before it. stopRestoringWorkspaces(Set(pendingRestorationMemory.records.map { $0.workspace.key })) rememberWorkspaceState() } }
public func setAutomaticTilingEnabled(_ enabled: Bool, animatedResume: Bool = false) { guard !enabled || !isWaitingForTour, isAutomaticTilingEnabled != enabled else { return } isAutomaticTilingEnabled = enabled manualCommandFrames.removeAll() publishPlacementState() if !enabled { cancelMouseGesture() } if !enabled { suspendMotion() } else { snapNextPass = !animatedResume needsRetile = true if isRunning { scheduleTurn() } } }}
extension WindowID { init?(exactly id: MotionWindowID) { guard let rawValue = UInt32(exactly: id.rawValue) else { return nil } self.init(rawValue: rawValue) }}