From fa957213175de0900349ebe86fbb7253b286ef33 Mon Sep 17 00:00:00 2001 From: Vincent Taverna Date: Mon, 2 Nov 2026 00:42:19 -0500 Subject: [PATCH] Finish sizing and verified retile commands Signed-off-by: Vincent Taverna --- Sources/ParcelCore/AdaptiveLayouts.swift | 43 +++- Sources/ParcelCore/Commands.swift | 63 +++--- Sources/ParcelCore/LayoutEngine.swift | 4 +- Sources/ParcelCore/Model.swift | 4 + Sources/ParcelCore/Reducer.swift | 49 ++++- Sources/ParcelCore/State.swift | 39 +++- Sources/ParcelCore/WorkspaceMemory.swift | 8 +- .../ParcelEngine/EngineConfiguration.swift | 5 + Sources/ParcelEngine/EngineEffects.swift | 129 +++++++++++- Sources/ParcelEngine/EngineEvents.swift | 10 +- Sources/ParcelEngine/EngineIPCHandler.swift | 2 + Sources/ParcelEngine/EngineInterfaces.swift | 12 +- Sources/ParcelEngine/EngineMotion.swift | 11 +- .../ParcelEngine/NativeEngineBackend.swift | 6 +- Sources/ParcelEngine/ParcelEngine.swift | 25 +++ .../AdaptiveLayoutRecoveryTests.swift | 19 +- .../AdaptiveUndoHistoryTests.swift | 20 +- .../ParcelCoreTests/CommandParityTests.swift | 15 +- Tests/ParcelCoreTests/CommandPixelTests.swift | 76 +++++++ Tests/ParcelCoreTests/CommandTests.swift | 48 +++-- Tests/ParcelCoreTests/DisplaySpaceTests.swift | 140 +++++++++++-- Tests/ParcelCoreTests/RoomFeedbackTests.swift | 55 ++--- Tests/ParcelCoreTests/UndoHistoryTests.swift | 2 +- .../WorkspaceCommandTests.swift | 28 ++- .../WorkspaceMemoryTests.swift | 10 +- .../ConfigurationAndDisplayTests.swift | 54 +++++ Tests/ParcelEngineTests/IPCTests.swift | 3 +- .../ParcelEngineTests/ParcelEngineTests.swift | 2 +- .../ReportDeliveryTests.swift | 190 ++++++++++++++++++ Tests/ParcelEngineTests/TestSupport.swift | 9 +- 30 files changed, 941 insertions(+), 140 deletions(-) diff --git a/Sources/ParcelCore/AdaptiveLayouts.swift b/Sources/ParcelCore/AdaptiveLayouts.swift index 00965f6e..04bdb188 100644 --- a/Sources/ParcelCore/AdaptiveLayouts.swift +++ b/Sources/ParcelCore/AdaptiveLayouts.swift @@ -53,7 +53,7 @@ extension TileTree { }) } - func updatingSurvivingFractions(from current: TileTree) -> TileTree { + func updatingSurvivingFractions(from current: TileTree, since projection: TileTree) -> TileTree { fold( { .tile($0) }, { node, first, second in @@ -62,19 +62,30 @@ extension TileTree { case .split(let axis, let fraction, let oldFirst, let oldSecond): return .split( axis: axis, - fraction: current.fraction(between: oldFirst.windows, and: oldSecond.windows, axis: axis) + fraction: current.changedFraction( + between: oldFirst.windows, and: oldSecond.windows, axis: axis, since: projection) ?? fraction, first: first, second: second) case .partition(let axis, let fraction, let oldFirst, let oldSecond): return .partition( axis: axis, - fraction: current.fraction(between: oldFirst.windows, and: oldSecond.windows, axis: axis) + fraction: current.changedFraction( + between: oldFirst.windows, and: oldSecond.windows, axis: axis, since: projection) ?? fraction, first: first, second: second) } }) } + private func changedFraction( + between left: [WindowID], and right: [WindowID], axis: Axis, since projection: TileTree + ) -> Double? { + guard let current = fraction(between: left, and: right, axis: axis), + let previous = projection.fraction(between: left, and: right, axis: axis), current != previous + else { return nil } + return current + } + private func fraction(between left: [WindowID], and right: [WindowID], axis: Axis) -> Double? { var pending = [self] while let node = pending.popLast() { @@ -156,7 +167,29 @@ extension Workspace { } var mainRatioPath: [TileEdge.Child] { - layoutVariant == .ultrawide && (tree?.tileCount ?? 0) >= 3 ? [.first] : [] + if layout == .side { + return layoutVariant == .ultrawide && (tree?.tileCount ?? 0) >= 3 ? [.first] : [] + } + var path: [TileEdge.Child] = [] + var node = tree + while let current = node { + switch current { + case .tile: return path + case .split(_, _, let first, _), .partition(_, _, let first, _): + if case .tile = first { return path } + path.append(.first) + node = first + } + } + return path + } + + var mainSizeRatio: Double { + guard layout != .accordion, let node = tree?.node(at: mainRatioPath[...]) else { return ratio.value } + switch node { + case .tile: return ratio.value + case .split(_, let fraction, _, _), .partition(_, let fraction, _, _): return fraction + } } func needsAdaptation(to screen: Rect, fullFrame: Rect) -> Bool { @@ -206,7 +239,7 @@ extension Workspace { adaptiveTileMemory = nil // An explicit rearrangement replaces the remembered grouping, never resurrects it. guard let tree, tree.hasSameTopology(as: memory.projection) else { return } - self.tree = memory.original.updatingSurvivingFractions(from: tree) + self.tree = memory.original.updatingSurvivingFractions(from: tree, since: memory.projection) for stack in tree.stacks { self.tree = self.tree?.mappingStacks { original in var selected = original diff --git a/Sources/ParcelCore/Commands.swift b/Sources/ParcelCore/Commands.swift index cc32c072..4f120406 100644 --- a/Sources/ParcelCore/Commands.swift +++ b/Sources/ParcelCore/Commands.swift @@ -79,27 +79,20 @@ extension State { workspace.changeLayout(layout) effects.append(.announce(.layoutChanged(layout))) case .setRatio(let ratio): - guard workspace.layout == .side else { - effects.append(.report(.unsupported)) - return - } workspace.changeRatio(ratio, effects: &effects) case .nudgeRatio(let delta): - guard workspace.layout == .side else { - effects.append(.report(.unsupported)) - return - } guard delta.isFinite else { effects.append(.report(.invalidRatio)) return } - let ratio = MainRatio(workspace.ratio.value + min(1, max(-1, delta))) - if ratio == workspace.ratio { - if delta > 0 { effects.append(.report(.maximumSizeReached)) } - if delta < 0 { effects.append(.report(.minimumSizeReached)) } + guard delta != 0 else { return } + let currentRatio = workspace.mainSizeRatio + let ratio = MainRatio(currentRatio + min(1, max(-1, delta))) + if delta > 0 ? ratio.value <= currentRatio : ratio.value >= currentRatio { + effects.append(.report(delta > 0 ? .maximumSizeReached : .minimumSizeReached)) return } - if workspace.layout == .side, (workspace.tree?.tileCount ?? 0) > 1, + if (workspace.tree?.tileCount ?? 0) > 1, let screen = displays[key.display]?.frame { let before = @@ -120,13 +113,7 @@ extension State { case .retile: workspace.rebuild(stacks: workspace.tree?.stacks ?? []) case .resetSizes: - workspace.tree = workspace.tree?.resettingSizes() - workspace.alternateSideTree = nil - workspace.changeRatio(workspace.configuredRatio) - if workspace.layoutVariant == .ultrawide && (workspace.tree?.tileCount ?? 0) >= 3 { - workspace.tree = workspace.tree?.replacingFraction(at: [], with: 0.75) - } - workspace.constrainTileCount() + workspace.resetSizes() effects.append(.announce(.sizesReset)) case .setWindowCap(let cap): guard Workspace.windowCapBounds.contains(cap) else { @@ -261,7 +248,7 @@ extension State { } let key = WorkspaceKey(display: display, space: space) let destination = workspaces[key] ?? newWorkspace(key) - if (destination.tree?.tileCount ?? 0) < destination.effectiveWindowCap || destination.whenFull == .stack { + if (destination.tree?.tileCount ?? 0) < destination.effectiveWindowCap { transfer(window, to: key, effects: &effects) focus(window, effects: &effects) effects.append(.announce(.movedToDisplay(window, display))) @@ -274,6 +261,11 @@ extension State { effects.append(.report(.noNeighbor(direction))) return } + if whenDisplayFull == .stack { + move(window, direction: direction, stacking: true, target: neighbor, effects: &effects) + effects.append(.announce(.movedToDisplay(window, display))) + return + } target = neighbor } guard let destination = workspace(containing: target) else { @@ -449,6 +441,31 @@ extension State { } extension Workspace { + mutating func resetSizes() { + let original = adaptiveTileMemory.flatMap { memory in + tree?.hasSameTopology(as: memory.projection) == true ? memory.original : nil + } + ratio = configuredRatio + alternateSideTree = nil + tree = tree.map { resettingSizes(of: $0) } + // Each slot count needs its own neutral geometry, including temporarily hidden tiles. + if let original, let projection = tree { + adaptiveTileMemory = AdaptiveTileMemory(original: resettingSizes(of: original), projection: projection) + } else { + adaptiveTileMemory = nil + } + } + + private func resettingSizes(of tree: TileTree) -> TileTree { + var resized = tree.resettingSizes() + guard layout == .side else { return resized } + let wide = layoutVariant == .ultrawide && tree.tileCount >= 3 + let path: [TileEdge.Child] = wide ? [.first] : [] + resized = resized.replacingFraction(at: path[...], with: configuredRatio.value) ?? resized + if wide { resized = resized.replacingFraction(at: [], with: 0.75) ?? resized } + return resized + } + public mutating func changeLayout(_ layout: Layout) { restoreAdaptiveTiles() layoutDefaults = nil @@ -466,9 +483,9 @@ extension Workspace { public mutating func changeRatio(_ ratio: MainRatio) { restoreAdaptiveTiles() self.ratio = ratio - if layout == .side { + if layout != .accordion { tree = tree?.replacingFraction(at: mainRatioPath[...], with: ratio.value) ?? tree - if let alternateSideTree { + if layout == .side, let alternateSideTree { let path: [TileEdge.Child] = layoutVariant != .ultrawide && alternateSideTree.tileCount >= 3 ? [.first] : [] self.alternateSideTree = diff --git a/Sources/ParcelCore/LayoutEngine.swift b/Sources/ParcelCore/LayoutEngine.swift index f7602d04..379c0a26 100644 --- a/Sources/ParcelCore/LayoutEngine.swift +++ b/Sources/ParcelCore/LayoutEngine.swift @@ -184,7 +184,9 @@ public enum LayoutEngine { let context = PlacementContext( gap: gap, outerTop: outerTop, outerBottom: outerBottom, windows: windows, workspace: workspace.key, topology: tree, - accordionFocus: focus, accordionWeight: Double(summaries[root].tileCount) * 4, + accordionFocus: focus, + accordionWeight: Double(summaries[root].tileCount) * 4 * workspace.ratio.value + / (1 - workspace.ratio.value), summaries: summaries, membership: membership) var placement = Placement( result: LayoutResult(visibleWindows: visible), edges: mode.collectingEdges ? [] : nil) diff --git a/Sources/ParcelCore/Model.swift b/Sources/ParcelCore/Model.swift index 1eeefc6c..27644c66 100644 --- a/Sources/ParcelCore/Model.swift +++ b/Sources/ParcelCore/Model.swift @@ -157,6 +157,10 @@ public enum Layout: String, Sendable, Equatable, Codable, CaseIterable { } } +public enum WhenDisplayFull: String, Sendable, Equatable, Codable, CaseIterable { + case swap, stack +} + public struct MainRatio: Sendable, Equatable, Codable { public let value: Double public static let half = MainRatio(1.0 / 2) diff --git a/Sources/ParcelCore/Reducer.swift b/Sources/ParcelCore/Reducer.swift index e6df9dd2..2c299ef1 100644 --- a/Sources/ParcelCore/Reducer.swift +++ b/Sources/ParcelCore/Reducer.swift @@ -26,6 +26,7 @@ package func reduce( var feedbackFrames = events.contains(where: \.isRetile) ? state.frames : nil var retileEvents: [Int] = [] var retileChanges: [WindowID: (event: Int, workspace: WorkspaceKey, frame: Rect)] = [:] + var observedInBatch: Set = [] var accepted = false var needsDiff = next.currentLayout == nil var closingNativeTabs: Set = [] @@ -75,6 +76,16 @@ package func reduce( if event.undoGestureTarget != nil { next.undoGesture?.operation = operation } } if feedbackFrames != nil { + if let window = event.observedWindow { + observedInBatch.insert(window) + retileChanges[window] = nil + } + if let key = event.retileReplacedWorkspace(in: next) { + for window in next.workspaces[key]?.tree?.windows ?? [] { + observedInBatch.insert(window) + retileChanges[window] = nil + } + } let layout = next.materializeLayout() retileChanges = retileChanges.filter { window, change in layout.frames[window] == change.frame && next.windows[window]?.isFloating == false @@ -83,7 +94,11 @@ package func reduce( if let key = retileKey { retileEvents.append(index) for window in retileWindows { - if let frame = layout.frames[window], frame != feedbackFrames?[window] { + if let frame = layout.frames[window], + frame != feedbackFrames?[window] + || (retileChanges[window] == nil && !observedInBatch.contains(window) + && frame == state.frames[window]) + { retileChanges[window] = (index, key, frame) } } @@ -136,19 +151,39 @@ package func reduce( effectsByEvent[0].insert(contentsOf: effects.filter { if case .setFrames = $0 { true } else { false } }, at: 0) effectsByEvent[events.count - 1].append( contentsOf: effects.filter { if case .setFrames = $0 { false } else { true } }) - var retileCounts: [Int: Int] = [:] - for write in writes { - if let change = retileChanges[write.window], change.frame == write.frame { - retileCounts[change.event, default: 0] += 1 - } + var retileCandidates: [Int: [WindowFrame]] = [:] + for (window, change) in retileChanges + where next.isActive(change.workspace) && desired.frames[window] == change.frame { + retileCandidates[change.event, default: []].append(WindowFrame(window: window, frame: change.frame)) } for index in retileEvents { - effectsByEvent[index].append(.report(.retiled(moved: retileCounts[index, default: 0]))) + effectsByEvent[index].append( + .confirmRetile(retileCandidates[index, default: []].sorted { $0.window < $1.window })) } return (next, effectsByEvent) } extension Event { + fileprivate var observedWindow: WindowID? { + switch self { + case .windowAppeared(let window, _, _): window.id + case .windowMovedByUser(let window, _), .windowResizedByUser(let window, _), .windowFrameEdited(let window, _), + .resolveRoom(let window, _, _): + window + default: nil + } + } + + fileprivate func retileReplacedWorkspace(in state: State) -> WorkspaceKey? { + switch self { + case .commandIssued(let command) where command != .retile && command.affectsWorkspace: + state.activeWorkspace + case .workspaceCommandIssued(let command, let key) where command != .retile && command.affectsWorkspace: + key + default: nil + } + } + fileprivate var isRetile: Bool { switch self { case .commandIssued(.retile), .workspaceCommandIssued(.retile, _): true diff --git a/Sources/ParcelCore/State.swift b/Sources/ParcelCore/State.swift index f649f9c0..54caf338 100644 --- a/Sources/ParcelCore/State.swift +++ b/Sources/ParcelCore/State.swift @@ -44,6 +44,7 @@ public struct State: Sendable, Equatable, Codable { public var minimizedPlacements: [WindowID: MinimizedPlacement]? public var cannotFit: [WindowID] private var hoverFocus: Bool? + private var displayFullPolicy: WhenDisplayFull? public var layoutDefaults: LayoutDefaults? public var displayLayoutDefaults: [DisplayID: LayoutDefaults]? private var windowWorkspace = StateCache<[WindowID: WorkspaceKey]>() @@ -55,6 +56,12 @@ public struct State: Sendable, Equatable, Codable { case windows, displays, activeSpaces, workspaces, activeDisplay, focusedWindow, activeMode, focusModes case frames, observedFrames, snapHistory, undoHistory, undoGesture, minimizedPlacements, cannotFit case hoverFocus, layoutDefaults, displayLayoutDefaults + case displayFullPolicy = "whenDisplayFull" + } + + public var whenDisplayFull: WhenDisplayFull { + get { displayFullPolicy ?? .swap } + set { displayFullPolicy = newValue == .swap ? nil : newValue } } public var hoverFocusEnabled: Bool { @@ -67,7 +74,8 @@ public struct State: Sendable, Equatable, Codable { workspaces: [WorkspaceKey: Workspace] = [:], windows: [WindowID: ManagedWindow] = [:], activeDisplay: DisplayID? = nil, focusedWindow: WindowID? = nil, frames: [WindowID: Rect] = [:], observedFrames: [WindowID: Rect] = [:], activeMode: String? = nil, - layoutDefaults: LayoutDefaults = LayoutDefaults(), displayLayoutDefaults: [DisplayID: LayoutDefaults] = [:] + layoutDefaults: LayoutDefaults = LayoutDefaults(), displayLayoutDefaults: [DisplayID: LayoutDefaults] = [:], + whenDisplayFull: WhenDisplayFull = .swap ) { self.displays = Dictionary(uniqueKeysWithValues: displays.map { ($0.id, $0) }) self.activeSpaces = activeSpaces @@ -85,6 +93,7 @@ public struct State: Sendable, Equatable, Codable { minimizedPlacements = nil cannotFit = [] hoverFocus = nil + displayFullPolicy = whenDisplayFull == .swap ? nil : whenDisplayFull self.layoutDefaults = layoutDefaults self.displayLayoutDefaults = displayLayoutDefaults for display in displays { @@ -102,6 +111,32 @@ public struct State: Sendable, Equatable, Codable { } } + public init(from decoder: any Decoder) throws { + let values = try decoder.container(keyedBy: CodingKeys.self) + windows = try values.decode([WindowID: ManagedWindow].self, forKey: .windows) + displays = try values.decode([DisplayID: Display].self, forKey: .displays) + activeSpaces = try values.decode([DisplayID: SpaceID].self, forKey: .activeSpaces) + workspaces = try values.decode([WorkspaceKey: Workspace].self, forKey: .workspaces) + activeDisplay = try values.decodeIfPresent(DisplayID.self, forKey: .activeDisplay) + focusedWindow = try values.decodeIfPresent(WindowID.self, forKey: .focusedWindow) + activeMode = try values.decodeIfPresent(String.self, forKey: .activeMode) + focusModes = try values.decodeIfPresent([WorkspaceKey: FocusModes].self, forKey: .focusModes) + frames = try values.decode([WindowID: Rect].self, forKey: .frames) + observedFrames = try values.decode([WindowID: Rect].self, forKey: .observedFrames) + snapHistory = try values.decodeIfPresent([WindowID: SnapHistory].self, forKey: .snapHistory) + undoHistory = try values.decodeIfPresent(UndoHistory.self, forKey: .undoHistory) + undoGesture = try values.decodeIfPresent(UndoGesture.self, forKey: .undoGesture) + minimizedPlacements = try values.decodeIfPresent( + [WindowID: MinimizedPlacement].self, forKey: .minimizedPlacements) + cannotFit = try values.decode([WindowID].self, forKey: .cannotFit) + hoverFocus = try values.decodeIfPresent(Bool.self, forKey: .hoverFocus) + layoutDefaults = try values.decodeIfPresent(LayoutDefaults.self, forKey: .layoutDefaults) + displayLayoutDefaults = try values.decodeIfPresent( + [DisplayID: LayoutDefaults].self, forKey: .displayLayoutDefaults) + let policy = try values.decodeIfPresent(WhenDisplayFull.self, forKey: .displayFullPolicy) ?? .swap + displayFullPolicy = policy == .swap ? nil : policy + } + public var activeWorkspace: WorkspaceKey? { guard let display = activeDisplay, let space = activeSpaces[display] else { return nil } return WorkspaceKey(display: display, space: space) @@ -381,6 +416,8 @@ public enum Report: Sendable, Equatable, Codable { public enum Effect: Sendable, Equatable, Codable { case setFrames([WindowFrame]) + /// Candidates for read-back confirmation, not a count of successful movement. + case confirmRetile([WindowFrame]) case focusWindow(WindowID) case raiseWindow(WindowID) case closeWindow(WindowID) diff --git a/Sources/ParcelCore/WorkspaceMemory.swift b/Sources/ParcelCore/WorkspaceMemory.swift index 064175bf..16280811 100644 --- a/Sources/ParcelCore/WorkspaceMemory.swift +++ b/Sources/ParcelCore/WorkspaceMemory.swift @@ -542,7 +542,13 @@ extension Workspace { var result = self if result.layout != saved.layout { result.changeLayout(saved.layout) } result.layoutDefaults = saved.layoutDefaults - if result.ratio != saved.ratio { result.changeRatio(saved.ratio) } + if result.ratio != saved.ratio { + if result.layout == .side { + result.changeRatio(saved.ratio) + } else { + result.ratio = saved.ratio + } + } result.configuredRatio = saved.configuredRatio result.gaps = saved.gaps result.reservedEdges = saved.reservedEdges diff --git a/Sources/ParcelEngine/EngineConfiguration.swift b/Sources/ParcelEngine/EngineConfiguration.swift index 2eca0571..35691d89 100644 --- a/Sources/ParcelEngine/EngineConfiguration.swift +++ b/Sources/ParcelEngine/EngineConfiguration.swift @@ -88,6 +88,11 @@ struct AppliedConfiguration { } func installLayoutDefaults(in state: inout State) { + if !value.general.shortcutsEnabled { state.activeMode = nil } + switch value.general.whenDisplayFull { + case .swap: state.whenDisplayFull = .swap + case .stack: state.whenDisplayFull = .stack + } state.layoutDefaults = layoutDefaults(value.layout.global) state.displayLayoutDefaults = Dictionary( uniqueKeysWithValues: value.layout.displays.map { diff --git a/Sources/ParcelEngine/EngineEffects.swift b/Sources/ParcelEngine/EngineEffects.swift index 34c84587..28c19d67 100644 --- a/Sources/ParcelEngine/EngineEffects.swift +++ b/Sources/ParcelEngine/EngineEffects.swift @@ -2,12 +2,17 @@ import Foundation import ParcelAnimation import ParcelCore +private enum RetileVerificationFailure: Error { + case missingBaseline(WindowID) + case missingFinalFrame(WindowID) +} + extension ParcelEngine { func execute(_ effects: [Effect]) { var raised: Set = [] for effect in effects { switch effect { - case .setFrames, .closeWindow, .toggleFullscreen, .saveFloatingRule, .undoLastRule: break + case .setFrames, .confirmRetile, .closeWindow, .toggleFullscreen, .saveFloatingRule, .undoLastRule: break case .focusWindow(let window): guard snapshot.focusedWindow == window else { continue } focusEffect(window, raise: false) @@ -61,6 +66,26 @@ extension ParcelEngine { } let result = EngineCommandResult( revision: revision, reports: reports, isAccepted: !reports.contains(where: \.isFailure)) + 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 + retileCompletions[id] = RetileCompletion( + order: retileCompletionOrder, pending: pending, result: result, + 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) @@ -141,6 +166,13 @@ extension ParcelEngine { } func cancelMotion(_ window: WindowID, remove: Bool) { + for id in retileCompletions.keys { + if let candidate = retileCompletions[id]?.windows[window], candidate.generation != nil, + candidate.finalFrame == nil + { + 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) } @@ -181,7 +213,102 @@ extension ParcelEngine { } } + 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 } + 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 completions = retileCompletions.values.sorted { $0.order < $1.order } + retileCompletions.removeAll() + for completion in completions { + 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 { + guard let initial = $0.initialFrame, let final = $0.finalFrame else { return false } + return initial != final + }.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.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) diff --git a/Sources/ParcelEngine/EngineEvents.swift b/Sources/ParcelEngine/EngineEvents.swift index 9e9a9157..fd3441f7 100644 --- a/Sources/ParcelEngine/EngineEvents.swift +++ b/Sources/ParcelEngine/EngineEvents.swift @@ -201,6 +201,7 @@ extension ParcelEngine { markWorkspaceMemoryChanges(previous: state, next: next, events: events) let effects = effectsByEvent.flatMap { $0 } updateWindowManagement() + continueRetileCorrections(acceptedEvents) pruneMotion() for (index, effects) in effectsByEvent.enumerated() { let command = index < pending.count ? pending[index] : nil @@ -218,7 +219,12 @@ extension ParcelEngine { for window in manual { manualCommandFrames[window] = next.frames[window] } } if let transaction { trace?.begin(.plan, transaction: transaction) } - planFrames(manualWindows: manual) + let retileWindows = Set( + effects.flatMap { effect -> [WindowID] in + if case .confirmRetile(let candidates) = effect { return candidates.map(\.window) } + return [] + }) + planFrames(manualWindows: manual.union(retileWindows)) rememberWorkspaceState() if let transaction { trace?.end(.plan, transaction: transaction) @@ -300,7 +306,6 @@ extension ParcelEngine { frameAdjustments[window] = nil if command == .retile { if state.windows[window]?.isFloating == false { - actualFrames[window] = nil targets[window] = nil } attemptedRuleSpaces[window] = nil @@ -310,7 +315,6 @@ extension ParcelEngine { case .commandIssued(.retile): if let key = state.activeWorkspace { for window in state.workspaces[key]?.order ?? [] where state.windows[window]?.isFloating == false { - actualFrames[window] = nil targets[window] = nil } } diff --git a/Sources/ParcelEngine/EngineIPCHandler.swift b/Sources/ParcelEngine/EngineIPCHandler.swift index e5d8550e..c3df0b6d 100644 --- a/Sources/ParcelEngine/EngineIPCHandler.swift +++ b/Sources/ParcelEngine/EngineIPCHandler.swift @@ -195,6 +195,8 @@ public final class EngineIPCHandler: IPCHandler { "active_mode": state.activeMode.map(JSONValue.string) ?? .null, "hover_focus": .bool(state.hoverFocusEnabled), "automatic_tiling": .bool(engine.isAutomaticTilingEnabled), + "shortcuts_enabled": .bool(engine.configuration.general.shortcutsEnabled), + "when_display_full": .string(state.whenDisplayFull.rawValue), "focus-modes": .object([ "no-peek-level": .number(engine.configuration.focusModes.noPeekLevel), "no-peek-blur": .bool(engine.configuration.focusModes.noPeekBlur), diff --git a/Sources/ParcelEngine/EngineInterfaces.swift b/Sources/ParcelEngine/EngineInterfaces.swift index 36d22e92..1e8b131b 100644 --- a/Sources/ParcelEngine/EngineInterfaces.swift +++ b/Sources/ParcelEngine/EngineInterfaces.swift @@ -119,17 +119,24 @@ public struct EngineFrameWrite: Sendable, Equatable { public let transaction: UInt64 public let generation: UInt64 public let isFinal: Bool + public let capturesInitialFrame: Bool - public init(window: WindowID, frame: Rect, transaction: UInt64, generation: UInt64 = 0, isFinal: Bool = true) { + public init( + window: WindowID, frame: Rect, transaction: UInt64, generation: UInt64 = 0, isFinal: Bool = true, + capturesInitialFrame: Bool = false + ) { self.window = window self.frame = frame self.transaction = transaction self.generation = generation self.isFinal = isFinal + self.capturesInitialFrame = capturesInitialFrame } } public struct EngineWriteReceipt: Sendable { + /// Fresh window-server frames captured before the first tracked write. + public let initialFrames: [WindowFrame] public let frames: [WindowFrame] public let failures: [EnginePlatformFailure] public let duration: Double @@ -137,9 +144,10 @@ public struct EngineWriteReceipt: Sendable { public init( frames: [WindowFrame], failures: [EnginePlatformFailure] = [], duration: Double, - writtenWindowCount: Int? = nil + writtenWindowCount: Int? = nil, initialFrames: [WindowFrame] = [] ) { precondition(writtenWindowCount == nil || writtenWindowCount.map { $0 > 0 } == true) + self.initialFrames = initialFrames self.frames = frames self.failures = failures self.duration = duration diff --git a/Sources/ParcelEngine/EngineMotion.swift b/Sources/ParcelEngine/EngineMotion.swift index 5328c0dc..98ef7300 100644 --- a/Sources/ParcelEngine/EngineMotion.swift +++ b/Sources/ParcelEngine/EngineMotion.swift @@ -151,6 +151,7 @@ extension ParcelEngine { } func rememberMotionPlan(_ plan: FramePlan, window: WindowID) { + bindRetile(window, plan: plan) nextMotionPlan += 1 motionPlans[window] = EngineFocusMotionPlan(id: nextMotionPlan, plan: plan) dispatchedMotionTimes[window] = nil @@ -324,7 +325,8 @@ extension ParcelEngine { rememberEcho(window, frame: rect, transaction: batch.identifier, generation: frame.generation) return EngineFrameWrite( window: window, frame: rect, transaction: batch.identifier, - generation: frame.generation, isFinal: frame.isFinal) + generation: frame.generation, isFinal: frame.isFinal, + capturesInitialFrame: capturesRetileBaseline(window, sent: frame)) } let generation = lifetime if writes.isEmpty { @@ -386,10 +388,17 @@ extension ParcelEngine { } busyApps.remove(batch.appID) activeBatches[batch.appID] = nil + for initial in receipt.initialFrames { + guard let sent = batch.frames.first(where: { $0.windowID == initial.window.motionID }), + coalescer.generation(for: sent.windowID) == sent.generation + else { continue } + acceptRetileBaseline(initial, sent: sent) + } for observed in receipt.frames { guard let sent = batch.frames.first(where: { $0.windowID == observed.window.motionID }), coalescer.generation(for: sent.windowID) == sent.generation else { continue } + acceptRetileReadback(observed, sent: sent) acceptReadback(observed, sent: sent) if sent.isFinal, !liveResizeWindows.contains(observed.window), let app = snapshot.state.windows[observed.window]?.app diff --git a/Sources/ParcelEngine/NativeEngineBackend.swift b/Sources/ParcelEngine/NativeEngineBackend.swift index 30c5a270..09006186 100644 --- a/Sources/ParcelEngine/NativeEngineBackend.swift +++ b/Sources/ParcelEngine/NativeEngineBackend.swift @@ -427,6 +427,10 @@ private final class SystemNativeEngineApplication: NativeEngineApplication { func acknowledgeMotion(_ window: UInt32) { thread.acknowledgeMotion(windowID: window) } func writeFrames(_ frames: [EngineFrameWrite]) async throws -> EngineWriteReceipt { + var initialFrames: [WindowFrame] = [] + for request in frames where request.capturesInitialFrame { + initialFrames.append(WindowFrame(window: request.window, frame: try await frame(request.window))) + } let receipt = try await thread.writeFrames( frames.map { AppThreadFrameWrite( @@ -517,7 +521,7 @@ private final class SystemNativeEngineApplication: NativeEngineApplication { failures += receipt.cleanupErrors.map { NativeEngineWorld.failure($0, app: app) } return EngineWriteReceipt( frames: actual, failures: failures, duration: duration, - writtenWindowCount: receipt.windows.isEmpty ? nil : receipt.windows.count) + writtenWindowCount: receipt.windows.isEmpty ? nil : receipt.windows.count, initialFrames: initialFrames) } func cancelFrameWrites(_ window: WindowID, throughGeneration: UInt64) async throws { diff --git a/Sources/ParcelEngine/ParcelEngine.swift b/Sources/ParcelEngine/ParcelEngine.swift index f65a22f3..4c6f8ee2 100644 --- a/Sources/ParcelEngine/ParcelEngine.swift +++ b/Sources/ParcelEngine/ParcelEngine.swift @@ -165,6 +165,21 @@ public final class ParcelEngine { let reply: CheckedContinuation? let windows: Set } + struct RetileWindow { + var target: Rect + var generation: UInt64? + var revision: UInt64? + var initialFrame: Rect? + var finalFrame: Rect? + } + struct RetileCompletion { + let order: UInt64 + let pending: Pending? + let result: EngineCommandResult + var windows: [WindowID: RetileWindow] + } + var retileCompletionOrder: UInt64 = 0 + var retileCompletions: [UUID: RetileCompletion] = [:] var windowOperations: [UUID: WindowOperation] = [:] var operatingWindows: Set { Set(windowOperations.values.flatMap(\.windows)) } var pumping = false @@ -372,6 +387,8 @@ public final class ParcelEngine { onMouseFeedback?(.targetChanged(nil)) pointerIsDown = false focusOperations = 0 + for completion in retileCompletions.values { completion.pending?.reply?.resume(throwing: EngineError.stopped) } + retileCompletions.removeAll() for operation in windowOperations.values { operation.task.cancel() operation.reply?.resume(throwing: EngineError.stopped) @@ -399,6 +416,8 @@ public final class ParcelEngine { } isolated deinit { + for completion in retileCompletions.values { completion.pending?.reply?.resume(throwing: EngineError.stopped) } + retileCompletions.removeAll() for operation in windowOperations.values { operation.task.cancel() operation.reply?.resume(throwing: EngineError.stopped) @@ -506,6 +525,11 @@ extension ParcelEngine { } func cancelCommand(_ id: UUID) { + if let completion = retileCompletions.removeValue(forKey: id) { + completion.pending?.reply?.resume(throwing: CancellationError()) + settleIfIdle() + return + } if let operation = windowOperations[id] { operation.task.cancel() operation.reply?.resume(throwing: CancellationError()) @@ -651,6 +675,7 @@ extension ParcelEngine { } func settleIfIdle() { + finishRetilesIfSettled() resolveWorkspaceWaiters() if !settlingTraces.isEmpty, !pumping, animators.values.allSatisfy(\.isIdle), coalescer.pendingCount == 0, coalescer.inFlightCount == 0 diff --git a/Tests/ParcelCoreTests/AdaptiveLayoutRecoveryTests.swift b/Tests/ParcelCoreTests/AdaptiveLayoutRecoveryTests.swift index 633a3677..e23ec1d2 100644 --- a/Tests/ParcelCoreTests/AdaptiveLayoutRecoveryTests.swift +++ b/Tests/ParcelCoreTests/AdaptiveLayoutRecoveryTests.swift @@ -143,13 +143,18 @@ import Testing #expect(state.workspaces[next]?.layout == .side) } - @Test(arguments: Layout.allCases.filter { $0 != .side }) - func mainSizeCommandsExplainUnsupportedLayouts(layout: Layout) { - let state = makeState(layout, count: 2, screen: landscape) - for command in [Command.setRatio(.threeFifths), .nudgeRatio(0.05)] { - let result = reduce(state, .commandIssued(command)) - #expect(result.0 == state) - #expect(result.1 == [.report(.unsupported)]) + @Test(arguments: Layout.allCases, [Command.setRatio(.threeFifths), .nudgeRatio(0.05)]) + func mainSizeCommandsWorkAcrossLayoutsAndDisplayOrientations(layout: Layout, action: Command) throws { + for screen in [landscape, portrait, wide] { + let state = focused(1, in: makeState(layout, count: 2, screen: screen)) + let before = try #require(state.frames[windowID(1)]) + let result = reduce(state, .commandIssued(action)) + let after = try #require(result.0.frames[windowID(1)]) + #expect(after.size.width * after.size.height > before.size.width * before.size.height) + #expect(result.0.workspaces[primaryKey]?.layout == layout) + #expect(result.0.workspaces[primaryKey]?.order == state.workspaces[primaryKey]?.order) + #expect(!result.1.contains(.report(.unsupported))) + #expect(command(.resetSizes, in: result.0).0.frames == state.frames) } } diff --git a/Tests/ParcelCoreTests/AdaptiveUndoHistoryTests.swift b/Tests/ParcelCoreTests/AdaptiveUndoHistoryTests.swift index ef1dcb9b..72355373 100644 --- a/Tests/ParcelCoreTests/AdaptiveUndoHistoryTests.swift +++ b/Tests/ParcelCoreTests/AdaptiveUndoHistoryTests.swift @@ -241,15 +241,21 @@ import Testing } } - @Test(arguments: [Layout.columns, .rows]) - func unsupportedRatioCommandsDoNotRecordHistory(layout: Layout) { + @Test(arguments: Layout.allCases, [Command.setRatio(.threeFifths), .nudgeRatio(0.1)]) + func mainSizeCommandsRecordUndoableHistoryInEveryLayout(layout: Layout, action: Command) { var before = focused(1, in: populated(2, layout: layout)) before.undoHistory = nil - for action in [Command.setRatio(.threeFifths), .nudgeRatio(0.1)] { - let result = command(action, in: before) - #expect(result.1 == [.report(.unsupported)]) - #expect(result.0.undoHistory == nil) - #expect(result.0.workspaces[primaryKey]?.ratio == .half) + let result = command(action, in: before) + #expect(result.1.contains(.announce(.ratioChanged(.threeFifths)))) + #expect(result.0.workspaces[primaryKey]?.ratio == .threeFifths) + #expect(result.0.frames != before.frames) + #expect(result.0.workspaces[primaryKey]?.order == before.workspaces[primaryKey]?.order) + for window in [1, 2] { + #expect(result.0.undoHistory?.count(for: windowID(window)) == 1) + let restored = command(.undo, in: focused(window, in: result.0)).0 + #expect(restored.frames == focused(window, in: before).frames) + #expect(restored.workspaces[primaryKey]?.ratio == .half) + #expect(restored.workspaces[primaryKey]?.layout == layout) } } } diff --git a/Tests/ParcelCoreTests/CommandParityTests.swift b/Tests/ParcelCoreTests/CommandParityTests.swift index 3b504b3a..98449bda 100644 --- a/Tests/ParcelCoreTests/CommandParityTests.swift +++ b/Tests/ParcelCoreTests/CommandParityTests.swift @@ -130,23 +130,24 @@ struct CommandParityTests { #expect(command(.resetSizes, in: State()).1 == [.report(.noActiveWorkspace)]) } - @Test(arguments: [false, true]) - func ratioLimitReportsDoNotWriteOrAnnounce(upper: Bool) { - let state = command(.setRatio(MainRatio(upper ? 0.8 : 0.2)), in: populated(2, layout: .side)).0 + @Test(arguments: [false, true], Layout.allCases) + func ratioLimitReportsDoNotWriteOrAnnounce(upper: Bool, layout: Layout) { + let state = command(.setRatio(MainRatio(upper ? 0.8 : 0.2)), in: populated(2, layout: layout)).0 let result = command(.nudgeRatio(upper ? 0.05 : -0.05), in: state) #expect(result.0 == state) #expect(result.1 == [.report(upper ? .maximumSizeReached : .minimumSizeReached)]) #expect(command(.nudgeRatio(0), in: state).1.isEmpty) } - @Test(arguments: [false, true]) - func learnedMinimumPreventsRatioNudgeAtPhysicalLimit(upper: Bool) { - var state = populated(2, layout: .side) + @Test(arguments: [false, true], Layout.allCases) + func learnedMinimumPreventsRatioNudgeAtPhysicalLimit(upper: Bool, layout: Layout) throws { + var state = focused(1, in: populated(2, layout: layout)) let constrained = windowID(upper ? 2 : 1) + let minimum = try #require(state.frames[constrained]).size state = reduce( state, - .minimumSizeChanged(constrained, minimum: LearnedMinimumSize(size: Size(width: 600, height: 100))) + .minimumSizeChanged(constrained, minimum: LearnedMinimumSize(size: minimum)) ).0 let result = command(.nudgeRatio(upper ? 0.05 : -0.05), in: state) #expect(result.0 == state) diff --git a/Tests/ParcelCoreTests/CommandPixelTests.swift b/Tests/ParcelCoreTests/CommandPixelTests.swift index 45755cf9..08c51834 100644 --- a/Tests/ParcelCoreTests/CommandPixelTests.swift +++ b/Tests/ParcelCoreTests/CommandPixelTests.swift @@ -75,6 +75,82 @@ func swapsHaveExactFramesInCanonicalLayouts(layout: Layout, direction: Direction #expect(frameWrites(result.1) == writes) } +@Test func threeColumnNudgesUseTheActualMainDividerAndResetToEqualWidths() { + let state = focused(3, in: populated(3, layout: .columns)) + let grown = command(.nudgeRatio(0.05), in: state) + #expect(grown.0.frames[windowID(1)] == Rect(width: 460, height: 800)) + #expect(grown.0.frames[windowID(2)] == Rect(x: 460, width: 370, height: 800)) + #expect(grown.0.frames[windowID(3)] == Rect(x: 830, width: 370, height: 800)) + #expect(grown.0.focusedWindow == windowID(3)) + let inverse = command(.nudgeRatio(-0.05), in: grown.0) + #expect(inverse.0.frames == state.frames) + #expect(command(.resetSizes, in: grown.0).0.frames == state.frames) + let preset = command(.setRatio(.threeFifths), in: state).0 + #expect(preset.frames[windowID(1)] == Rect(width: 720, height: 800)) + let nudgedPreset = command(.nudgeRatio(0.05), in: preset).0 + #expect(nudgedPreset.frames[windowID(1)] == Rect(width: 780, height: 800)) + #expect(command(.resetSizes, in: nudgedPreset).0.frames == state.frames) +} + +@Test(arguments: Layout.allCases) +func sizeNudgesGrowShrinkAndResetWithoutChangingMembership(layout: Layout) throws { + let initial = focused(layout == .accordion ? 3 : 2, in: populated(3, layout: layout)) + let state = command(.resetSizes, in: initial).0 + let main = windowID(layout == .accordion ? 3 : 1) + let before = try #require(state.frames[main]) + let grown = command(.nudgeRatio(0.05), in: state) + let larger = try #require(grown.0.frames[main]) + let shrunk = command(.nudgeRatio(-0.05), in: state) + let smaller = try #require(shrunk.0.frames[main]) + #expect(larger.size.width * larger.size.height > before.size.width * before.size.height) + #expect(smaller.size.width * smaller.size.height < before.size.width * before.size.height) + for result in [grown, shrunk] { + #expect(result.0.focusedWindow == state.focusedWindow) + #expect(result.0.workspaces[primaryKey]?.layout == layout) + #expect(result.0.workspaces[primaryKey]?.order == state.workspaces[primaryKey]?.order) + #expect(result.0.workspaces[primaryKey]?.openingOrder == state.workspaces[primaryKey]?.openingOrder) + #expect(Set(result.0.frames.keys) == Set(state.frames.keys)) + #expect(!frameWrites(result.1).isEmpty) + #expect(command(.resetSizes, in: result.0).0.frames == state.frames) + #expect(command(.undo, in: result.0).0.frames == state.frames) + } + #expect(command(.nudgeRatio(-0.05), in: grown.0).0.frames == state.frames) + #expect(command(.nudgeRatio(0), in: state).0 == state) + #expect(command(.nudgeRatio(0), in: state).1.isEmpty) +} + +@Test func cappedRowsResetBothVisibleAndHiddenSizesAndRetainLaterMainSizeEdits() { + let initial = focused(2, in: populated(3, layout: .rows)) + let state = command(.resetSizes, in: initial).0 + #expect(state.workspaces[primaryKey]?.visibleWindows.count == 2) + #expect(state.frames[windowID(1)] == Rect(width: 1200, height: 400)) + let grown = command(.nudgeRatio(0.05), in: state).0 + let reset = command(.resetSizes, in: grown).0 + #expect(reset.frames == state.frames) + #expect(reset.workspaces[primaryKey]?.visibleWindows == state.workspaces[primaryKey]?.visibleWindows) + #expect(reset.workspaces[primaryKey]?.order == state.workspaces[primaryKey]?.order) + let expanded = command(.setWindowCap(0), in: reset).0 + #expect(expanded.workspaces[primaryKey]?.visibleWindows.count == 3) + #expect(expanded.frames == command(.setWindowCap(0), in: initial).0.frames) + let edited = command(.nudgeRatio(0.05), in: reset).0 + let expandedEdit = command(.setWindowCap(0), in: edited).0 + #expect(expandedEdit.frames[windowID(1)] == edited.frames[windowID(1)]) + #expect(expandedEdit.frames[windowID(1)] == Rect(width: 1200, height: 440)) + #expect(expandedEdit.frames[windowID(2)] == Rect(y: 440, width: 1200, height: 180)) + #expect(expandedEdit.frames[windowID(3)] == Rect(y: 620, width: 1200, height: 180)) +} + +@Test(arguments: [Layout.grid, .tree, .bsp]) +func mainSizeNudgesLeaveOtherRowsUnchanged(layout: Layout) { + let state = focused(4, in: populated(4, layout: layout)) + let result = command(.nudgeRatio(0.1), in: state) + #expect(result.0.frames[windowID(1)] == Rect(width: 720, height: 400)) + #expect(result.0.frames[windowID(2)] == Rect(x: 720, width: 480, height: 400)) + #expect(result.0.frames[windowID(3)] == state.frames[windowID(3)]) + #expect(result.0.frames[windowID(4)] == state.frames[windowID(4)]) + #expect(result.0.focusedWindow == windowID(4)) +} + private func movedFourFrames(_ layout: Layout, _ direction: Direction) -> [WindowID: Rect] { var frames = fourFrames(layout) switch (layout, direction) { diff --git a/Tests/ParcelCoreTests/CommandTests.swift b/Tests/ParcelCoreTests/CommandTests.swift index 2d345775..1d6b9d65 100644 --- a/Tests/ParcelCoreTests/CommandTests.swift +++ b/Tests/ParcelCoreTests/CommandTests.swift @@ -149,11 +149,20 @@ func setLayoutBalancesWithoutChangingMembership(layout: Layout) { #expect(result.1.contains(.announce(.ratioChanged(.threeFifths)))) } -@Test func ratioOutsideSideIsReportedWithoutMutation() { - let state = populated() +@Test(arguments: Layout.allCases) +func setRatioResizesMainWindowWithoutChangingLayout(layout: Layout) throws { + let state = focused(1, in: populated(3, layout: layout)) + let before = try #require(state.frames[windowID(1)]) let result = command(.setRatio(.twoThirds), in: state) - #expect(result.0 == state) - #expect(result.1 == [.report(.unsupported)]) + let after = try #require(result.0.frames[windowID(1)]) + #expect(after.size.width * after.size.height > before.size.width * before.size.height) + #expect(result.0.workspaces[primaryKey]?.layout == layout) + #expect(result.0.workspaces[primaryKey]?.order == state.workspaces[primaryKey]?.order) + #expect(result.0.workspaces[primaryKey]?.openingOrder == state.workspaces[primaryKey]?.openingOrder) + #expect(result.0.workspaces[primaryKey]?.visibleWindows == state.workspaces[primaryKey]?.visibleWindows) + #expect(result.0.focusedWindow == windowID(1)) + #expect(result.1.contains(.announce(.ratioChanged(.twoThirds)))) + #expect(command(.setRatio(.twoThirds), in: result.0).0 == result.0) } @Test func nudgeRatioMovesDivider() { @@ -167,15 +176,17 @@ func setLayoutBalancesWithoutChangingMembership(layout: Layout) { ]) } -@Test func nudgeRatioClampsBothBounds() { - let state = populated(2, layout: .side) +@Test(arguments: Layout.allCases) +func nudgeRatioClampsBothBounds(layout: Layout) { + let state = populated(2, layout: layout) #expect(command(.nudgeRatio(10), in: state).0.workspaces[primaryKey]?.ratio.value == 0.8) #expect(command(.nudgeRatio(-10), in: state).0.workspaces[primaryKey]?.ratio.value == 0.2) } -@Test func nonFiniteNudgeIsReported() { - let state = populated(2, layout: .side) - let result = command(.nudgeRatio(.nan), in: state) +@Test(arguments: Layout.allCases, [Double.nan, .infinity, -.infinity]) +func nonFiniteNudgeIsReported(layout: Layout, delta: Double) { + let state = populated(2, layout: layout) + let result = command(.nudgeRatio(delta), in: state) #expect(result.0 == state) #expect(result.1 == [.report(.invalidRatio)]) } @@ -197,7 +208,7 @@ func setLayoutBalancesWithoutChangingMembership(layout: Layout) { #expect(result.0.frames[windowID(2)] == Rect(x: 800, width: 400, height: 800)) } -@Test func retileBalancesIncrementalSplitsAndReportsCount() { +@Test func retileBalancesIncrementalSplitsAndRequestsReadbackConfirmation() { var state = populated(0) for number in 1...3 { state = @@ -206,12 +217,23 @@ func setLayoutBalancesWithoutChangingMembership(layout: Layout) { } let result = command(.retile, in: state) #expect(result.0.frames[windowID(1)] == Rect(width: 400, height: 800)) - #expect(result.1.contains(.report(.retiled(moved: 3)))) + #expect( + result.1.contains( + .confirmRetile( + (1...3).map { + WindowFrame(window: windowID($0), frame: result.0.frames[windowID($0)]!) + }))) } -@Test func noOpRetileReportsZeroAndDoesNotWrite() { +@Test func cachedRetileRequestsRevalidationWithoutPlanningWritesOrGuessingMovement() { let result = command(.retile, in: populated()) - #expect(result.1 == [.report(.retiled(moved: 0))]) + #expect( + result.1 == [ + .confirmRetile( + (1...3).map { + WindowFrame(window: windowID($0), frame: result.0.frames[windowID($0)]!) + }) + ]) } @Test func stackJoinsDirectionalNeighborAndMakesFocusVisible() { diff --git a/Tests/ParcelCoreTests/DisplaySpaceTests.swift b/Tests/ParcelCoreTests/DisplaySpaceTests.swift index a3dc0816..50ace1f1 100644 --- a/Tests/ParcelCoreTests/DisplaySpaceTests.swift +++ b/Tests/ParcelCoreTests/DisplaySpaceTests.swift @@ -1,3 +1,4 @@ +import Foundation import Testing @testable import ParcelCore @@ -74,16 +75,96 @@ func moveToDisplayUsesGlobalGeometry(direction: Direction) { #expect(result.1 == [.report(.noNeighbor(.right))]) } -@Test func swapAcrossFullDisplaysKeepsEachTileCount() { - var state = focused(2, in: multipleDisplays(destinationCap: 2)) - state.workspaces[secondaryKey]?.whenFull = .float +@Test(arguments: Direction.allCases, WhenFull.allCases) +func swapAcrossFullDisplaysKeepsEachWindowCount(direction: Direction, overflow: WhenFull) { + let source = windowID(direction == .right ? 2 : 1) + let target = windowID(direction == .left ? 4 : 3) + var state = focused(Int(source.rawValue), in: multipleDisplays(direction, destinationCap: 2)) + state.workspaces[secondaryKey]?.whenFull = overflow + let result = command(.swap(direction), in: state) + #expect(result.0.workspace(containing: source) == secondaryKey) + #expect(result.0.workspace(containing: target) == primaryKey) + for key in [primaryKey, secondaryKey] { + #expect(result.0.workspaces[key]?.order.count == state.workspaces[key]?.order.count) + #expect(result.0.workspaces[key]?.tree?.tileCount == 2) + #expect(result.0.workspaces[key]?.layout == state.workspaces[key]?.layout) + #expect(result.0.workspaces[key]?.whenFull == state.workspaces[key]?.whenFull) + } + #expect(result.0.frames[source] == state.frames[target]) + #expect(result.0.frames[target] == state.frames[source]) + #expect(result.0.focusedWindow == source) + #expect(result.0.activeDisplay == secondaryDisplay) +} + +@Test(arguments: WhenDisplayFull.allCases) +func edgeSwapKeepsHiddenStackMembersOnTheirOriginalDisplay(policy: WhenDisplayFull) { + var state = multipleDisplays(destinationCap: 2) + state = command(.setWindowCap(2), in: state).0 + state = reduce(focused(2, in: state), .windowAppeared(managed(5), workspace: primaryKey, frame: Rect())).0 + state = command(.stack(.left), in: focused(4, in: state)).0 + state = command(.setWindowCap(1), in: state).0 + state = focused(2, in: state) + state.whenDisplayFull = policy let result = command(.swap(.right), in: state) #expect(result.0.workspace(containing: windowID(2)) == secondaryKey) - #expect(result.0.workspace(containing: windowID(3)) == primaryKey) - #expect(result.0.workspaces[primaryKey]?.tree?.tileCount == 2) - #expect(result.0.workspaces[secondaryKey]?.tree?.tileCount == 2) - #expect(result.0.frames[windowID(2)] == state.frames[windowID(3)]) - #expect(result.0.frames[windowID(3)] == state.frames[windowID(2)]) + #expect(result.0.workspace(containing: windowID(5)) == primaryKey) + #expect(result.0.workspace(containing: windowID(3)) == secondaryKey) + #expect(result.0.workspace(containing: windowID(4)) == (policy == .swap ? primaryKey : secondaryKey)) + #expect(result.0.workspaces[primaryKey]?.order.count == (policy == .swap ? 3 : 2)) + #expect(result.0.workspaces[secondaryKey]?.order.count == (policy == .swap ? 2 : 3)) + #expect(result.0.workspaces[primaryKey]?.visibleWindows.count == 2) + #expect(result.0.workspaces[secondaryKey]?.visibleWindows == [windowID(2)]) + #expect(result.0.focusedWindow == windowID(2)) +} + +@Test(arguments: Layout.allCases, Layout.allCases) +func fullDisplaySwapPreservesIndependentLayoutSettings(sourceLayout: Layout, destinationLayout: Layout) throws { + var state = multipleDisplays(destinationCap: 2) + state = command(.setLayout(sourceLayout), in: state).0 + state = command(.setRatio(.threeFifths), in: state).0 + state = command(.setLayout(destinationLayout), in: focused(3, in: state)).0 + state = command(.setRatio(.twoThirds), in: state).0 + state = focused(2, in: state) + let result = command(.swap(.right), in: state) + #expect(result.0.workspace(containing: windowID(2)) == secondaryKey) + for key in [primaryKey, secondaryKey] { + let before = try #require(state.workspaces[key]) + let after = try #require(result.0.workspaces[key]) + #expect(after.layout == before.layout) + #expect(after.ratio == before.ratio) + #expect(after.gaps == before.gaps) + #expect(after.reservedEdges == before.reservedEdges) + #expect(after.windowCap == before.windowCap) + #expect(after.order.count == before.order.count) + #expect(after.visibleWindows.count == before.visibleWindows.count) + } +} + +@Test(arguments: WhenDisplayFull.allCases) +func displayFullPolicyRoundTripsAndLegacySnapshotsDefaultToSwap(policy: WhenDisplayFull) throws { + var state = multipleDisplays(destinationCap: 2) + #expect(state.whenDisplayFull == .swap) + #expect(State(whenDisplayFull: policy).whenDisplayFull == policy) + state.whenDisplayFull = policy + let data = try JSONEncoder().encode(state) + let decoded = try JSONDecoder().decode(State.self, from: data) + #expect(decoded == state) + #expect(decoded.whenDisplayFull == policy) + #expect( + command(.swap(.right), in: focused(2, in: decoded)).0 == command(.swap(.right), in: focused(2, in: state)).0) + if policy == .swap { + #expect(!String(decoding: data, as: UTF8.self).contains("\"whenDisplayFull\"")) + var explicit = state + explicit.whenDisplayFull = .stack + let encoded = try JSONEncoder().encode(explicit) + let json = String(decoding: encoded, as: UTF8.self).replacingOccurrences( + of: "\"whenDisplayFull\":\"stack\"", with: "\"whenDisplayFull\":\"swap\"") + #expect(try JSONDecoder().decode(State.self, from: Data(json.utf8)) == state) + } else { + let invalid = String(decoding: data, as: UTF8.self).replacingOccurrences( + of: "\"whenDisplayFull\":\"stack\"", with: "\"whenDisplayFull\":\"invalid\"") + #expect(throws: DecodingError.self) { try JSONDecoder().decode(State.self, from: Data(invalid.utf8)) } + } } @Test func edgeSwapReachesAFullStaggeredDisplay() { @@ -103,19 +184,32 @@ func moveToDisplayUsesGlobalGeometry(direction: Direction) { #expect(result.0.workspace(containing: windowID(3)) == primaryKey) } -@Test func edgeSwapStacksOnAFullDisplay() { - let state = focused(2, in: multipleDisplays(destinationCap: 2)) - let result = command(.swap(.right), in: state) - #expect(result.0.workspace(containing: windowID(2)) == secondaryKey) - #expect(result.0.workspace(containing: windowID(3)) == secondaryKey) +@Test(arguments: Direction.allCases, WhenFull.allCases) +func edgeSwapStacksOnAFullDisplayWhenConfigured(direction: Direction, overflow: WhenFull) { + let source = windowID(direction == .right ? 2 : 1) + let target = windowID(direction == .left ? 4 : 3) + var state = focused(Int(source.rawValue), in: multipleDisplays(direction, destinationCap: 2)) + state.whenDisplayFull = .stack + state.workspaces[secondaryKey]?.whenFull = overflow + let result = command(.swap(direction), in: state) + #expect(result.0.workspace(containing: source) == secondaryKey) + #expect(result.0.workspace(containing: target) == secondaryKey) + #expect(result.0.workspaces[primaryKey]?.order.count == 1) + #expect(result.0.workspaces[secondaryKey]?.order.count == 3) #expect(result.0.workspaces[secondaryKey]?.tree?.tileCount == 2) - #expect(result.0.workspaces[secondaryKey]?.tree?.stack(containing: windowID(2))?.windows.count == 2) - #expect(result.0.focusedWindow == windowID(2)) + #expect(result.0.frames[source] == result.0.frames[target]) + #expect(!result.0.visibleWindows.contains(target)) + #expect(result.0.windows[source]?.isFloating == false) + #expect(result.0.workspaces[secondaryKey]?.layout == .columns) + #expect(result.0.workspaces[secondaryKey]?.whenFull == overflow) + #expect(result.0.focusedWindow == source) + #expect(result.1.contains(.announce(.movedToDisplay(source, secondaryDisplay)))) } -@Test(arguments: Direction.allCases) -func edgeSwapMovesToEmptyAdjacentDisplay(direction: Direction) throws { +@Test(arguments: Direction.allCases, WhenDisplayFull.allCases) +func edgeSwapMovesToEmptyAdjacentDisplay(direction: Direction, policy: WhenDisplayFull) throws { var state = multipleDisplays(direction) + state.whenDisplayFull = policy state = reduce(state, .windowDisappeared(windowID(3))).0 state = reduce(state, .windowDisappeared(windowID(4))).0 state = focused(direction == .right ? 2 : 1, in: state) @@ -127,8 +221,10 @@ func edgeSwapMovesToEmptyAdjacentDisplay(direction: Direction) throws { #expect(result.1.contains(.announce(.movedToDisplay(window, secondaryDisplay)))) } -@Test func edgeSwapMovesToDisplayWithRoomWithoutDisplacingWindows() { - let state = focused(2, in: multipleDisplays()) +@Test(arguments: WhenDisplayFull.allCases) +func edgeSwapMovesToDisplayWithRoomWithoutDisplacingWindows(policy: WhenDisplayFull) { + var state = focused(2, in: multipleDisplays()) + state.whenDisplayFull = policy let result = command(.swap(.right), in: state) #expect(result.0.workspace(containing: windowID(2)) == secondaryKey) #expect(result.0.workspace(containing: windowID(3)) == secondaryKey) @@ -152,8 +248,10 @@ func edgeSwapMovesToEmptyAdjacentDisplay(direction: Direction) throws { #expect(result.0.workspace(containing: windowID(3)) == thirdKey) } -@Test func swapPrefersNeighborOnTheSameDisplay() { - let state = focused(1, in: multipleDisplays()) +@Test(arguments: WhenDisplayFull.allCases) +func swapPrefersNeighborOnTheSameDisplay(policy: WhenDisplayFull) { + var state = focused(1, in: multipleDisplays(destinationCap: 2)) + state.whenDisplayFull = policy let result = command(.swap(.right), in: state) #expect(result.0.workspace(containing: windowID(1)) == primaryKey) #expect(result.0.workspace(containing: windowID(2)) == primaryKey) diff --git a/Tests/ParcelCoreTests/RoomFeedbackTests.swift b/Tests/ParcelCoreTests/RoomFeedbackTests.swift index 3dba1fec..a1721630 100644 --- a/Tests/ParcelCoreTests/RoomFeedbackTests.swift +++ b/Tests/ParcelCoreTests/RoomFeedbackTests.swift @@ -284,9 +284,9 @@ struct RoomFeedbackTests { return reduce(state, .relayout).0 } - private func retileCounts(_ effects: [Effect]) -> [Int] { + private func retileCandidateCounts(_ effects: [Effect]) -> [Int] { effects.compactMap { effect in - if case .report(.retiled(let count)) = effect { return count } + if case .confirmRetile(let candidates) = effect { return candidates.count } return nil } } @@ -298,11 +298,11 @@ struct RoomFeedbackTests { #expect(after.frames[windowID(1)] == Rect(width: 400, height: 800)) #expect(after.frames[windowID(2)] == Rect(x: 400, width: 400, height: 800)) #expect(after.frames[windowID(3)] == Rect(x: 800, width: 400, height: 800)) - #expect(retileCounts(effects) == [3]) + #expect(retileCandidateCounts(effects) == [3]) } @Test(arguments: [false, true]) - func retileCountsOnlyChangedFramesInItsWorkspace(primaryChanged: Bool) { + func retileRevalidatesOnlyItsOwnWorkspaceIncludingCachedFrames(primaryChanged: Bool) { var before = withDestination(populated()) let expectedFrames = before.frames let displaced = Rect(x: 10, y: 20, width: 100, height: 100) @@ -314,7 +314,12 @@ struct RoomFeedbackTests { #expect(after.frames == expectedFrames) #expect(frameWrites(effects).map(\.window) == (primaryChanged ? [windowID(2), windowID(10)] : [windowID(10)])) - #expect(retileCounts(effects) == [primaryChanged ? 1 : 0]) + #expect(retileCandidateCounts(effects) == [3]) + #expect( + effects.contains( + .confirmRetile((1...3).map { WindowFrame(window: windowID($0), frame: expectedFrames[windowID($0)]!) })) + ) + #expect(!effects.contains { if case .report(.retiled) = $0 { true } else { false } }) } @Test(arguments: [false, true]) @@ -328,8 +333,8 @@ struct RoomFeedbackTests { #expect(after.workspaces[primaryKey]?.layout == .rows) #expect(frameWrites(effects[0]).count == 2) #expect(frameWrites(effects[1]).isEmpty) - #expect(retileCounts(effects[retileFirst ? 0 : 1]) == [0]) - #expect(retileCounts(effects[retileFirst ? 1 : 0]).isEmpty) + #expect(retileCandidateCounts(effects[retileFirst ? 0 : 1]) == [0]) + #expect(retileCandidateCounts(effects[retileFirst ? 1 : 0]).isEmpty) } @Test(arguments: [false, true]) @@ -343,7 +348,7 @@ struct RoomFeedbackTests { #expect(after.workspaces[primaryKey]?.order == [windowID(1), windowID(2)]) #expect(frameWrites(effects[0]).map(\.window) == [windowID(1), windowID(2)]) #expect(frameWrites(effects[1]).isEmpty) - #expect(retileCounts(effects[retileFirst ? 0 : 1]) == [0]) + #expect(retileCandidateCounts(effects[retileFirst ? 0 : 1]) == [0]) } @Test(arguments: [false, true]) @@ -354,10 +359,10 @@ struct RoomFeedbackTests { let (_, effects) = reduce(populated(1), events) #expect(frameWrites(effects[0]) == [WindowFrame(window: windowID(1), frame: testScreen)]) - #expect(retileCounts(effects[retileFirst ? 0 : 1]) == [0]) + #expect(retileCandidateCounts(effects[retileFirst ? 0 : 1]) == [0]) } - @Test func retileCountsOnlyChangesThatStillNeedAWrite() throws { + @Test func retileCandidateCountsOnlyChangesThatStillNeedAWrite() throws { let before = try unbalancedForRetile(populated()) let target = Rect(width: 400, height: 800) let (_, effects) = reduce( @@ -365,7 +370,7 @@ struct RoomFeedbackTests { [.commandIssued(.retile), .windowMovedByUser(windowID(1), frame: target)]) #expect(frameWrites(effects[0]).map(\.window) == [windowID(2), windowID(3)]) - #expect(retileCounts(effects[0]) == [2]) + #expect(retileCandidateCounts(effects[0]) == [2]) #expect(effects[1].isEmpty) } @@ -377,8 +382,8 @@ struct RoomFeedbackTests { let (_, effects) = reduce(before, events) #expect(frameWrites(effects[0]).count == 3) - #expect(retileCounts(effects[0]) == [0]) - #expect(effects.dropFirst().allSatisfy { frameWrites($0).isEmpty && retileCounts($0).isEmpty }) + #expect(retileCandidateCounts(effects[0]) == [0]) + #expect(effects.dropFirst().allSatisfy { frameWrites($0).isEmpty && retileCandidateCounts($0).isEmpty }) } @Test func retileRepeatedInOneBatchCountsEachChangedWriteOnlyOnce() throws { @@ -386,8 +391,8 @@ struct RoomFeedbackTests { let (_, effects) = reduce(before, [.commandIssued(.retile), .commandIssued(.retile)]) #expect(frameWrites(effects[0]).count == 3) - #expect(retileCounts(effects[0]) == [3]) - #expect(effects[1] == [.report(.retiled(moved: 0))]) + #expect(retileCandidateCounts(effects[0]) == [3]) + #expect(effects[1] == [.confirmRetile([])]) } @Test func retileReportsStayWithEachActedOnDisplayAfterFocusSwitches() throws { @@ -405,11 +410,11 @@ struct RoomFeedbackTests { frameWrites(effects[0]).map(\.window) == [ windowID(1), windowID(2), windowID(3), windowID(10), windowID(11), ]) - #expect(retileCounts(effects[0]) == [3]) - #expect(retileCounts(effects[2]) == [2]) + #expect(retileCandidateCounts(effects[0]) == [3]) + #expect(retileCandidateCounts(effects[2]) == [2]) #expect(effects.dropFirst().allSatisfy { frameWrites($0).isEmpty }) - #expect(retileCounts(effects[1]).isEmpty) - #expect(retileCounts(effects[3]).isEmpty) + #expect(retileCandidateCounts(effects[1]).isEmpty) + #expect(retileCandidateCounts(effects[3]).isEmpty) } @Test func retileDoesNotCountWritesOnTheSpaceActivatedLaterInItsBatch() throws { @@ -435,8 +440,8 @@ struct RoomFeedbackTests { #expect(after.activeWorkspace == otherKey) #expect(frameWrites(effects[0]).map(\.window) == [windowID(10), windowID(11)]) - #expect(retileCounts(effects[0]) == [0]) - #expect(retileCounts(effects[2]) == [2]) + #expect(retileCandidateCounts(effects[0]) == [0]) + #expect(retileCandidateCounts(effects[2]) == [2]) #expect(after.frames[windowID(1)] == before.frames[windowID(1)]) #expect(after.frames[windowID(10)] == Rect(width: 1200, height: 400)) } @@ -449,7 +454,7 @@ struct RoomFeedbackTests { [.commandIssued(.retile), .activeSpaceChanged(display: primaryDisplay, space: primarySpace)]) #expect(effects[0] == [.report(.noActiveWorkspace)]) - #expect(retileCounts(effects.flatMap { $0 }).isEmpty) + #expect(retileCandidateCounts(effects.flatMap { $0 }).isEmpty) } @Test func retileStillReportsZeroWhenItsDisplayDisconnectsBeforeTheFinalWrite() throws { @@ -458,7 +463,7 @@ struct RoomFeedbackTests { #expect(after.activeWorkspace == nil) #expect(frameWrites(effects.flatMap { $0 }).isEmpty) - #expect(retileCounts(effects[0]) == [0]) + #expect(retileCandidateCounts(effects[0]) == [0]) } @Test func retileAttributionSurvivesRejectedEventsWithoutCreditingTheNextRetile() throws { @@ -467,8 +472,8 @@ struct RoomFeedbackTests { before, [.commandIssued(.retile), .focusChanged(windowID(99)), .commandIssued(.retile)]) #expect(frameWrites(effects[0]).count == 3) - #expect(retileCounts(effects[0]) == [3]) + #expect(retileCandidateCounts(effects[0]) == [3]) #expect(effects[1] == [.report(.unknownWindow(windowID(99)))]) - #expect(effects[2] == [.report(.retiled(moved: 0))]) + #expect(effects[2] == [.confirmRetile([])]) } } diff --git a/Tests/ParcelCoreTests/UndoHistoryTests.swift b/Tests/ParcelCoreTests/UndoHistoryTests.swift index 27072dcf..d2208918 100644 --- a/Tests/ParcelCoreTests/UndoHistoryTests.swift +++ b/Tests/ParcelCoreTests/UndoHistoryTests.swift @@ -307,7 +307,7 @@ import Testing let before = initial() let commands: [Command] = [ .swap(.left), .move(.left), .stack(.left), .moveToDisplay(.left), .unstack, .makePrimary, - .tileWindow(windowID(1)), .tileWindow(windowID(99)), .setLayout(.columns), .setRatio(.half), + .tileWindow(windowID(1)), .tileWindow(windowID(99)), .setLayout(.columns), .nudgeRatio(0), .nudgeRatio(.nan), .setWindowCap(8), .setWindowCap(-1), .split(.vertical), .resetSizes, .balance, .retile, .snap(.restore), .toggleBorders, ] diff --git a/Tests/ParcelCoreTests/WorkspaceCommandTests.swift b/Tests/ParcelCoreTests/WorkspaceCommandTests.swift index 798ec616..8b596c2f 100644 --- a/Tests/ParcelCoreTests/WorkspaceCommandTests.swift +++ b/Tests/ParcelCoreTests/WorkspaceCommandTests.swift @@ -54,7 +54,16 @@ struct WorkspaceCommandTests { #expect(after.workspaces[key]?.layout == .side) #expect(after.workspaces[key]?.ratio == ratio) } - if command == .retile { #expect(effects.contains(.report(.retiled(moved: 2)))) } + if command == .retile { + #expect( + effects.contains( + .confirmRetile( + (4...6).map { + WindowFrame( + window: WindowID(rawValue: UInt32($0)), + frame: after.frames[WindowID(rawValue: UInt32($0))]!) + }))) + } } @Test func targetedLayoutRecordsUndoForItsWindowsWithoutChangingTheOtherDisplay() { @@ -82,16 +91,23 @@ struct WorkspaceCommandTests { .workspaceCommandIssued(.setLayout(.columns), workspace: key), .workspaceCommandIssued(.retile, workspace: key), ]) - #expect(effects[1].contains(.report(.retiled(moved: 0)))) - #expect(!effects[0].contains(.report(.retiled(moved: 0)))) + #expect(effects[1].contains(.confirmRetile([]))) + #expect(!effects[0].contains(.confirmRetile([]))) } @Test func repeatedScopedRetilesCountEachWriteOnce() { let key = WorkspaceKey(display: right, space: space) let event = Event.workspaceCommandIssued(.retile, workspace: key) - let (_, effects) = reduce(scene(), [event, event]) - #expect(effects[0].contains(.report(.retiled(moved: 2)))) - #expect(effects[1].contains(.report(.retiled(moved: 0)))) + let (after, effects) = reduce(scene(), [event, event]) + #expect( + effects[0].contains( + .confirmRetile( + (4...6).map { + WindowFrame( + window: WindowID(rawValue: UInt32($0)), frame: after.frames[WindowID(rawValue: UInt32($0))]! + ) + }))) + #expect(effects[1].contains(.confirmRetile([]))) } @Test func staleSpaceAndDisconnectedDisplayDoNothing() { diff --git a/Tests/ParcelCoreTests/WorkspaceMemoryTests.swift b/Tests/ParcelCoreTests/WorkspaceMemoryTests.swift index 6a76cd25..e68e5292 100644 --- a/Tests/ParcelCoreTests/WorkspaceMemoryTests.swift +++ b/Tests/ParcelCoreTests/WorkspaceMemoryTests.swift @@ -146,16 +146,20 @@ import Testing #expect(restored.windows.isEmpty) } - @Test func settingsOnlyPreservesExistingMembersAndCustomLiveTree() throws { - let memory = try capture(original()) + @Test(arguments: Layout.allCases.filter { $0 != .side }) + func settingsOnlyPreservesExistingMembersAndCustomLiveTree(layout: Layout) throws { + var saved = original() + saved.workspaces[key]?.layout = layout + let memory = try capture(saved) var state = live([1, 2]) - state.workspaces[key]?.layout = .tree + state.workspaces[key]?.layout = layout state.workspaces[key]?.tree = .split( axis: .vertical, fraction: 0.19, first: .tile(WindowStack(id(102))), second: .tile(WindowStack(id(101)))) let restored = memory.restoring(state, restoreWindows: false) #expect(restored.workspaces[key]?.order == state.workspaces[key]?.order) #expect(restored.workspaces[key]?.openingOrder == state.workspaces[key]?.openingOrder) #expect(restored.workspaces[key]?.tree == state.workspaces[key]?.tree) + #expect(restored.workspaces[key]?.ratio == saved.workspaces[key]?.ratio) #expect(restored.windows == state.windows) #expect(restored.frames == state.frames) #expect(restored.workspaces[key]?.windowCap == 4) diff --git a/Tests/ParcelEngineTests/ConfigurationAndDisplayTests.swift b/Tests/ParcelEngineTests/ConfigurationAndDisplayTests.swift index efcff293..e9ee45c8 100644 --- a/Tests/ParcelEngineTests/ConfigurationAndDisplayTests.swift +++ b/Tests/ParcelEngineTests/ConfigurationAndDisplayTests.swift @@ -100,6 +100,60 @@ struct ParcelEngineDisplayTests { @Suite("Engine hot configuration") @MainActor struct ParcelEngineConfigurationTests { + @Test(arguments: ConfigWhenDisplayFull.allCases) + func fullDisplayPolicyReachesCoreAndHotReload(policy: ConfigWhenDisplayFull) async throws { + var configuration = engineConfiguration() + configuration.general.whenDisplayFull = policy + let harness = try EngineHarness(configuration: configuration) + try await harness.start() + let expected: WhenDisplayFull = policy == .swap ? .swap : .stack + #expect(harness.engine.snapshot.state.whenDisplayFull == expected) + let handler = EngineIPCHandler(engine: harness.engine) + guard case .object(let initial) = try await handler.query(.config) else { + Issue.record("Configuration query must return an object") + return + } + #expect(initial["when_display_full"] == .string(policy.rawValue)) + configuration.general.whenDisplayFull = policy == .swap ? .stack : .swap + try harness.engine.applyConfiguration(configuration) + try harness.scheduler.runReady() + #expect(harness.engine.snapshot.state.whenDisplayFull != expected) + guard case .object(let reloaded) = try await handler.query(.config) else { + Issue.record("Configuration query must return an object") + return + } + #expect(reloaded["when_display_full"] == .string(configuration.general.whenDisplayFull.rawValue)) + await harness.engine.stop() + } + + @Test func disablingShortcutsLeavesNamedModesButClearsActiveModeOnReload() async throws { + var configuration = engineConfiguration() + configuration.modes["resize"] = [.command(.ratioIncrease): KeyChord(key: .equal)] + let harness = try EngineHarness(configuration: configuration) + try await harness.start() + let mode = EngineCommandBatch([.enterMode("resize")], engine: harness.engine) + try await mode.waitUntilEnqueued() + try harness.scheduler.runReady() + _ = try await mode.results() + #expect(harness.engine.snapshot.state.activeMode == "resize") + configuration.general.shortcutsEnabled = false + try harness.engine.applyConfiguration(configuration) + try harness.scheduler.runReady() + #expect(harness.engine.snapshot.state.activeMode == nil) + #expect(harness.engine.configuration.modes["resize"] == configuration.modes["resize"]) + let handler = EngineIPCHandler(engine: harness.engine) + guard case .object(let query) = try await handler.query(.config) else { + Issue.record("Configuration query must return an object") + return + } + #expect(query["shortcuts_enabled"] == .bool(false)) + configuration.general.shortcutsEnabled = true + try harness.engine.applyConfiguration(configuration) + try harness.scheduler.runReady() + #expect(harness.engine.snapshot.state.activeMode == nil) + await harness.engine.stop() + } + @Test(arguments: [ConfigWhenFull.stack, .float], [0, 3]) func configuredOverflowPolicyAndUnlimitedSentinelReachCore(policy: ConfigWhenFull, cap: Int) async throws { var configuration = engineConfiguration() diff --git a/Tests/ParcelEngineTests/IPCTests.swift b/Tests/ParcelEngineTests/IPCTests.swift index b8299deb..cc9a3cb5 100644 --- a/Tests/ParcelEngineTests/IPCTests.swift +++ b/Tests/ParcelEngineTests/IPCTests.swift @@ -247,6 +247,7 @@ struct ParcelEngineIPCTests { "path": .string("/tmp/parcel-test.toml"), "version": .string("test-version"), "schema_version": .integer(1), "active_mode": .null, "hover_focus": .bool(false), "automatic_tiling": .bool(true), + "shortcuts_enabled": .bool(true), "when_display_full": .string("swap"), "focus-modes": .object([ "no-peek-level": .number(0.5), "no-peek-blur": .bool(true), "clean-space-color": .string("graphite"), @@ -608,8 +609,8 @@ struct ParcelEngineIPCTests { let retile = Task { @MainActor in try await handler.run(command: "retile", args: []) } try await waitForEngineTurn(harness) try harness.scheduler.runReady() - guard case .object(let retiled) = try await retile.value else { throw HarnessError.missingAction } try harness.finishMotion() + guard case .object(let retiled) = try await retile.value else { throw HarnessError.missingAction } #expect(retiled["accepted"] == .bool(true)) #expect(harness.world.frames == harness.engine.snapshot.state.frames) #expect(!harness.engine.isAutomaticTilingEnabled) diff --git a/Tests/ParcelEngineTests/ParcelEngineTests.swift b/Tests/ParcelEngineTests/ParcelEngineTests.swift index ebb37a1a..fa5c4e84 100644 --- a/Tests/ParcelEngineTests/ParcelEngineTests.swift +++ b/Tests/ParcelEngineTests/ParcelEngineTests.swift @@ -201,6 +201,7 @@ struct ParcelEngineCommandTests { #expect(harness.engine.layoutPassCount == passes) #expect(harness.scheduler.pendingCount == 1) try harness.scheduler.runReady() + try harness.finishMotion() let results = try await batch.results() #expect(harness.engine.layoutPassCount == passes + 1) @@ -216,7 +217,6 @@ struct ParcelEngineCommandTests { harness.engine.snapshot.state.frames[WindowID(rawValue: 1)] == Rect(x: 0, y: 0, width: 1200, height: 400)) #expect( harness.engine.snapshot.state.frames[WindowID(rawValue: 2)] == Rect(x: 0, y: 400, width: 1200, height: 400)) - try harness.finishMotion() #expect(harness.engine.isIdle) await harness.engine.stop() } diff --git a/Tests/ParcelEngineTests/ReportDeliveryTests.swift b/Tests/ParcelEngineTests/ReportDeliveryTests.swift index 4b3e8f95..67d69d5a 100644 --- a/Tests/ParcelEngineTests/ReportDeliveryTests.swift +++ b/Tests/ParcelEngineTests/ReportDeliveryTests.swift @@ -14,6 +14,7 @@ struct ReportDeliveryTests { harness.engine.onReport = { delivered.append(($0, $1)) } harness.engine.send(.commandIssued(.retile)) try harness.scheduler.runReady() + try harness.finishMotion() let notice = try #require(delivered.last) #expect(notice.0 == .retiled(moved: 0)) #expect(notice.1 == harness.engine.snapshot.state) @@ -21,6 +22,195 @@ struct ReportDeliveryTests { await harness.engine.stop() } + @Test func emptyRetileCompletesWithoutWaitingForUnrelatedFrameWrites() async throws { + let harness = try EngineHarness() + try await harness.start() + try harness.add([1, 2]) + try harness.finishMotion() + harness.world.deferWrites = true + let batch = EngineCommandBatch([.setLayout(.rows), .retile], engine: harness.engine) + try await batch.waitUntilEnqueued() + try harness.scheduler.runReady() + let results = try await batch.results() + #expect(results[1].reports == [.retiled(moved: 0)]) + #expect(harness.world.pendingWriteCount > 0) + #expect(!harness.engine.isIdle) + while harness.world.pendingWriteCount > 0 { try harness.world.completeNextWrite() } + #expect(harness.engine.isIdle) + await harness.engine.stop() + } + + @Test func retileWithoutWindowsCompletesAtIdleWithZeroConfirmedMovement() async throws { + let harness = try EngineHarness() + try await harness.start() + let batch = EngineCommandBatch([.retile], engine: harness.engine) + try await batch.waitUntilEnqueued() + try harness.scheduler.runReady() + let result = try #require(try await batch.results().first) + #expect(result.isAccepted) + #expect(result.reports == [.retiled(moved: 0)]) + #expect(harness.world.allWrites.isEmpty) + #expect(harness.engine.isIdle) + await harness.engine.stop() + } + + @Test(arguments: [false, true], [false, true]) + func retileReportsFreshlyConfirmedMovementAndThenZero(glide: Bool, workspaceScoped: Bool) async throws { + let harness = try EngineHarness(configuration: engineConfiguration(glide: glide)) + try await harness.start() + try harness.add([1, 2]) + try harness.finishMotion() + let balanced = harness.world.frames + harness.engine.setAutomaticTilingEnabled(false) + // Deliberately omit the notification: neither planned geometry nor cached readback proves movement. + harness.world.frames[WindowID(rawValue: 1)] = Rect(x: 70, y: 80, width: 300, height: 400) + var delivered: [Report] = [] + harness.engine.onReport = { report, _ in delivered.append(report) } + for expected in [1, 0] { + let task = Task { @MainActor in + if workspaceScoped { return try await harness.engine.perform(.retile, in: engineWorkspace) } + return try await harness.engine.perform(.retile) + } + for _ in 0..<100 where harness.scheduler.pendingCount == 0 { await Task.yield() } + try #require(harness.scheduler.pendingCount > 0, "Retile did not enqueue") + try harness.scheduler.runReady() + try harness.finishMotion() + let result = try await task.value + #expect(result.isAccepted) + #expect(result.reports == [.retiled(moved: expected)]) + #expect(delivered.last == .retiled(moved: expected)) + #expect(harness.world.frames == balanced) + #expect(!harness.engine.isAutomaticTilingEnabled) + } + await harness.engine.stop() + } + + @Test(arguments: [false, true]) + func retileWaitsForFinalReadbackAndCountsEachAnimatedWindowOnce(glide: Bool) async throws { + let harness = try EngineHarness(configuration: engineConfiguration(glide: glide)) + try await harness.start() + try harness.add([1, 2]) + try harness.add([3]) + try harness.finishMotion() + let before = harness.world.frames + harness.world.deferWrites = true + var delivered: [Report] = [] + harness.engine.onReport = { report, _ in delivered.append(report) } + let batch = EngineCommandBatch([.retile], engine: harness.engine) + try await batch.waitUntilEnqueued() + try harness.scheduler.runReady() + #expect(delivered.isEmpty) + #expect(!harness.engine.isIdle) + if glide { + try harness.finishMotion(after: 0.05) + try #require(harness.world.pendingWriteCount > 0) + try harness.world.completeNextWrite() + #expect(delivered.isEmpty) + } + try harness.finishMotion() + while harness.world.pendingWriteCount > 0 { try harness.world.completeNextWrite() } + let result = try #require(try await batch.results().first) + let changed = harness.world.frames.filter { before[$0.key] != $0.value }.count + #expect(changed > 0) + #expect(result.reports == [.retiled(moved: changed)]) + #expect(delivered == [.retiled(moved: changed)]) + #expect(harness.engine.isIdle) + await harness.engine.stop() + } + + @Test(arguments: [false, true]) + func refusedRetileFramesDoNotCountAsMovement(glide: Bool) async throws { + let harness = try EngineHarness(configuration: engineConfiguration(glide: glide)) + try await harness.start() + try harness.add([1, 2]) + try harness.finishMotion() + harness.engine.setAutomaticTilingEnabled(false) + harness.world.userFrame(WindowID(rawValue: 1), frame: Rect(x: 70, y: 80, width: 300, height: 400)) + try harness.scheduler.runReady() + let before = harness.world.frames + harness.world.behaviors[engineApp] = .init(refusesFrames: true) + let batch = EngineCommandBatch([.retile], engine: harness.engine) + try await batch.waitUntilEnqueued() + try harness.scheduler.runReady() + try harness.finishMotion() + let result = try #require(try await batch.results().first) + #expect(result.reports == [.retiled(moved: 0)]) + #expect(harness.world.frames == before) + #expect(!harness.world.allWrites.isEmpty) + await harness.engine.stop() + } + + @Test func adjustedRetileCountsAcceptedMovementRatherThanExactTargetMatches() async throws { + let harness = try EngineHarness() + try await harness.start() + try harness.add([1, 2]) + try harness.finishMotion() + harness.engine.setAutomaticTilingEnabled(false) + harness.world.userFrame(WindowID(rawValue: 1), frame: Rect(x: 70, y: 80, width: 300, height: 400)) + try harness.scheduler.runReady() + let before = harness.world.frames + harness.world.behaviors[engineApp] = .init(widthMultiple: 128) + let batch = EngineCommandBatch([.retile], engine: harness.engine) + try await batch.waitUntilEnqueued() + try harness.scheduler.runReady() + try harness.finishMotion() + let result = try #require(try await batch.results().first) + let changed = harness.world.frames.filter { before[$0.key] != $0.value }.count + #expect(changed == 2) + #expect(result.reports == [.retiled(moved: changed)]) + #expect(harness.world.frames != harness.engine.snapshot.state.frames) + await harness.engine.stop() + } + + @Test(arguments: [Command.setLayout(.rows), .undo]) + func supersededRetileDoesNotCreditStaleReceiptsOrItsReplacement(replacement: Command) async throws { + let harness = try EngineHarness(configuration: engineConfiguration(glide: true)) + try await harness.start() + try harness.add([1, 2]) + try harness.add([3]) + try harness.finishMotion() + let before = harness.world.frames + harness.world.deferWrites = true + let retile = EngineCommandBatch([.retile], engine: harness.engine) + try await retile.waitUntilEnqueued() + try harness.scheduler.runReady() + let latest = EngineCommandBatch([replacement], engine: harness.engine) + try await latest.waitUntilEnqueued() + try harness.scheduler.runReady() + try harness.finishMotion() + while harness.world.pendingWriteCount > 0 { try harness.world.completeNextWrite() } + try harness.finishMotion() + while harness.world.pendingWriteCount > 0 { try harness.world.completeNextWrite() } + let result = try #require(try await retile.results().first) + #expect(result.reports == [.retiled(moved: 0)]) + #expect(try await latest.results().first?.isAccepted == true) + #expect(harness.world.frames == harness.engine.snapshot.state.frames) + if replacement == .undo { #expect(harness.world.frames == before) } + await harness.engine.stop() + } + + @Test(arguments: [false, true]) + func stoppingOrCancellingRetileResumesItsWaitingCaller(cancel: Bool) async throws { + let harness = try EngineHarness() + try await harness.start() + try harness.add([1, 2]) + harness.world.deferWrites = true + let batch = EngineCommandBatch([.retile], engine: harness.engine) + try await batch.waitUntilEnqueued() + try harness.scheduler.runReady() + let task = try #require(batch.tasks.first) + if cancel { + task.cancel() + await #expect(throws: CancellationError.self) { try await task.value } + } else { + await harness.engine.stop() + await #expect(throws: EngineError.stopped) { try await task.value } + } + while harness.world.pendingWriteCount > 0 { try harness.world.completeNextWrite() } + try harness.finishMotion() + await harness.engine.stop() + } + @Test func adaptiveCapsReachFeedbackAtStartupReloadAndCommands() async throws { var configuration = engineConfiguration(layout: .grid) configuration.layout.global.windowCap = 5 diff --git a/Tests/ParcelEngineTests/TestSupport.swift b/Tests/ParcelEngineTests/TestSupport.swift index c0556690..32f82216 100644 --- a/Tests/ParcelEngineTests/TestSupport.swift +++ b/Tests/ParcelEngineTests/TestSupport.swift @@ -134,6 +134,7 @@ final class FakeEngineWorld: EngineWindowWorld, EngineCommandWindowProviding { var offsetWrites = Int.max var timesOut = false var vanishes = false + var refusesFrames = false } struct WriteRecord { @@ -296,8 +297,12 @@ final class FakeEngineWorld: EngineWindowWorld, EngineCommandWindowProviding { if behavior.timesOut { return EngineWriteReceipt(frames: [], failures: [.timedOut(record.app)], duration: behavior.duration) } + let initial = record.writes.compactMap { write -> WindowFrame? in + guard write.capturesInitialFrame, let frame = frames[write.window] else { return nil } + return WindowFrame(window: write.window, frame: frame) + } let observed = record.writes.map { write in - var frame = write.frame + var frame = behavior.refusesFrames ? frames[write.window] ?? write.frame : write.frame if let minimum = behavior.minimumSize { frame.size = Size( width: max(frame.size.width, minimum.width), height: max(frame.size.height, minimum.height)) @@ -318,7 +323,7 @@ final class FakeEngineWorld: EngineWindowWorld, EngineCommandWindowProviding { return WindowFrame(window: write.window, frame: frame) } behaviors[record.app] = behavior - return EngineWriteReceipt(frames: observed, duration: behavior.duration) + return EngineWriteReceipt(frames: observed, duration: behavior.duration, initialFrames: initial) } } -- knotmirror 0.0.1