import Foundation import Synchronization import Testing @testable import ParcelCore func populated(_ count: Int = 3, layout: Layout = .columns, cap: Int = 8) -> State { let space = workspace(count, layout: layout, cap: cap) let windows = Dictionary( uniqueKeysWithValues: (1...max(1, count)).prefix(count).map { (windowID($0), managed($0)) }) let state = State( displays: [Display(id: primaryDisplay, frame: testScreen)], activeSpaces: [primaryDisplay: primarySpace], workspaces: [primaryKey: space], windows: windows ) return reduce(state, .commandIssued(.retile)).0 } func focused(_ number: Int, in state: State) -> State { reduce(state, .focusChanged(windowID(number))).0 } func command(_ command: Command, in state: State) -> (State, [Effect]) { reduce(state, .commandIssued(command)) } func frameWrites(_ effects: [Effect]) -> [WindowFrame] { effects.flatMap { effect in if case .setFrames(let writes) = effect { return writes } return [] } } @Test func appearedWindowGetsFrameAndFocus() { let state = populated(0) let result = reduce(state, .windowAppeared(managed(1), workspace: primaryKey, frame: Rect(width: 100, height: 100))) #expect(result.0.frames[windowID(1)] == testScreen) #expect(result.0.focusedWindow == windowID(1)) #expect(result.1.contains(.focusWindow(windowID(1)))) #expect(result.1.contains(.raiseWindow(windowID(1)))) #expect(result.1.contains(.announce(.focused(windowID(1))))) #expect(frameWrites(result.1) == [WindowFrame(window: windowID(1), frame: testScreen)]) } @Test func appearanceAlreadyAtTargetDoesNotWrite() { let result = reduce(populated(0), .windowAppeared(managed(1), workspace: primaryKey, frame: testScreen)) #expect(frameWrites(result.1).isEmpty) #expect(result.0.frames[windowID(1)] == testScreen) } @Test func duplicateAppearanceKeepsTileAndOrder() { let state = focused(3, in: populated()) let result = reduce( state, .windowAppeared(managed(3), workspace: primaryKey, frame: state.frames[windowID(3)] ?? Rect())) var expected = state expected.observedFrames[windowID(3)] = state.frames[windowID(3)] #expect(result.0 == expected) #expect(result.1.isEmpty) } @Test func duplicateAppearanceUpdatesMetadata() { let state = populated() var updated = managed(2) updated.title = "Updated title" let result = reduce( state, .windowAppeared(updated, workspace: primaryKey, frame: state.frames[windowID(2)] ?? Rect())) #expect(result.0.windows[windowID(2)]?.title == "Updated title") #expect(result.0.workspaces[primaryKey]?.order == state.workspaces[primaryKey]?.order) } @Test func floatingAppearanceOnlyRecordsFrame() { let frame = Rect(x: 10.5, y: 20.5, width: 333.3, height: 222.2) let result = reduce(populated(0), .windowAppeared(managed(1, floating: true), workspace: primaryKey, frame: frame)) #expect(result.0.frames[windowID(1)] == frame) #expect(result.0.observedFrames[windowID(1)] == frame) #expect(result.0.workspaces[primaryKey]?.tree == nil) #expect(frameWrites(result.1).isEmpty) } @Test func appearanceAtCapRaisesNewestStackMember() { let state = populated(2, cap: 2) let result = reduce(state, .windowAppeared(managed(3), workspace: primaryKey, frame: Rect(width: 200, height: 200))) #expect(result.0.workspaces[primaryKey]?.tree?.tileCount == 2) #expect(result.0.frames[windowID(2)] == result.0.frames[windowID(3)]) #expect(result.1.contains(.raiseWindow(windowID(3)))) #expect(result.0.visibleWindows == [windowID(1), windowID(3)]) } @Test func disappearedWindowRemovesAllRecords() { let result = reduce(populated(), .windowDisappeared(windowID(2))) #expect(result.0.windows[windowID(2)] == nil) #expect(result.0.frames[windowID(2)] == nil) #expect(result.0.observedFrames[windowID(2)] == nil) #expect(result.0.workspace(containing: windowID(2)) == nil) #expect(!frameWrites(result.1).contains { $0.window == windowID(2) }) } @Test func disappearingFocusedWindowFocusesSurvivor() { let state = focused(3, in: populated()) let result = reduce(state, .windowDisappeared(windowID(3))) #expect(result.0.focusedWindow == windowID(2)) #expect(result.1.contains(.focusWindow(windowID(2)))) } @Test func disappearingLastWindowClearsFocus() { let result = reduce(focused(1, in: populated(1)), .windowDisappeared(windowID(1))) #expect(result.0.focusedWindow == nil) #expect(result.0.workspaces[primaryKey]?.tree == nil) #expect(result.0.frames.isEmpty) #expect(frameWrites(result.1).isEmpty) } @Test func duplicateDisappearanceIsNoOp() { let state = populated() let result = reduce(state, .windowDisappeared(windowID(99))) #expect(result.0 == state) #expect(result.1.isEmpty) } @Test func disappearingVisibleStackMemberRaisesSurvivor() { let state = focused(3, in: populated(3, cap: 2)) let result = reduce(state, .windowDisappeared(windowID(3))) #expect(result.0.workspaces[primaryKey]?.visibleWindows == [windowID(1), windowID(2)]) #expect(result.1.contains(.raiseWindow(windowID(2)))) } @Test func disappearingHiddenStackMemberKeepsFocusAndGeometry() { let state = focused(3, in: populated(3, cap: 2)) let result = reduce(state, .windowDisappeared(windowID(2))) let frame = Rect(x: 600, width: 600, height: 800) #expect(result.0.focusedWindow == windowID(3)) #expect(state.frames[windowID(3)] == frame) #expect(result.0.frames[windowID(3)] == frame) #expect(frameWrites(result.1).isEmpty) } @Test func tiledUserMoveSnapsBackWithoutReordering() { let state = populated() let actual = Rect(x: 20, y: 20, width: 100, height: 100) let result = reduce(state, .windowMovedByUser(windowID(2), frame: actual)) #expect(result.0.frames == state.frames) #expect(result.0.observedFrames[windowID(2)] == actual) #expect(result.0.workspaces == state.workspaces) #expect(frameWrites(result.1) == [WindowFrame(window: windowID(2), frame: Rect(x: 400, width: 400, height: 800))]) } @Test func tiledUserResizeSnapsBack() { let state = populated(1) let result = reduce(state, .windowResizedByUser(windowID(1), frame: Rect(width: 200, height: 100))) #expect(result.0.frames == state.frames) #expect(frameWrites(result.1) == [WindowFrame(window: windowID(1), frame: testScreen)]) } @Test func targetFrameFeedbackDoesNotLoop() { let state = populated(1) let result = reduce(state, .windowMovedByUser(windowID(1), frame: testScreen)) #expect(result.1.isEmpty) } @Test func floatingUserMoveOnlyRecordsFrame() { let state = command(.toggleFloat, in: focused(2, in: populated())).0 let actual = Rect(x: -90.2, y: 23.1, width: 230, height: 400) let result = reduce(state, .windowMovedByUser(windowID(2), frame: actual)) #expect(result.0.frames[windowID(2)] == actual) #expect(result.1.isEmpty) } @Test func floatingUserResizeOnlyRecordsFrame() { let state = command(.toggleFloat, in: focused(1, in: populated(1))).0 let actual = Rect(width: 333, height: 444) let result = reduce(state, .windowResizedByUser(windowID(1), frame: actual)) #expect(result.0.frames[windowID(1)] == actual) #expect(result.1.isEmpty) } @Test func unknownUserMoveReportsWindow() { let state = populated() let result = reduce(state, .windowMovedByUser(windowID(99), frame: testScreen)) #expect(result.0 == state) #expect(result.1 == [.report(.unknownWindow(windowID(99)))]) } @Test func unknownUserResizeReportsWindow() { let result = reduce(populated(), .windowResizedByUser(windowID(99), frame: testScreen)) #expect(result.1 == [.report(.unknownWindow(windowID(99)))]) } @Test func invalidGeometryDoesNotMutateState() { var state = populated() state.frames[windowID(1)] = Rect(x: 47, y: 29, width: 80, height: 90) let result = reduce(state, .windowFrameEdited(windowID(1), frame: Rect(width: -.infinity, height: 100))) #expect(result.0 == state) #expect(result.1 == [.report(.invalidGeometry)]) } @Test func invalidAppearanceDoesNotInsert() { let state = populated() let result = reduce(state, .windowAppeared(managed(4), workspace: primaryKey, frame: Rect(width: -1, height: 10))) #expect(result.0 == state) #expect(result.1 == [.report(.invalidGeometry)]) } @Test func observedFocusDoesNotRequestFocusAgain() { let result = reduce(populated(), .focusChanged(windowID(2))) #expect(result.0.focusedWindow == windowID(2)) #expect(result.0.workspaces[primaryKey]?.focus == windowID(2)) #expect(!result.1.contains(.focusWindow(windowID(2)))) #expect(result.1.contains(.announce(.focused(windowID(2))))) } @Test func unchangedFocusIsNoOp() { let state = focused(2, in: populated()) let result = reduce(state, .focusChanged(windowID(2))) #expect(result.0 == state) #expect(result.1.isEmpty) } @Test func nilFocusRemembersWorkspaceFocus() { let state = focused(2, in: populated()) let result = reduce(state, .focusChanged(nil)) #expect(result.0.focusedWindow == nil) #expect(result.0.workspaces[primaryKey]?.focus == windowID(2)) } @Test func unknownFocusIsReported() { let result = reduce(populated(), .focusChanged(windowID(99))) #expect(result.1 == [.report(.unknownWindow(windowID(99)))]) } @Test func focusHiddenStackMemberSelectsAndRaisesIt() { let result = reduce(populated(3, cap: 2), .focusChanged(windowID(2))) #expect(result.0.visibleWindows == [windowID(1), windowID(2)]) #expect(result.1.contains(.raiseWindow(windowID(2)))) #expect(frameWrites(result.1).isEmpty) } @Test func minimumLearningRetilesOnlyChangedFrames() { let state = populated(2) let minimum = LearnedMinimumSize(size: Size(width: 900, height: 200)) let result = reduce(state, .minimumSizeChanged(windowID(1), minimum: minimum)) #expect(result.0.windows[windowID(1)]?.minimum == minimum) #expect(frameWrites(result.1).count == 2) #expect(result.0.frames[windowID(1)]?.size.width == 900) } @Test func minimumResetIsInspectableAndRetiles() { let state = reduce( populated(2), .minimumSizeChanged(windowID(1), minimum: LearnedMinimumSize(size: Size(width: 900, height: 200))) ).0 let result = reduce(state, .minimumSizeChanged(windowID(1), minimum: nil)) #expect(result.0.windows[windowID(1)]?.minimum == nil) #expect(result.0.frames[windowID(1)]?.size.width == 600) } @Test func unknownMinimumIsReported() { let result = reduce(populated(), .minimumSizeChanged(windowID(99), minimum: nil)) #expect(result.1 == [.report(.unknownWindow(windowID(99)))]) } @Test func invalidMinimumDoesNotReplaceLearnedValue() { let state = populated() let result = reduce( state, .minimumSizeChanged(windowID(1), minimum: LearnedMinimumSize(size: Size(width: -1, height: 5)))) #expect(result.0 == state) #expect(result.1 == [.report(.invalidGeometry)]) } @Test func movingAHiddenMemberReportsTheDestinationCountNotTheSourceCount() throws { let before = populated(3, cap: 2) let result = reduce(before, .windowDropped(source: windowID(2), target: windowID(1), stacking: true)) let destination = try #require(result.0.workspaces[primaryKey]?.tree?.stacks.first) #expect(Set(destination.windows) == Set([windowID(1), windowID(2)])) #expect(result.1.contains(.announce(.windowsStacked(window: destination.visible, count: 2)))) } @Test func splittingAnExistingStackDoesNotAnnounceAnotherMerge() { let before = command(.setWindowCap(1), in: populated(4)).0 let result = command(.setWindowCap(2), in: before) #expect(result.0.workspaces[primaryKey]?.tree?.tileCount == 2) #expect(!result.1.contains { if case .announce(.windowsStacked) = $0 { true } else { false } }) } @Test(arguments: [WhenFull.stack, .float]) func conflictingMinimumsRespectWhenFullWithAnExplicitReason(policy: WhenFull) throws { var initial = populated(2) initial.workspaces[primaryKey]?.whenFull = policy let minimum = LearnedMinimumSize(size: Size(width: 700, height: 200)) let result = reduce( initial, [ .minimumSizeChanged(windowID(1), minimum: minimum), .minimumSizeChanged(windowID(2), minimum: minimum), ]) let state = result.0 let workspace = try #require(state.workspaces[primaryKey]) #expect(workspace.windowCap == initial.workspaces[primaryKey]?.windowCap) #expect(workspace.order == initial.workspaces[primaryKey]?.order) #expect(state.cannotFit.isEmpty) #expect(state.windows[windowID(2)]?.managementReason == .whenFull) if policy == .stack { #expect(state.windows.values.allSatisfy { !$0.isFloating }) #expect(workspace.tree?.tileCount == 1) #expect(state.frames[windowID(1)] == state.frames[windowID(2)]) let stack = try #require(workspace.tree?.stacks.first) #expect(result.1.flatMap { $0 }.contains(.announce(.windowsStacked(window: stack.visible, count: 2)))) } else { #expect(state.windows[windowID(2)]?.isFloating == true) #expect(workspace.tree?.windows == [windowID(1)]) #expect(result.1.flatMap { $0 }.contains(.report(.spaceFull(windowID(2))))) } let repeated = command(.retile, in: state) #expect(!repeated.1.contains { if case .announce(.windowsStacked) = $0 { true } else { false } }) } @Test(arguments: [WhenFull.stack, .float]) func minimumLargerThanUsableDisplayFloatsWithoutRepeatedReports(policy: WhenFull) { var initial = populated(1) initial.workspaces[primaryKey]?.whenFull = policy initial.workspaces[primaryKey]?.reservedEdges = Insets(left: 100) let result = reduce( initial, .minimumSizeChanged(windowID(1), minimum: LearnedMinimumSize(size: Size(width: 1150, height: 200)))) #expect(result.0.windows[windowID(1)]?.isFloating == true) #expect(result.0.windows[windowID(1)]?.managementReason == .whenFull) #expect(result.0.workspaces[primaryKey]?.tree == nil) #expect(result.0.cannotFit.isEmpty) #expect(result.1.contains(.report(.spaceFull(windowID(1))))) let repeated = command(.retile, in: result.0) #expect(!repeated.1.contains(.report(.spaceFull(windowID(1))))) } @Test func frameEffectsAreSortedByWindowNumber() { let result = command(.setLayout(.rows), in: populated(8)) let writes = frameWrites(result.1) #expect(writes.map(\.window) == writes.map(\.window).sorted()) } @Test(arguments: [WhenFull.stack, .float]) func oversizedWindowDoesNotDisplaceFittingNeighbors(policy: WhenFull) throws { var initial = populated(3) initial.workspaces[primaryKey]?.whenFull = policy let result = reduce( initial, [ .minimumSizeChanged(windowID(1), minimum: LearnedMinimumSize(size: Size(width: 400, height: 200))), .minimumSizeChanged(windowID(2), minimum: LearnedMinimumSize(size: Size(width: 400, height: 200))), .minimumSizeChanged(windowID(3), minimum: LearnedMinimumSize(size: Size(width: 1400, height: 200))), ]) let workspace = try #require(result.0.workspaces[primaryKey]) #expect(workspace.tree?.tileCount == 2) #expect(workspace.tree?.windows == [windowID(1), windowID(2)]) #expect(result.0.windows[windowID(1)]?.isFloating == false) #expect(result.0.windows[windowID(2)]?.isFloating == false) #expect(result.0.windows[windowID(3)]?.isFloating == true) #expect(result.0.cannotFit.isEmpty) #expect(!result.1.flatMap { $0 }.contains { if case .announce(.windowsStacked) = $0 { true } else { false } }) } @Test(arguments: [WhenFull.stack, .float]) func oversizedRecoveryRebalancesSurvivorsBeforeReducingCapacity(policy: WhenFull) throws { var initial = populated(4, layout: .grid) initial.workspaces[primaryKey]?.whenFull = policy initial.workspaces[primaryKey]?.tree = .split( axis: .vertical, fraction: 0.5, first: .split( axis: .horizontal, fraction: 0.5, first: .tile(WindowStack(windowID(1))), second: .tile(WindowStack(windowID(2)))), second: .split( axis: .horizontal, fraction: 0.5, first: .tile(WindowStack(windowID(3))), second: .tile(WindowStack(windowID(4))))) let result = reduce( initial, [1400.0, 400, 400, 900].enumerated().map { index, width in .minimumSizeChanged(windowID(index + 1), minimum: LearnedMinimumSize(size: Size(width: width, height: 200))) }) let workspace = try #require(result.0.workspaces[primaryKey]) #expect(workspace.tree?.tileCount == 3) #expect(workspace.tree?.windows == [2, 3, 4].map(windowID)) #expect(result.0.windows[windowID(1)]?.isFloating == true) #expect([2, 3, 4].allSatisfy { result.0.windows[windowID($0)]?.isFloating == false }) #expect(result.0.cannotFit.isEmpty) } enum CapacityArrivalTiming: CaseIterable { case single, batched, learnedLater } @Test(arguments: [WhenFull.stack, .float], CapacityArrivalTiming.allCases) func constrainedArrivalOverflowsBeforeEstablishedTiles(policy: WhenFull, timing: CapacityArrivalTiming) throws { var initial = populated(2) initial.workspaces[primaryKey]?.whenFull = policy initial.workspaces[primaryKey]?.gaps = Gaps(outer: Insets(20)) initial = reduce( initial, [1, 2].map { .minimumSizeChanged(windowID($0), minimum: LearnedMinimumSize(size: Size(width: 400, height: 200))) } ).0 var arrival = managed(3) let minimum = LearnedMinimumSize(size: Size(width: 500, height: 200)) arrival.minimum = timing == .learnedLater ? nil : minimum let batched = timing == .batched var before = batched ? populated(0) : initial before.workspaces[primaryKey]?.whenFull = policy before.workspaces[primaryKey]?.gaps = Gaps(outer: Insets(20)) var events: [Event] = [] if batched { for number in 1...2 { let window = try #require(initial.windows[windowID(number)]) events.append(.windowAppeared(window, workspace: primaryKey, frame: Rect(width: 400, height: 300))) } } events.append(.windowAppeared(arrival, workspace: primaryKey, frame: Rect(width: 500, height: 300))) var result = reduce(before, events).0 if timing == .learnedLater { result = reduce(result, .minimumSizeChanged(windowID(3), minimum: minimum)).0 } let stacks = try #require(result.workspaces[primaryKey]?.tree?.stacks) #expect(stacks.count == 2) #expect(stacks[0].windows == [windowID(1)]) #expect(stacks[1].windows == (policy == .stack ? [windowID(2), windowID(3)] : [windowID(2)])) #expect(result.windows[windowID(3)]?.isFloating == (policy == .float)) #expect(result.frames[windowID(1)] == initial.frames[windowID(1)]) #expect(result.frames[windowID(2)] == initial.frames[windowID(2)]) #expect(result.cannotFit.isEmpty) let retiled = command(.retile, in: result).0 #expect(retiled.frames == result.frames) } @Test(arguments: [WhenFull.stack, .float]) func capacityRecoveryKeepsSmallNewcomerWhenRemovingItWouldNotHelp(policy: WhenFull) throws { var initial = populated(3) initial.workspaces[primaryKey]?.whenFull = policy let result = reduce( initial, [700.0, 700, 100].enumerated().map { index, width in .minimumSizeChanged(windowID(index + 1), minimum: LearnedMinimumSize(size: Size(width: width, height: 200))) } ).0 #expect(result.workspaces[primaryKey]?.tree?.tileCount == 2) #expect(result.windows[windowID(3)]?.isFloating == false) #expect(result.frames[windowID(3)] != result.frames[windowID(1)]) #expect(result.cannotFit.isEmpty) } @Test(arguments: [false, true]) func capacityRecoveryGroupsWideStacksBeforeSacrificingAFlexibleTile(userMade: Bool) throws { var initial = populated(4, cap: 3) initial.workspaces[primaryKey]?.tree = .split( axis: .vertical, fraction: 0.5, first: .split( axis: .horizontal, fraction: 0.5, first: .tile(WindowStack(windowID(1))), second: .tile(WindowStack(windowID(2)))), second: .tile(WindowStack(windowID(3), others: [windowID(4)], isUserMade: userMade))) let result = reduce( initial, [700.0, 0, 0, 750].enumerated().map { index, width in .minimumSizeChanged( windowID(index + 1), minimum: LearnedMinimumSize(size: Size(width: width, height: width > 0 ? 600 : 0))) } ).0 let stacks = try #require(result.workspaces[primaryKey]?.tree?.stacks) #expect(stacks.count == (userMade ? 2 : 3)) let wide = try #require(stacks.first { $0.windows.contains(windowID(1)) }) #expect(Set(wide.windows) == Set((userMade ? [1, 3, 4] : [1, 4]).map(windowID))) #expect(wide.isUserMade == userMade) #expect(result.frames[windowID(1)] == result.frames[windowID(4)]) #expect(result.frames[windowID(2)] != result.frames[windowID(1)]) #expect(result.cannotFit.isEmpty) #expect(result.windows.values.allSatisfy { !$0.isFloating }) try roundTrip(result) } @Test(arguments: [false, true]) func capacityRecoveryRevisitsAutomaticMergesWhenAnotherMinimumArrives(userMade: Bool) throws { var initial = populated(4, cap: 2) initial.workspaces[primaryKey]?.tree = .split( axis: .horizontal, fraction: 0.5, first: .tile(WindowStack(windowID(1))), second: .tile(WindowStack(windowID(2), others: [windowID(3), windowID(4)], isUserMade: userMade))) let result = reduce( initial, [700.0, 750, 0, 0].enumerated().map { index, width in .minimumSizeChanged( windowID(index + 1), minimum: LearnedMinimumSize(size: Size(width: width, height: width > 0 ? 600 : 0))) } ).0 let tree = try #require(result.workspaces[primaryKey]?.tree) #expect(tree.tileCount == (userMade ? 1 : 2)) #expect(Set(tree.windows) == Set((1...4).map(windowID))) #expect(result.frames[windowID(1)] == result.frames[windowID(2)]) #expect(tree.stacks.contains(where: \.isUserMade) == userMade) #expect(result.cannotFit.isEmpty) #expect(result.windows.values.allSatisfy { !$0.isFloating }) try roundTrip(result) } @Test(arguments: [WhenFull.stack, .float], [700.0, 1400.0]) func capacityRecoveryPreservesOrEndsFocusAsRequired(policy: WhenFull, focusedMinimum: Double) { var initial = command(.toggleFocus, in: focused(2, in: populated(2))).0 initial.workspaces[primaryKey]?.whenFull = policy let result = reduce( initial, [ .minimumSizeChanged(windowID(1), minimum: LearnedMinimumSize(size: Size(width: 700, height: 200))), .minimumSizeChanged( windowID(2), minimum: LearnedMinimumSize(size: Size(width: focusedMinimum, height: 200))), ]) let oversized = focusedMinimum > testScreen.size.width #expect(result.0.windows[windowID(2)]?.isFloating == oversized) #expect(result.0.activeFocusModes.focusedWindow == (oversized ? nil : windowID(2))) if !oversized { #expect(result.0.frames[windowID(2)] == testScreen) } #expect(result.0.cannotFit.isEmpty) } @Test func capacityMergePreservesProtectedStackThroughSlotRefill() throws { var initial = populated(3, cap: 2) initial.workspaces[primaryKey]?.gaps = Gaps(inner: 12) initial.workspaces[primaryKey]?.tree = .split( axis: .horizontal, fraction: 0.5, first: .tile(WindowStack(windowID(1))), second: .tile(WindowStack(windowID(2), others: [windowID(3)], isUserMade: true))) let constrained = reduce( initial, [800.0, 400, 400].enumerated().map { index, width in .minimumSizeChanged(windowID(index + 1), minimum: LearnedMinimumSize(size: Size(width: width, height: 200))) } ).0 #expect(constrained.workspaces[primaryKey]?.tree?.tileCount == 1) #expect(constrained.workspaces[primaryKey]?.tree?.firstStack.isUserMade == true) let restored = reduce(constrained, .windowDisappeared(windowID(1))).0 let stack = try #require(restored.workspaces[primaryKey]?.tree?.firstStack) #expect(restored.workspaces[primaryKey]?.tree?.tileCount == 1) #expect(Set(stack.windows) == Set([windowID(2), windowID(3)])) #expect(stack.isUserMade) #expect(restored.frames[windowID(2)] == restored.frames[windowID(3)]) } @Test func capacityRecoveryKeepsFocusThroughMultipleReductions() { var initial = command(.toggleFocus, in: focused(1, in: populated(4))).0 initial.workspaces[primaryKey]?.whenFull = .float let result = reduce( initial, (1...4).map { .minimumSizeChanged(windowID($0), minimum: LearnedMinimumSize(size: Size(width: 700, height: 200))) } ).0 #expect(result.activeFocusModes.focusedWindow == windowID(1)) #expect(result.windows[windowID(1)]?.isFloating == false) #expect(result.workspaces[primaryKey]?.tree?.windows == [windowID(1)]) #expect(result.frames[windowID(1)] == testScreen) #expect(result.cannotFit.isEmpty) } @Test func capacityCandidatesUseExpandedFocusBounds() { var initial = command(.toggleFocus, in: focused(1, in: populated(3))).0 initial.workspaces[primaryKey]?.whenFull = .float let result = reduce( initial, [700.1, 500, 100].enumerated().map { index, width in .minimumSizeChanged(windowID(index + 1), minimum: LearnedMinimumSize(size: Size(width: width, height: 200))) } ).0 #expect(result.activeFocusModes.focusedWindow == windowID(1)) #expect(result.workspaces[primaryKey]?.tree?.windows == [windowID(1), windowID(2)]) #expect(result.windows[windowID(3)]?.isFloating == true) #expect(result.frames[windowID(1)] == testScreen) #expect(result.cannotFit.isEmpty) } @Test(arguments: [20, 40]) func capacityRecoveryBoundsLayoutPassesForCrowdedWorkspaces(count: Int) { let ids = (1...count).map(windowID) let workspace = Workspace( key: primaryKey, layout: .columns, gaps: Gaps(inner: 1000), windowCap: Int.max, order: ids) let windows = Dictionary( uniqueKeysWithValues: (1...count).map { number in var window = managed(number) window.minimum = LearnedMinimumSize(size: Size(width: 4, height: 4)) return (window.id, window) }) let initial = State( displays: [Display(id: primaryDisplay, frame: Rect(width: 320, height: 200))], activeSpaces: [primaryDisplay: primarySpace], workspaces: [primaryKey: workspace], windows: windows) let arrangements = Mutex(0) let result = LayoutEngine.$arrangementObserver.withValue( { arrangements.withLock { $0 += 1 } }, operation: { reduce(initial, .relayout).0 }) #expect(result.cannotFit.isEmpty) #expect(result.windows.count == count) #expect(arrangements.withLock { $0 } <= count * 8) } @Test func focusObservationsReuseGeometryButAccordionSelectionReflows() { let state = populated(3, cap: 2) let arrangements = Mutex(0) let selected = LayoutEngine.$arrangementObserver.withValue( { arrangements.withLock { $0 += 1 } }, operation: { reduce(state, [.focusChanged(windowID(1)), .focusChanged(windowID(2)), .focusChanged(nil)]) }) #expect(arrangements.withLock { $0 } == 0) #expect(selected.0.visibleWindows == [windowID(1), windowID(2)]) #expect(selected.1.flatMap { frameWrites($0) }.isEmpty) let accordion = focused(1, in: populated(3, layout: .accordion)) arrangements.withLock { $0 = 0 } let reflow = LayoutEngine.$arrangementObserver.withValue( { arrangements.withLock { $0 += 1 } }, operation: { reduce(accordion, .focusChanged(windowID(2))) }) #expect(arrangements.withLock { $0 } == 1) #expect(!frameWrites(reflow.1).isEmpty) } @Test(arguments: [false, true]) func capturedFocusCommandsKeepMembershipAndArrangeOnce(explicitWorkspace: Bool) { let before = focused(3, in: populated(3)) let workspace = explicitWorkspace ? primaryKey : nil let arrangements = Mutex(0) let enabled = LayoutEngine.$arrangementObserver.withValue( { arrangements.withLock { $0 += 1 } }, operation: { reduce(before, .commandForWindow(windowID(1), .toggleFocus, workspace: workspace)) }) #expect(arrangements.withLock { $0 } == 1) #expect(enabled.0.modes(for: primaryKey).focusedWindow == windowID(1)) #expect(enabled.1.contains(.announce(.focusModeChanged(.focus, enabled: true)))) #expect(!enabled.1.contains(.announce(.focusModeChanged(.focus, enabled: false)))) arrangements.withLock { $0 = 0 } let observed = LayoutEngine.$arrangementObserver.withValue( { arrangements.withLock { $0 += 1 } }, operation: { reduce(enabled.0, .focusChanged(windowID(1))) }) #expect(arrangements.withLock { $0 } == 0) #expect(observed.0.modes(for: primaryKey).focusedWindow == windowID(1)) let disabled = reduce(observed.0, .commandForWindow(windowID(1), .toggleFocus, workspace: workspace)) #expect(disabled.0.modes(for: primaryKey).focusedWindow == nil) #expect(disabled.0.frames == before.frames) } @Test func undoSnapshotsAndRetileFeedbackReuseThePostEditLayout() throws { let before = focused(1, in: populated(3, layout: .side)) let edge = try #require(before.tileEdges.first) let events: [Event] = [ .tileEdgeResized(edge, delta: 20), .commandIssued(.nudgeRatio(0.02)), .commandIssued(.retile), ] for event in events { let arrangements = Mutex(0) let edited = LayoutEngine.$arrangementObserver.withValue( { arrangements.withLock { $0 += 1 } }, operation: { reduce(before, [event, .focusChanged(windowID(1))]) }) #expect(arrangements.withLock { $0 } == 1) let restored = command(.undo, in: edited.0).0 #expect(restored.frames == before.frames) #expect(restored.workspaces[primaryKey]?.tree == before.workspaces[primaryKey]?.tree) } } @Test func coldUndoableEditsPrepareCanonicalGeometryOnlyOnce() { let warm = focused(1, in: populated(3, layout: .side)) var cold = warm cold.frames = warm.frames.mapValues { frame in Rect(x: frame.minX + 10, y: frame.minY + 10, width: frame.size.width, height: frame.size.height) } let arrangements = Mutex(0) let edited = LayoutEngine.$arrangementObserver.withValue( { arrangements.withLock { $0 += 1 } }, operation: { reduce(cold, .commandIssued(.nudgeRatio(0.02))) }) #expect(arrangements.withLock { $0 } == 2) #expect(!frameWrites(edited.1).isEmpty) let restored = command(.undo, in: edited.0).0 #expect(restored.frames == warm.frames) #expect(restored.workspaces == warm.workspaces) } @Test func rejectedFrameSamplesKeepGestureGroupingWithoutRearranging() { var before = command(.toggleFloat, in: focused(1, in: populated(1))).0 before.undoHistory = nil let first: Event = .windowFrameEdited(windowID(1), frame: Rect(x: 50, width: 600, height: 500)) let second: Event = .windowFrameEdited(windowID(1), frame: Rect(x: 100, width: 600, height: 500)) let started = reduce(before, [.undoGestureBegan, first]).0 let expected = reduce(started, [second, .undoGestureEnded]).0 let rejected: [(Event, Report)] = [ (.windowFrameEdited(windowID(99), frame: Rect(width: 600, height: 500)), .unknownWindow(windowID(99))), (.windowFrameEdited(windowID(1), frame: Rect(width: -1, height: 500)), .invalidGeometry), ] for (event, issue) in rejected { let arrangements = Mutex(0) let result = LayoutEngine.$arrangementObserver.withValue( { arrangements.withLock { $0 += 1 } }, operation: { reduce(started, [event, second, .undoGestureEnded]) }) #expect(arrangements.withLock { $0 } == 0) #expect(result.1[0] == [.report(issue)]) #expect(result.0 == expected) #expect(result.0.undoHistory?.count(for: windowID(1)) == 1) #expect(command(.undo, in: result.0).0.frames == before.frames) } } @Test func steadyEdgeTicksTraverseOnceAndRejectChangedMinimums() throws { let before = focused(1, in: populated(3, layout: .side)) let edge = try #require(before.tileEdges.first) let seed = reduce(before, [.undoGestureBegan, .tileEdgeResized(edge, delta: 20)]).0 let traversals = Mutex(0) let edited = LayoutEngine.$traversalObserver.withValue( { traversals.withLock { $0 += 1 } }, operation: { reduce(seed, .tileEdgeResized(edge, delta: 40)) }) #expect(traversals.withLock { $0 } == 1) #expect(!frameWrites(edited.1).isEmpty) #expect(edited.0.undoHistory?.count(for: windowID(1)) == 1) #expect(command(.undo, in: edited.0).0.frames == before.frames) let minimum = LearnedMinimumSize(size: Size(width: 900, height: 100)) let changed = reduce(edited.0, .minimumSizeChanged(windowID(1), minimum: minimum)).0 let rejected = reduce(changed, .tileEdgeResized(edge, delta: 60)) #expect(rejected.0 == changed) #expect(rejected.1 == [.report(.invalidGeometry)]) } @Test func reducerDoesNotMutateItsInput() { let state = populated() let original = state _ = reduce(state, .windowDisappeared(windowID(1))) #expect(state == original) } @Test func stateAndEffectValuesEncode() throws { let state = focused(3, in: populated(3, cap: 2)) try roundTrip(state) let result = command(.setLayout(.side), in: state) try roundTrip(result.1) } @Test(arguments: [false, true]) func hoverFocusRoundTripsWithDerivedLayoutCaches(enabled: Bool) throws { let state = reduce(populated(2), .hoverFocusConfigured(enabled)).0 let decoded = try JSONDecoder().decode(State.self, from: JSONEncoder().encode(state)) #expect(decoded == state) #expect(decoded.hoverFocusEnabled == enabled) #expect(decoded.workspace(containing: windowID(1)) == primaryKey) #expect(decoded.visibleWindows == state.visibleWindows) } @Test func workspaceLookupTracksExternalReplacementAndDecodedState() throws { var state = populated(2) let moved = windowID(2) let destination = WorkspaceKey(display: primaryDisplay, space: SpaceID(rawValue: 9)) state.workspaces[primaryKey]?.remove(moved) state.workspaces[destination] = Workspace(key: destination, order: [moved]) #expect(state.workspace(containing: moved) == destination) #expect(state.workspace(containing: windowID(1)) == primaryKey) let decoded = try JSONDecoder().decode(State.self, from: JSONEncoder().encode(state)) #expect(decoded == state) #expect(decoded.workspace(containing: moved) == destination) let activated = reduce(decoded, .activeSpaceChanged(display: primaryDisplay, space: destination.space)).0 #expect(activated.workspace(containing: moved) == destination) #expect(activated.visibleWindows == [moved]) #expect(activated.frames[moved] == testScreen) } @Test func externalGeometryChangesInvalidateDirectionalFocusAndLayout() throws { var state = focused(1, in: populated(2)) state.workspaces[primaryKey]?.changeLayout(.rows) state.displays[primaryDisplay] = Display( id: primaryDisplay, frame: Rect(x: 100, y: 50, width: 900, height: 600)) let result = command(.focus(.down), in: state) #expect(result.0.focusedWindow == windowID(2)) #expect(result.0.frames[windowID(1)] == Rect(x: 100, y: 50, width: 900, height: 300)) #expect(result.0.frames[windowID(2)] == Rect(x: 100, y: 350, width: 900, height: 300)) let decoded = try JSONDecoder().decode(State.self, from: JSONEncoder().encode(result.0)) #expect(command(.focus(.up), in: decoded).0.focusedWindow == windowID(1)) }