import Foundation import ParcelAnimation import ParcelCore private enum RetileVerificationFailure: Error { case missingBaseline(WindowID) case missingFinalFrame(WindowID) case deadlineExceeded(unconfirmed: Int) } extension ParcelEngine { func execute(_ effects: [Effect]) { var raised: Set = [] for effect in effects { switch effect { case .setFrames, .confirmRetile, .closeWindow, .toggleFullscreen, .saveFloatingRule, .undoLastRule: break case .focusWindow(let window): guard !isWaitingForTour, snapshot.focusedWindow == window else { continue } focusEffect(window, raise: false) case .raiseWindow(let window): guard !isWaitingForTour, snapshot.state.visibleWindows.contains(window), raised.insert(window).inserted else { continue } if window != snapshot.focusedWindow { focusEffect(window, raise: true) } case .announce(let value): if case .layoutChanged = value, !configuration.accessibility.announceLayoutChanges { continue } if case .focused(let window) = value, snapshot.focusedWindow != window { continue } announcer.announce(value) case .report(let report): deliver(report) } } if let focused = snapshot.focusedWindow, raised.contains(focused) { focusEffect(focused, raise: true) } } func deliver(_ report: Report) { log.record(.core(report)) onReport?(report, snapshot.state) } func nativeFocusedWindow(for command: Command) async throws -> ManagedWindow? { let enablesFocus = command == .toggleFocus && snapshot.state.activeFocusModes.focusedWindow == nil let usesConfirmedFocus: Bool switch command { case .swap, .focusNextWindow, .focusPreviousWindow, .focusNextInStack, .focusPreviousInStack, .makePrimary: usesConfirmedFocus = true default: usesConfirmedFocus = false } guard command == .close || command == .toggleFullscreen || command == .toggleFloat || command == .alwaysFloat || enablesFocus || usesConfirmedFocus, let provider = world as? any EngineCommandWindowProviding else { return nil } do { return try await provider.focusedCommandWindow() } catch { recordWindowCommandFailure(error) throw error } } func nativeFocusedEffect(for command: Command, window: ManagedWindow?) -> Effect? { guard command == .close || command == .toggleFullscreen, let window, snapshot.focusedWindow != window.id else { return nil } return command == .close ? .closeWindow(window.id) : .toggleFullscreen(window.id) } func finishCommand(_ pending: Pending?, effects: [Effect]) { let reports = effects.compactMap { effect -> Report? in if case .report(let report) = effect { return report } return nil } let result = EngineCommandResult( revision: revision, reports: reports, isAccepted: !reports.contains(where: \.isFailure)) if result.isAccepted, let pending { let command: Command? switch pending.event { case .commandIssued(let value), .workspaceCommandIssued(let value, _), .commandForWindow(_, let value, _): command = value default: command = nil } if let feature = command.flatMap(Self.activityFeature) { activity?.record(feature: feature) } } if let candidates = effects.compactMap({ effect -> [WindowFrame]? in if case .confirmRetile(let frames) = effect { return frames } return nil }).first { if candidates.isEmpty { let report = Report.retiled(moved: 0) deliver(report) pending?.reply?.resume( returning: EngineCommandResult( revision: result.revision, reports: result.reports + [report], isAccepted: result.isAccepted)) return } let id = pending?.commandID ?? UUID() retileCompletionOrder += 1 let timeout = scheduler.schedule(after: Self.retileConfirmationDuration) { [weak self] in self?.finishRetile(id, deadlineExceeded: true) self?.settleIfIdle() } retileCompletions[id] = RetileCompletion( order: retileCompletionOrder, pending: pending, result: result, timeout: timeout, windows: Dictionary( uniqueKeysWithValues: candidates.map { ($0.window, RetileWindow(target: $0.frame)) })) return } let native = effects.filter { $0.commandWindow != nil || $0 == .undoLastRule } guard !native.isEmpty else { pending?.reply?.resume(returning: result) return } let windows = Set(native.compactMap(\.commandWindow)) if let busy = windows.intersection(operatingWindows).sorted().first { let error = EngineWindowCommandError.busy(busy) recordWindowCommandFailure(error) pending?.reply?.resume(throwing: error) return } for window in windows { cancelMotion(window, remove: false) } let id = pending?.commandID ?? UUID() let generation = lifetime let task = Task { @MainActor [weak self] in guard let self else { return } let outcome: Result do { for effect in native { try Task.checkCancellation() guard self.isRunning, self.lifetime == generation else { throw EngineError.stopped } guard !self.isWaitingForTour else { throw CancellationError() } switch effect { case .closeWindow(let window): try await self.world.close(window) case .toggleFullscreen(let window): try await self.world.toggleFullscreen(window) case .undoLastRule: guard let undo = self.onUndoLastRule else { throw EngineError.settingsUnavailable } try await undo() case .saveFloatingRule(let window): guard let observed = self.observations[window]?.window, let writer = self.onAlwaysFloat else { throw EngineError.settingsUnavailable } try await writer(observed) guard self.isRunning, self.lifetime == generation else { throw EngineError.stopped } try Task.checkCancellation() if self.manualFloating[window] != true { self.reapplyRule(to: window) } default: preconditionFailure("Expected a native window effect.") } } try Task.checkCancellation() guard self.isRunning, self.lifetime == generation else { throw EngineError.stopped } outcome = .success(result) } catch { if self.isRunning, self.lifetime == generation, !(error is CancellationError) { self.recordWindowCommandFailure(error) } outcome = .failure(error) } guard let operation = self.windowOperations.removeValue(forKey: id) else { return } operation.reply?.resume(with: outcome) self.settleIfIdle() } windowOperations[id] = WindowOperation(task: task, reply: pending?.reply, windows: windows) } private func recordWindowCommandFailure(_ error: any Error) { if let failure = error as? EnginePlatformFailure { handle(failure) } else { log.record(.internalFailure(error)) onFailure?(error) } } func focusEffect(_ window: WindowID, raise: Bool) { guard !spaceCommandRunning else { return } guard let app = snapshot.state.windows[window]?.app, !unmanageableApps.contains(app), let workspace = snapshot.state.workspace(containing: window), snapshot.state.isActive(workspace), !suspendedDisplays.contains(workspace.display) else { return } let generation = lifetime focusOperations += 1 let completion: @MainActor (EnginePlatformFailure?) -> Void = { [weak self] failure in guard let self, self.isStarting || self.isRunning, self.lifetime == generation else { return } self.focusOperations -= 1 if let failure { self.handle(failure) } self.settleIfIdle() } if raise { world.raise(window, completion: completion) } else { world.focus(window, completion: completion) } } func cancelMotion(_ window: WindowID, remove: Bool, preservingUnboundFloat: Bool = false) { if !preservingUnboundFloat || explicitFloatPlacements[window]?.generation != nil { cancelExplicitFloatPlacement(window) } if remove || !finalResizeWindows.contains(window) { activityPlacements[window] = nil } for id in retileCompletions.keys { if let candidate = retileCompletions[id]?.windows[window], candidate.generation != nil, candidate.finalFrame == nil, !candidate.confirmedMoved { retileCompletions[id]?.windows[window] = nil } } if let generation = coalescer.generation(for: window.motionID), let app = snapshot.state.windows[window]?.app { world.cancelFrameWrites(window, for: app, throughGeneration: generation) } for display in animators.keys { animators[display]?.cancel(window.motionID) if animators[display]?.isIdle == true { links[display]?.stop() } } let focusedPlan = snapshot.focusedMotionPlan motionPlans[window] = nil writtenMotionPlans[window] = nil finalizedMotionPlans[window] = nil dispatchedMotionTimes[window] = nil updateFocusedMotionPlan() if focusedPlan != snapshot.focusedMotionPlan { for subscriber in subscribers.values { subscriber.yield(snapshot) } } coalescer.remove(window.motionID) pendingFrames[window.motionID] = nil frameTransactions[window] = nil targets[window] = nil placements[window] = nil if remove { workspaceWriteAttempts[window] = nil actualFrames[window] = nil manualCommandFrames[window] = nil echoes[window] = nil intrinsicFloating[window] = nil minimumCandidates[window] = nil frameAdjustments[window] = nil frameWriteDiagnostics[window] = nil acceptedReadbacks[window] = nil initialFloatPlacements.remove(window) pendingSizeFitResets.remove(window) correctiveWrites[window] = nil protrusionAttempts[window] = nil exhaustedProtrusionTargets[window] = nil blockedWindows.remove(window) dragging.remove(window) dropping.remove(window) liveResizeWindows.remove(window) finalResizeWindows.remove(window) deferredResizeMinimums[window] = nil } } func continueRetileCorrections(_ events: [Event]) { guard events.allSatisfy({ event in switch event { case .relayout, .minimumSizeChanged, .focusChanged: true default: false } }) else { return } for id in retileCompletions.keys { guard let completion = retileCompletions[id] else { continue } for window in completion.windows.keys { if let frame = snapshot.state.frames[window] { retileCompletions[id]?.windows[window]?.target = frame } } } } func bindRetile(_ window: WindowID, plan: FramePlan) { for id in retileCompletions.keys { guard var candidate = retileCompletions[id]?.windows[window], candidate.target == snapshot.state.frames[window] else { continue } candidate.generation = plan.request.generation candidate.revision = plan.revision candidate.finalFrame = nil retileCompletions[id]?.windows[window] = candidate } } func capturesRetileBaseline(_ window: WindowID, sent: MotionFrame) -> Bool { retileCompletions.values.contains { guard let candidate = $0.windows[window] else { return false } return candidate.generation == sent.generation && candidate.revision == sent.revision && candidate.initialFrame == nil } } func acceptRetileBaseline(_ observed: WindowFrame, sent: MotionFrame) { for id in retileCompletions.keys { guard let candidate = retileCompletions[id]?.windows[observed.window], candidate.generation == sent.generation, candidate.revision == sent.revision, candidate.initialFrame == nil else { continue } retileCompletions[id]?.windows[observed.window]?.initialFrame = observed.frame } } func acceptRetileReadback(_ observed: WindowFrame, sent: MotionFrame) { for id in retileCompletions.keys { guard var candidate = retileCompletions[id]?.windows[observed.window], candidate.generation == sent.generation, candidate.revision == sent.revision else { continue } if sent.isFinal { candidate.finalFrame = observed.frame if let initial = candidate.initialFrame, initial != observed.frame { candidate.confirmedMoved = true } } retileCompletions[id]?.windows[observed.window] = candidate } } func finishRetilesIfSettled() { guard !retileCompletions.isEmpty, !isFlushing, !pumping, queue.isEmpty, turn == nil, !needsRetile, animators.values.allSatisfy(\.isIdle), coalescer.pendingCount == 0, coalescer.inFlightCount == 0 else { return } let ids = retileCompletions.sorted { $0.value.order < $1.value.order }.map(\.key) for id in ids { finishRetile(id, deadlineExceeded: false) } } private func finishRetile(_ id: UUID, deadlineExceeded: Bool) { guard let completion = retileCompletions.removeValue(forKey: id) else { return } completion.timeout.cancel() if deadlineExceeded { let unconfirmed = completion.windows.values.filter { $0.finalFrame == nil }.count log.record(.internalFailure(RetileVerificationFailure.deadlineExceeded(unconfirmed: unconfirmed))) } else { for (window, candidate) in completion.windows where candidate.generation != nil { if candidate.initialFrame == nil { log.record(.internalFailure(RetileVerificationFailure.missingBaseline(window))) } else if candidate.finalFrame == nil { log.record(.internalFailure(RetileVerificationFailure.missingFinalFrame(window))) } } } let moved = completion.windows.values.filter(\.confirmedMoved).count let report = Report.retiled(moved: moved) deliver(report) completion.pending?.reply?.resume( returning: EngineCommandResult( revision: completion.result.revision, reports: completion.result.reports + [report], isAccepted: completion.result.isAccepted)) } func pruneMotion() { for id in retileCompletions.keys { guard var completion = retileCompletions[id] else { continue } completion.windows = completion.windows.filter { window, candidate in candidate.confirmedMoved || candidate.finalFrame != nil || (snapshot.state.frames[window] == candidate.target && snapshot.state.workspace(containing: window).map { snapshot.state.isActive($0) } == true) } retileCompletions[id] = completion } for window in placements.keys { guard let key = snapshot.state.workspace(containing: window), snapshot.state.isActive(key) else { cancelMotion(window, remove: snapshot.state.windows[window] == nil) continue } let ownsDirectWrite = dragging.contains(window) && liveResizeWindows.contains(window) && placements[window].map { snapshot.state.displays[$0] != nil } == true if placements[window] != key.display && !ownsDirectWrite { cancelMotion(window, remove: false) } } for display in animators.keys where snapshot.state.displays[display] == nil { links[display]?.stop() links[display] = nil animators[display] = nil } } } extension Effect { fileprivate var commandWindow: WindowID? { switch self { case .closeWindow(let window), .toggleFullscreen(let window), .saveFloatingRule(let window): window default: nil } } }