import Foundation import Testing @testable import ParcelCore @Test(arguments: Layout.allCases) func conflictingMinimumsKeepGapsAndTilesOnScreen(layout: Layout) { var space = workspace(3, layout: layout, gaps: Gaps(inner: 10)) let windows = [windowID(1): managed(1, minimum: Size(width: 1000, height: 1000))] let screen = Rect(width: 100, height: 100) space.adapt(to: screen) let result = LayoutEngine.arrange(space, in: screen, windows: windows) for frame in result.frames.values { #expect(frame.minX >= 0 && frame.maxX <= 100) #expect(frame.minY >= 0 && frame.maxY <= 100) } #expect(result.cannotFit == [windowID(1)]) } @Test func fractionalMinimumUsesNextWholePoint() { var space = workspace(2, layout: .columns) let screen = Rect(width: 100, height: 100) space.adapt(to: screen) let result = LayoutEngine.arrange( space, in: screen, windows: [windowID(1): managed(1, minimum: Size(width: 50.4, height: 0))]) #expect(result.frames[windowID(1)]?.size.width == 51) #expect(result.frames[windowID(2)]?.size.width == 49) #expect(result.cannotFit.isEmpty) } @Test func migrationReselectsFocusedMemberAfterFillingStack() { let state = multipleDisplays(destinationCap: 1) let result = reduce( state, .displaySetChanged([state.displays[secondaryDisplay] ?? Display(id: secondaryDisplay, frame: Rect())])) #expect(result.0.focusedWindow == windowID(1)) #expect(result.0.visibleWindows == [windowID(1)]) #expect(result.0.workspaces[secondaryKey]?.focus == windowID(1)) #expect(result.1.contains(.raiseWindow(windowID(1)))) } @Test func disconnectRecentersFloatingWindow() throws { let floated = command(.toggleFloat, in: focused(3, in: multipleDisplays())).0 let previous = try #require(floated.frames[windowID(3)]) let result = reduce(floated, .displaySetChanged([Display(id: primaryDisplay, frame: testScreen)])) let relocated = try #require(result.0.frames[windowID(3)]) #expect(result.0.workspace(containing: windowID(3)) == primaryKey) #expect(relocated.size == previous.size) #expect(relocated.center == testScreen.center) #expect(frameWrites(result.1).contains { $0.window == windowID(3) }) } @Test func migrationWaitsForReplacementDisplaySpace() { let state = focused(2, in: populated()) let display = Display(id: secondaryDisplay, frame: testScreen) let pending = reduce(state, .displaySetChanged([display])).0 #expect(pending.workspace(containing: windowID(2)) == primaryKey) let result = reduce(pending, .activeSpaceChanged(display: secondaryDisplay, space: secondarySpace)) #expect(result.0.workspaces[primaryKey]?.order.isEmpty == true) #expect(result.0.workspaces[secondaryKey]?.order == (1...3).map(windowID)) #expect(result.0.focusedWindow == windowID(2)) } @Test func disconnectedInactiveSpaceRemainsDormant() { let key = WorkspaceKey(display: primaryDisplay, space: secondarySpace) let state = reduce( multipleDisplays(), .windowAppeared(managed(5), workspace: key, frame: Rect(width: 100, height: 100)) ).0 let result = reduce( state, .displaySetChanged([state.displays[secondaryDisplay] ?? Display(id: secondaryDisplay, frame: Rect())])) #expect(result.0.workspaces[key]?.order == [windowID(5)]) #expect(!frameWrites(result.1).contains { $0.window == windowID(5) }) } @Test func inactiveFrameObservationIsReconciledOnReturn() { let initial = focused(2, in: populated()) let away = reduce(initial, .activeSpaceChanged(display: primaryDisplay, space: secondarySpace)).0 let resized = reduce(away, .windowResizedByUser(windowID(1), frame: Rect(width: 100, height: 100))) #expect(frameWrites(resized.1).isEmpty) let result = reduce(resized.0, .activeSpaceChanged(display: primaryDisplay, space: primarySpace)) #expect(frameWrites(result.1) == [WindowFrame(window: windowID(1), frame: Rect(width: 400, height: 800))]) } @Test func floatingStackMemberIsRaisedAboveRemainingStack() { let state = focused(3, in: populated(3, cap: 1)) let result = command(.toggleFloat, in: state) #expect(result.0.visibleWindows == [windowID(2), windowID(3)]) let raised = result.1.compactMap { effect -> WindowID? in if case .raiseWindow(let window) = effect { return window } return nil } #expect(raised.last == windowID(3)) } @Test func duplicateBackgroundAppearanceDoesNotStealFocus() { let state = focused(1, in: populated()) let result = reduce( state, .windowAppeared(managed(2), workspace: primaryKey, frame: Rect(x: 400, width: 400, height: 800))) #expect(result.0.focusedWindow == windowID(1)) #expect(result.0.workspaces[primaryKey]?.focus == windowID(1)) #expect(result.1.isEmpty) } @Test func floatingDisplayMoveDiffsInsteadOfWritingUnchangedFrame() { let floated = command(.toggleFloat, in: multipleDisplays()).0 let target = Rect(x: 1500, width: 600, height: 800) let state = reduce(floated, .windowMovedByUser(windowID(1), frame: target)).0 let result = command(.moveToDisplay(.right), in: state) #expect(result.0.frames[windowID(1)] == target) #expect(frameWrites(result.1).isEmpty) } @Test func stackInitializerDeduplicatesEveryMember() { let stack = WindowStack(windowID(1), others: [windowID(2), windowID(2), windowID(1), windowID(3)]) #expect(stack.windows == (1...3).map(windowID)) #expect(stack.visible == windowID(1)) #expect(stack.recency == [2, 3, 1].map(windowID)) } @Suite("Window stack") struct WindowStackTests { @Test(arguments: 1...4) func stackInitializerSeedsLastHiddenFallback(count: Int) throws { let order = (1...count).map(windowID) let stack = WindowStack(windowID(1), others: Array(order.dropFirst())) #expect(stack.windows == order) #expect(stack.recency == Array(order.dropFirst()) + [windowID(1)]) if count == 1 { #expect(stack.removing(windowID(1)) == nil) } else { let remaining = try #require(stack.removing(windowID(1))) #expect(remaining.windows == Array(order.dropFirst())) #expect(remaining.visible == windowID(count)) } } @Test func stackSelectionKeepsPresentationAndRemembersEverySurvivor() throws { let order = (1...4).map(windowID) var stack = WindowStack(windowID(1), others: Array(order.dropFirst())) for selected in [2, 4, 3, 2, 1] { stack.select(windowID(selected)) #expect(stack.windows == order) } #expect(stack.recency == [4, 3, 2, 1].map(windowID)) for closed in 1...3 { stack = try #require(stack.removing(windowID(closed))) #expect(stack.visible == windowID(closed + 1)) #expect(stack.windows == ((closed + 1)...4).map(windowID)) #expect(stack.recency == ((closed + 1)...4).reversed().map(windowID)) } #expect(stack.removing(windowID(4)) == nil) } @Test func stackAppendSelectsNewMemberAndRemembersPreviousSelection() throws { var stack = WindowStack(windowID(1), others: [windowID(2), windowID(3)]) stack.select(windowID(2)) stack.append(windowID(4)) #expect(stack.windows == (1...4).map(windowID)) #expect(stack.visible == windowID(4)) #expect(stack.recency == [3, 1, 2, 4].map(windowID)) let remaining = try #require(stack.removing(windowID(4))) #expect(remaining.visible == windowID(2)) #expect(remaining.recency == [3, 1, 2].map(windowID)) } @Test(arguments: [1, 2, 3]) func stackDuplicateAppendDoesNotSelectOrChangeHistory(member: Int) { var stack = WindowStack(windowID(1), others: [windowID(2), windowID(3)]) stack.select(windowID(2)) let original = stack stack.append(windowID(member)) #expect(stack == original) } @Test func stackReselectAndUnknownOperationsLeaveHistoryUnchanged() { var stack = WindowStack(windowID(1), others: [windowID(2), windowID(3)]) stack.select(windowID(2)) let original = stack stack.select(windowID(2)) #expect(stack == original) stack.select(windowID(9)) #expect(stack == original) #expect(stack.removing(windowID(9)) == original) #expect(stack.replacing(windowID(9), with: windowID(2)) == original) #expect(stack.replacing(windowID(9), with: windowID(10)) == original) #expect(stack.replacing(windowID(2), with: windowID(2)) == original) } @Test(arguments: [false, true]) func stackCycleUsesPresentationOrderAndUpdatesRecency(forward: Bool) throws { let order = (1...4).map(windowID) var stack = WindowStack(windowID(1), others: Array(order.dropFirst())) stack.select(windowID(3)) stack.select(windowID(1)) let original = stack stack.cycle(forward: forward) let selected = windowID(forward ? 2 : 4) #expect(stack.windows == order) #expect(stack.visible == selected) #expect(stack.recency == original.recency.filter { $0 != selected } + [selected]) let remaining = try #require(stack.removing(selected)) #expect(remaining.visible == windowID(1)) for expected in forward ? [3, 4, 1] : [3, 2, 1] { stack.cycle(forward: forward) #expect(stack.visible == windowID(expected)) #expect(stack.windows == order) #expect(stack.recency.last == stack.visible) } } @Test(arguments: [false, true]) func stackSingletonCycleIsUnchangedAndRemovalEmptiesStack(forward: Bool) { var stack = WindowStack(windowID(1)) let original = stack stack.cycle(forward: forward) #expect(stack == original) #expect(stack.removing(windowID(1)) == nil) #expect(stack.removing(windowID(9)) == original) } @Test(arguments: [1, 3, 4]) func stackHiddenRemovalPreservesRemainingRecency(member: Int) throws { var stack = WindowStack(windowID(1), others: [windowID(2), windowID(3), windowID(4)]) stack.select(windowID(3)) stack.select(windowID(2)) let original = stack let remaining = try #require(stack.removing(windowID(member))) #expect(stack == original) #expect(remaining.windows == stack.windows.filter { $0 != windowID(member) }) #expect(remaining.visible == windowID(2)) #expect(remaining.recency == stack.recency.filter { $0 != windowID(member) }) let afterVisibleCloses = try #require(remaining.removing(windowID(2))) #expect(afterVisibleCloses.visible == windowID(member == 3 ? 1 : 3)) } @Test(arguments: [2, 3]) func stackReplacementPreservesPresentationSlotAndRecencyRank(member: Int) throws { var stack = WindowStack(windowID(1), others: [windowID(2), windowID(3), windowID(4)]) stack.select(windowID(3)) stack.select(windowID(2)) let original = stack let replacement = stack.replacing(windowID(member), with: windowID(9)) #expect(stack == original) #expect(replacement.windows == (member == 2 ? [1, 9, 3, 4] : [1, 2, 9, 4]).map(windowID)) #expect(replacement.visible == windowID(member == 2 ? 9 : 2)) #expect(replacement.recency == (member == 2 ? [4, 1, 3, 9] : [4, 1, 9, 2]).map(windowID)) let remaining = try #require(replacement.removing(replacement.visible)) #expect(remaining.visible == windowID(member == 2 ? 3 : 9)) #expect(try #require(remaining.removing(remaining.visible)).visible == windowID(1)) } @Test(arguments: [1, 2, 3]) func stackReplacementWithExistingMemberSwapsIdentities(visible: Int) throws { var stack = WindowStack(windowID(1), others: [windowID(2), windowID(3)]) stack.select(windowID(3)) stack.select(windowID(visible)) let original = stack let swapped = stack.replacing(windowID(1), with: windowID(2)) #expect(stack == original) #expect(swapped.windows == [2, 1, 3].map(windowID)) let expectedVisible = switch visible { case 1: windowID(2) case 2: windowID(1) default: windowID(3) } #expect(swapped.visible == expectedVisible) let expectedRecency = stack.recency.map { member in if member == windowID(1) { windowID(2) } else if member == windowID(2) { windowID(1) } else { member } } #expect(swapped.recency == expectedRecency) #expect(swapped.replacing(windowID(2), with: windowID(1)) == original) let remaining = try #require(swapped.removing(swapped.visible)) #expect(remaining.visible == expectedRecency[expectedRecency.count - 2]) #expect(try JSONDecoder().decode(WindowStack.self, from: JSONEncoder().encode(swapped)) == swapped) } @Test func stackRecencyIsValueStateAndAffectsEquality() { var first = WindowStack(windowID(1), others: [windowID(2), windowID(3)]) first.select(windowID(2)) let snapshot = first first.select(windowID(3)) first.select(windowID(2)) #expect(first.windows == snapshot.windows) #expect(first.visible == snapshot.visible) #expect(first != snapshot) #expect(first.recency == [1, 3, 2].map(windowID)) #expect(snapshot.recency == [3, 1, 2].map(windowID)) } @Test(arguments: 1...4) func stackCodableRoundTripPreservesRecencyAndCloseFallback(visible: Int) throws { var stack = WindowStack(windowID(1), others: [windowID(2), windowID(3), windowID(4)]) for selected in [3, 2, 4, visible] { stack.select(windowID(selected)) } var decoded = try JSONDecoder().decode(WindowStack.self, from: JSONEncoder().encode(stack)) #expect(decoded == stack) #expect(decoded.windows == (1...4).map(windowID)) #expect(decoded.recency == stack.recency) while stack.windows.count > 1 { stack = try #require(stack.removing(stack.visible)) decoded = try #require(decoded.removing(decoded.visible)) #expect(decoded == stack) } #expect(decoded.removing(decoded.visible) == nil) } @Test func stackSingletonCodableRoundTripPreservesRecency() throws { let stack = WindowStack(windowID(1)) let decoded = try JSONDecoder().decode(WindowStack.self, from: JSONEncoder().encode(stack)) #expect(decoded == stack) #expect(decoded.recency == [windowID(1)]) #expect(decoded.removing(decoded.visible) == nil) } @Test(arguments: 1...3) func decodedLegacyStackSeedsHistoryAndReencodesRecency(visible: Int) throws { let json = "{\"windows\":[1,2,3],\"visible\":\(visible)}" var stack = try JSONDecoder().decode(WindowStack.self, from: Data(json.utf8)) #expect(stack.windows == (1...3).map(windowID)) #expect(stack.visible == windowID(visible)) #expect(stack.recency == (1...3).filter { $0 != visible }.map(windowID) + [windowID(visible)]) let encoded = try JSONEncoder().encode(stack) #expect(String(decoding: encoded, as: UTF8.self).contains("\"recency\":")) #expect(try JSONDecoder().decode(WindowStack.self, from: encoded) == stack) stack = try #require(stack.removing(stack.visible)) #expect(stack.visible == windowID(visible == 3 ? 2 : 3)) stack.select(stack.windows[0]) #expect(stack.recency.last == stack.visible) #expect(try #require(stack.removing(stack.visible)).visible == stack.windows[1]) } @Test func decodedLegacySingletonStackSeedsHistory() throws { let json = "{\"windows\":[7],\"visible\":7}" let stack = try JSONDecoder().decode(WindowStack.self, from: Data(json.utf8)) #expect(stack == WindowStack(windowID(7))) #expect(stack.recency == [windowID(7)]) #expect(stack.removing(stack.visible) == nil) } @Test(arguments: [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]) func decodedStackAcceptsEachValidRecencyPermutation(recency: [Int]) throws { let visible = try #require(recency.last) let json = "{\"windows\":[1,2,3],\"visible\":\(visible),\"recency\":\(recency)}" let stack = try JSONDecoder().decode(WindowStack.self, from: Data(json.utf8)) #expect(stack.windows == (1...3).map(windowID)) #expect(stack.visible == windowID(visible)) #expect(stack.recency == recency.map(windowID)) let remaining = try #require(stack.removing(stack.visible)) #expect(remaining.visible == windowID(recency[1])) } @Test(arguments: ["[]", "[1,2]", "[1,2,2]", "[1,2,3,3]", "[1,2,9]", "[3,2,1]", "[1,3,2]"]) func decodedStackRejectsMalformedRecencyWithKeyContext(recency: String) { let json = "{\"windows\":[1,2,3],\"visible\":3,\"recency\":\(recency)}" do { _ = try JSONDecoder().decode(WindowStack.self, from: Data(json.utf8)) Issue.record("Malformed stack recency was accepted") } catch DecodingError.dataCorrupted(let context) { #expect(context.codingPath.map(\.stringValue) == ["recency"]) #expect(!context.debugDescription.isEmpty) } catch { Issue.record("Expected a recency data-corruption error, received \(error)") } } @Test(arguments: ["null", "1", "\"invalid\"", "{}", "true", "[1,null,3]", "[1,2,\"3\"]"]) func decodedStackRejectsPresentInvalidRecencyInsteadOfMigrating(recency: String) { let json = "{\"windows\":[1,2,3],\"visible\":3,\"recency\":\(recency)}" #expect(throws: DecodingError.self) { try JSONDecoder().decode(WindowStack.self, from: Data(json.utf8)) } } @Test(arguments: [ "{\"windows\":[],\"visible\":1,\"recency\":[1]}", "{\"windows\":[1,1],\"visible\":1,\"recency\":[1,1]}", "{\"windows\":[1,2],\"visible\":3,\"recency\":[1,2]}", "{\"windows\":[1,2],\"recency\":[1,2]}", "{\"visible\":2,\"recency\":[1,2]}", ]) func decodedStackWithRecencyStillRejectsInvalidMembership(json: String) { #expect(throws: DecodingError.self) { try JSONDecoder().decode(WindowStack.self, from: Data(json.utf8)) } } } @Test(arguments: [0, -1]) func decodedInvalidCapIsRejected(cap: Int) throws { let data = try JSONEncoder().encode(workspace(3)) let json = String(decoding: data, as: UTF8.self).replacingOccurrences( of: "\"windowCap\":8", with: "\"windowCap\":\(cap)") #expect(throws: (any Error).self) { try JSONDecoder().decode(Workspace.self, from: Data(json.utf8)) } } @Test func decodedEmptyStackIsRejected() { let json = "{\"windows\":[],\"visible\":1}" #expect(throws: (any Error).self) { try JSONDecoder().decode(WindowStack.self, from: Data(json.utf8)) } } @Test func decodedStackWithMissingVisibleMemberIsRejected() { let json = "{\"windows\":[1,2],\"visible\":3}" #expect(throws: (any Error).self) { try JSONDecoder().decode(WindowStack.self, from: Data(json.utf8)) } } @Test func decodedStackWithDuplicateMembersIsRejected() { let json = "{\"windows\":[1,1],\"visible\":1}" #expect(throws: (any Error).self) { try JSONDecoder().decode(WindowStack.self, from: Data(json.utf8)) } } @Test func unsupportedLearnedVersionIsReported() { let state = populated() let minimum = LearnedMinimumSize(size: Size(width: 100, height: 100), schemaVersion: 2) let result = reduce(state, .minimumSizeChanged(windowID(1), minimum: minimum)) #expect(result.0 == state) #expect(result.1 == [.report(.unsupportedMinimumVersion(2))]) } @Test func unsupportedAppearanceMinimumIsReported() { var window = managed(4) window.minimum = LearnedMinimumSize(size: Size(width: 100, height: 100), schemaVersion: 2) let state = populated() let result = reduce(state, .windowAppeared(window, workspace: primaryKey, frame: Rect())) #expect(result.0 == state) #expect(result.1 == [.report(.unsupportedMinimumVersion(2))]) } @Test(arguments: [false, true]) func duplicateFloatingStatusUpdatePreservesOrderAndRememberedFocus(active: Bool) throws { var state = focused(1, in: populated(3, cap: 2)) if !active { state = reduce(state, .activeSpaceChanged(display: primaryDisplay, space: secondarySpace)).0 } let originalOrder = try #require(state.workspaces[primaryKey]?.order) for floating in [true, false] { let result = reduce( state, .windowAppeared( managed(2, floating: floating), workspace: primaryKey, frame: state.frames[windowID(2)] ?? Rect())) #expect(result.0.workspaces[primaryKey]?.order == originalOrder) #expect(result.0.workspaces[primaryKey]?.focus == windowID(1)) #expect(result.0.focusedWindow == state.focusedWindow) #expect(!result.1.contains(.focusWindow(windowID(2)))) state = result.0 } if !active { let returned = reduce(state, .activeSpaceChanged(display: primaryDisplay, space: primarySpace)) #expect(returned.0.focusedWindow == windowID(1)) } } @Test func backgroundRetilingAtCapDoesNotHideFocusedStackMember() { var state = focused(3, in: populated(3, cap: 1)) state = reduce( state, .windowAppeared(managed(1, floating: true), workspace: primaryKey, frame: testScreen) ).0 let result = reduce(state, .windowAppeared(managed(1), workspace: primaryKey, frame: testScreen)) #expect(result.0.focusedWindow == windowID(3)) #expect(result.0.workspaces[primaryKey]?.focus == windowID(3)) #expect(result.0.visibleWindows == [windowID(3)]) #expect(result.0.workspaces[primaryKey]?.order == (1...3).map(windowID)) #expect(result.1.contains(.raiseWindow(windowID(3)))) } @Test func explicitRetilingOfFocusedWindowKeepsItsSelectionAndOpeningOrder() { var state = command(.toggleFloat, in: focused(1, in: populated(3, cap: 1))).0 let order = state.workspaces[primaryKey]?.openingOrder state = reduce(state, .windowAppeared(managed(1), workspace: primaryKey, frame: testScreen)).0 #expect(state.windows[windowID(1)]?.isFloating == true) state = command(.tileWindow(windowID(1)), in: state).0 #expect(state.workspaces[primaryKey]?.openingOrder == order) #expect(state.workspaces[primaryKey]?.focus == windowID(1)) #expect(state.visibleWindows == [windowID(1)]) } @Test func futureReplaySchemaIsRejectedBeforeUnknownEventShape() { #expect(throws: EventStreamError.unsupportedVersion(line: 1, version: 9)) { try EventStream.decode("{\"version\":9,\"event\":{\"futureEvent\":{}}}") } }