import Foundation import ParcelConfig import ParcelCore import ParcelEngine import Testing @Suite("Engine displays and Spaces") @MainActor struct ParcelEngineDisplayTests { @Test func switchingSpacesCancelsOldMotionAndSnapsNewWorkspace() async throws { let harness = try EngineHarness(configuration: engineConfiguration(glide: true)) try await harness.start() try harness.add([1, 2]) let secondSpace = SpaceID(rawValue: 9) let hiddenWorkspace = WorkspaceKey(display: engineDisplay, space: secondSpace) harness.world.appear(engineWindow(3), workspace: hiddenWorkspace) try harness.scheduler.runReady() #expect(harness.world.writes(for: WindowID(rawValue: 3)).isEmpty) let priorWrites = harness.world.allWrites.count harness.world.emit(.observed(.activeSpaceChanged(display: engineDisplay, space: secondSpace))) try harness.scheduler.runReady() try harness.finishMotion() #expect(harness.engine.snapshot.state.activeSpaces[engineDisplay] == secondSpace) #expect(harness.engine.snapshot.focusedWindow == WindowID(rawValue: 3)) #expect(harness.engine.snapshot.tiles == [WindowFrame(window: WindowID(rawValue: 3), frame: engineScreen)]) #expect( harness.world.allWrites.dropFirst(priorWrites).allSatisfy { $0.window == WindowID(rawValue: 3) && $0.frame == engineScreen }) #expect(harness.world.frames[WindowID(rawValue: 3)] == engineScreen) #expect(harness.links.runningCount == 0) #expect(harness.engine.isIdle) harness.world.emit(.observed(.activeSpaceChanged(display: engineDisplay, space: engineSpace))) try harness.scheduler.runReady() try harness.finishMotion() #expect(harness.engine.snapshot.focusedWindow == WindowID(rawValue: 2)) #expect(harness.engine.snapshot.tiles.map(\.window) == [WindowID(rawValue: 1), WindowID(rawValue: 2)]) #expect( harness.world.frames[WindowID(rawValue: 2)] == harness.engine.snapshot.state.frames[WindowID(rawValue: 2)]) #expect(harness.engine.isIdle) await harness.engine.stop() } @Test func displayUnplugDuringAnimationMigratesAndStopsRemovedLink() async throws { let harness = try EngineHarness( configuration: engineConfiguration(glide: true), initialState: engineInitialState(twoDisplays: true)) try await harness.start() harness.world.appear(engineWindow(1)) harness.world.appear( engineWindow(2), workspace: WorkspaceKey(display: secondEngineDisplay, space: SpaceID(rawValue: 2)), frame: Rect(x: 1300, y: 100, width: 300, height: 200)) try harness.scheduler.runReady() let removedLink = try #require(harness.links.links[secondEngineDisplay]) #expect(removedLink.isRunning) harness.world.emit(.observed(.displaySetChanged([Display(id: engineDisplay, frame: engineScreen)]))) try harness.scheduler.runReady() try harness.finishMotion() #expect(harness.engine.snapshot.state.displays[secondEngineDisplay] == nil) #expect(harness.engine.snapshot.state.workspace(containing: WindowID(rawValue: 2)) == engineWorkspace) #expect(harness.engine.snapshot.focusedWindow == WindowID(rawValue: 2)) #expect(!removedLink.isRunning) #expect(removedLink.stopCount > 0) for tile in harness.engine.snapshot.tiles { #expect(tile.frame.minX >= engineScreen.minX) #expect(tile.frame.maxX <= engineScreen.maxX) #expect(harness.world.frames[tile.window] == tile.frame) } let writes = harness.world.writes.count removedLink.fireLate(at: harness.clock.now + 1) #expect(harness.world.writes.count == writes) #expect(harness.log.motionErrors.isEmpty) #expect(harness.engine.isIdle) await harness.engine.stop() } @Test func allDisplaysRemovedLeavesNoVisibleWritesOrRunningLinks() async throws { let harness = try EngineHarness(configuration: engineConfiguration(glide: true)) try await harness.start() try harness.add([1, 2]) harness.world.emit(.observed(.displaySetChanged([]))) try harness.scheduler.runReady() let writes = harness.world.writes.count try harness.finishMotion() #expect(harness.engine.snapshot.tiles.isEmpty) #expect(harness.engine.snapshot.focusedWindow == nil) #expect(harness.engine.snapshot.state.windows.count == 2) #expect(harness.links.runningCount == 0) #expect(harness.world.writes.count == writes) #expect(harness.engine.isIdle) await harness.engine.stop() } } @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() configuration.layout.global.whenFull = policy configuration.layout.global.windowCap = cap let harness = try EngineHarness(configuration: configuration) try await harness.start() let workspace = try #require(harness.engine.snapshot.state.workspaces[engineWorkspace]) #expect(workspace.whenFull == (policy == .stack ? WhenFull.stack : .float)) #expect(workspace.windowCap == (cap == 0 ? Int.max : cap)) await harness.engine.stop() } @Test func perDisplayOverflowPolicyHotReloadDoesNotChangeOtherWorkspace() async throws { let harness = try EngineHarness(initialState: engineInitialState(twoDisplays: true)) try await harness.start() let other = WorkspaceKey(display: secondEngineDisplay, space: SpaceID(rawValue: 2)) var configuration = harness.engine.configuration var values = configuration.layout.global values.whenFull = .float values.windowCap = 2 configuration.layout.displays[try #require(UUID(uuidString: secondEngineDisplay.rawValue))] = values try harness.engine.applyConfiguration(configuration) try harness.scheduler.runReady() #expect(harness.engine.snapshot.state.workspaces[engineWorkspace]?.whenFull == .stack) #expect(harness.engine.snapshot.state.workspaces[engineWorkspace]?.windowCap == 3) #expect(harness.engine.snapshot.state.workspaces[other]?.whenFull == .float) #expect(harness.engine.snapshot.state.workspaces[other]?.windowCap == 2) await harness.engine.stop() } @Test func overflowFloatingSurvivesRepeatedNativeObservations() async throws { var configuration = engineConfiguration() configuration.layout.global.windowCap = 1 configuration.layout.global.whenFull = .float let harness = try EngineHarness(configuration: configuration) try await harness.start() try harness.add([1]) let overflow = engineWindow(2) harness.world.appear(overflow) try harness.scheduler.runReady() #expect(harness.engine.snapshot.state.windows[overflow.id]?.isFloating == true) #expect(harness.log.reports.contains(.spaceFull(overflow.id))) harness.world.appear(overflow) try harness.scheduler.runReady() #expect(harness.engine.snapshot.state.windows[overflow.id]?.isFloating == true) #expect(harness.engine.snapshot.state.workspaces[engineWorkspace]?.tree?.tileCount == 1) await harness.engine.stop() } @Test(arguments: [FrameChangeOrigin.unknown, .reconciled]) func initialNativeFrameNotificationsUseLatestSizeWithoutReplacingTheCenteredTarget(origin: FrameChangeOrigin) async throws { var configuration = engineConfiguration() configuration.layout.global.windowCap = 1 configuration.layout.global.whenFull = .float let harness = try EngineHarness(configuration: configuration) try await harness.start() try harness.add([1]) let overflow = engineWindow(2) harness.world.appear(overflow) harness.world.userFrame( overflow.id, frame: Rect(x: 80, y: 108, width: 360, height: 240), resized: true, origin: origin) try harness.scheduler.runReady() try harness.finishMotion(after: 0.03) let centered = Rect(x: 420, y: 280, width: 360, height: 240) #expect(harness.engine.snapshot.state.frames[overflow.id] == centered) #expect(harness.world.frames[overflow.id] == centered) await harness.engine.stop() } @Test(arguments: [false, true]) func initialFloatPlacementSurvivesNativeNotificationsUntilItsFirstReadback(beforeDispatch: Bool) async throws { var configuration = engineConfiguration() configuration.layout.global.windowCap = 1 configuration.layout.global.whenFull = .float let harness = try EngineHarness(configuration: configuration) try await harness.start() try harness.add([1]) harness.world.deferWrites = true let overflow = engineWindow(2) harness.world.appear(overflow) try harness.scheduler.runReady() if !beforeDispatch { try harness.scheduler.advance(by: 0.02) } harness.world.userFrame( overflow.id, frame: Rect(x: 80, y: 108, width: 360, height: 240), resized: true, origin: .unknown) try harness.scheduler.runReady() let centered = Rect(x: 450, y: 300, width: 300, height: 200) #expect(harness.engine.snapshot.state.frames[overflow.id] == centered) if beforeDispatch { try harness.scheduler.advance(by: 0.03) } #expect(harness.world.pendingWriteCount == 1) try harness.world.completeNextWrite() try harness.scheduler.runReady() #expect(harness.world.frames[overflow.id] == centered) await harness.engine.stop() } @Test func anExplicitUserEditInterruptsInitialOverflowPlacement() async throws { var configuration = engineConfiguration() configuration.layout.global.windowCap = 1 configuration.layout.global.whenFull = .float let harness = try EngineHarness(configuration: configuration) try await harness.start() try harness.add([1]) let overflow = engineWindow(2) harness.world.appear(overflow) try harness.scheduler.runReady() let userFrame = Rect(x: 80, y: 108, width: 360, height: 240) harness.world.userFrame(overflow.id, frame: userFrame, resized: true) try harness.scheduler.runReady() try harness.finishMotion(after: 0.03) #expect(harness.engine.snapshot.state.frames[overflow.id] == userFrame) #expect(harness.world.frames[overflow.id] == userFrame) #expect(harness.world.writes(for: overflow.id).isEmpty) await harness.engine.stop() } @Test(arguments: [false, true]) func duplicateOverflowDiscoveryWritesCenteredNativeFrame(withTileRule: Bool) async throws { var configuration = engineConfiguration() configuration.layout.global.windowCap = 1 configuration.layout.global.whenFull = .float if withTileRule { configuration.rules = [RuleConfiguration(bundleID: engineApp.bundleID, action: .tile)] } let harness = try EngineHarness(configuration: configuration) try await harness.start() try harness.add([1]) let overflow = engineWindow(2) harness.world.appear(overflow) harness.world.appear(overflow) try harness.scheduler.runReady() try harness.finishMotion(after: 0.03) let centered = Rect(x: 450, y: 300, width: 300, height: 200) #expect(harness.engine.snapshot.state.frames[overflow.id] == centered) #expect(harness.world.frames[overflow.id] == centered) #expect(harness.world.writes(for: overflow.id).count == 1) await harness.engine.stop() } @Test(arguments: ConfigLayout.allCases.filter { $0 != .accordion }, [0.6, 2.0 / 3.0]) func savedMainSizeAppliesWhenTheSecondWindowArrives(layout: ConfigLayout, ratio: Double) async throws { var configuration = engineConfiguration(layout: layout) configuration.layout.global.ratio = ratio let harness = try EngineHarness(configuration: configuration) try await harness.start() try harness.add([1, 2]) try harness.finishMotion() let frames = harness.engine.snapshot.state.frames let first = try #require(frames[WindowID(rawValue: 1)]) let second = try #require(frames[WindowID(rawValue: 2)]) let firstArea = first.size.width * first.size.height let secondArea = second.size.width * second.size.height #expect(abs(firstArea / (firstArea + secondArea) - ratio) < 0.002) #expect(harness.world.frames[WindowID(rawValue: 1)] == first) #expect(harness.world.frames[WindowID(rawValue: 2)] == second) await harness.engine.stop() } @Test func appWideFloatRuleReclassifiesExistingWindows() async throws { let harness = try EngineHarness() try await harness.start() try harness.add([1], app: engineApp) try harness.add([2], app: secondEngineApp) try harness.finishMotion() let firstBefore = try #require(harness.engine.snapshot.state.frames[WindowID(rawValue: 1)]) var configuration = harness.engine.configuration configuration.rules.append(RuleConfiguration(bundleID: engineApp.bundleID, action: .float)) try harness.engine.applyConfiguration(configuration) try harness.scheduler.runReady() try harness.finishMotion() let state = harness.engine.snapshot.state #expect(state.windows[WindowID(rawValue: 1)]?.isFloating == true) #expect(state.windows[WindowID(rawValue: 2)]?.isFloating == false) #expect(state.frames[WindowID(rawValue: 1)] == firstBefore) #expect(state.frames[WindowID(rawValue: 2)] == engineScreen) #expect(harness.world.frames[WindowID(rawValue: 2)] == engineScreen) await harness.engine.stop() } @Test func hotGeometryRebuildsLayoutWithGapsRatioReservedEdgesAndCap() async throws { let harness = try EngineHarness() try await harness.start() try harness.add([1, 2, 3]) let before = harness.engine.layoutPassCount var configuration = harness.engine.configuration configuration.layout.global = LayoutValues( defaultLayout: .side, ratio: 0.7, gaps: LayoutGaps(inner: 20, outer: 10), reserved: ReservedEdges(top: 30), windowCap: 2 ) try harness.engine.applyConfiguration(configuration) #expect(harness.scheduler.pendingCount == 1) try harness.scheduler.runReady() try harness.finishMotion() let workspace = try #require(harness.engine.snapshot.state.workspaces[engineWorkspace]) #expect(harness.engine.layoutPassCount == before + 1) #expect(workspace.layout == .side) #expect(workspace.ratio == MainRatio(0.7)) #expect(workspace.gaps == Gaps(inner: 20, outer: Insets(10))) #expect(workspace.reservedEdges == Insets(top: 30)) #expect(workspace.windowCap == 2) #expect(workspace.tree?.tileCount == 2) #expect( harness.engine.snapshot.state.frames[WindowID(rawValue: 1)] == Rect(x: 10, y: 40, width: 812, height: 750)) #expect( harness.engine.snapshot.state.frames[WindowID(rawValue: 3)] == Rect(x: 842, y: 40, width: 348, height: 750)) #expect( harness.world.frames[WindowID(rawValue: 3)] == harness.engine.snapshot.state.frames[WindowID(rawValue: 3)]) #expect(harness.engine.isIdle) await harness.engine.stop() } enum ReturningGeometry: CaseIterable, Sendable { case outerGap, innerGap, reservedEdges, layout, windowCap, ratio func change(_ configuration: inout ParcelConfiguration) { switch self { case .outerGap: configuration.layout.global.gaps.outer = 23 case .innerGap: configuration.layout.global.gaps.inner = 20 case .reservedEdges: configuration.layout.global.reserved.top = 40 case .layout: configuration.layout.global.defaultLayout = .columns case .windowCap: configuration.layout.global.windowCap = 2 case .ratio: configuration.layout.global.ratio = 0.7 } } } @Test(arguments: ReturningGeometry.allCases, [false, true]) func hotGeometryReturnReappliesEarlierFrames(edit: ReturningGeometry, glide: Bool) async throws { let original = engineConfiguration(glide: glide, layout: .side) let harness = try EngineHarness(configuration: original) harness.world.emitsEngineEchoes = true try await harness.start() try harness.add([1, 2, 3]) try harness.finishMotion() let frames = harness.world.frames let passes = harness.engine.layoutPassCount var changed = original edit.change(&changed) try harness.engine.applyConfiguration(changed) try harness.scheduler.runReady() try harness.finishMotion() #expect(harness.world.frames != frames) try harness.engine.applyConfiguration(original) try harness.scheduler.runReady() try harness.finishMotion() #expect(harness.engine.snapshot.state.frames == frames) #expect(harness.world.frames == frames) #expect(harness.engine.layoutPassCount == passes + 2) #expect(harness.engine.isIdle) await harness.engine.stop() } @Test(arguments: [false, true]) func rapidGeometryReturnsDoNotBlockContainedResizeGridAdjustments(reserved: Bool) async throws { let original = engineConfiguration() let harness = try EngineHarness(configuration: original) harness.world.behaviors[engineApp] = .init(widthMultiple: 7) try await harness.start() try harness.add([1, 2]) var configuration = original for value in [17.0, 23, 0, 17, 23, 0, 17, 23, 0] { if reserved { configuration.layout.global.reserved.top = value } else { configuration.layout.global.gaps.outer = value } try harness.engine.applyConfiguration(configuration) try harness.scheduler.runReady() try harness.scheduler.advance(by: 0.02) for (window, target) in harness.engine.snapshot.state.frames { let expected = Rect( origin: target.origin, size: Size(width: (target.size.width / 7).rounded(.down) * 7, height: target.size.height)) #expect(harness.world.frames[window] == expected) } #expect(harness.engine.isIdle) } await harness.engine.stop() } @Test func perDisplayConfigurationDoesNotChangeOtherWorkspace() async throws { let harness = try EngineHarness(initialState: engineInitialState(twoDisplays: true)) try await harness.start() try harness.add([1, 2]) let secondWorkspace = WorkspaceKey(display: secondEngineDisplay, space: SpaceID(rawValue: 2)) try harness.add([3, 4], workspace: secondWorkspace) let originalFirst = harness.engine.snapshot.state.workspaces[engineWorkspace] var configuration = harness.engine.configuration let uuid = try #require(UUID(uuidString: secondEngineDisplay.rawValue)) configuration.layout.displays[uuid] = LayoutValues(defaultLayout: .rows, gaps: LayoutGaps(inner: 12, outer: 6)) try harness.engine.applyConfiguration(configuration) try harness.scheduler.runReady() try harness.finishMotion() #expect(harness.engine.snapshot.state.workspaces[engineWorkspace] == originalFirst) #expect(harness.engine.snapshot.state.workspaces[secondWorkspace]?.layout == .rows) #expect( harness.engine.snapshot.state.frames[WindowID(rawValue: 3)] == Rect(x: 1206, y: 6, width: 1188, height: 388) ) #expect( harness.engine.snapshot.state.frames[WindowID(rawValue: 4)] == Rect(x: 1206, y: 406, width: 1188, height: 388)) await harness.engine.stop() } @Test func floatRulesHotReloadAndRemovalPreserveIntrinsicFloating() async throws { let harness = try EngineHarness() try await harness.start() let matched = engineWindow(1, title: "Inspector 12") let unmatched = engineWindow(2, title: "Document") let intrinsic = engineWindow(3, app: secondEngineApp, floating: true) harness.world.appear(matched) harness.world.appear(unmatched) harness.world.appear(intrinsic) try harness.scheduler.runReady() let oldFocus = harness.engine.snapshot.focusedWindow var configuration = harness.engine.configuration configuration.floatRules = [ FloatRule(bundleID: engineApp.bundleID, titleRegex: "^Inspector [0-9]+$", role: "AXWindow") ] try harness.engine.applyConfiguration(configuration) try harness.scheduler.runReady() try harness.finishMotion() #expect(harness.engine.snapshot.state.windows[matched.id]?.isFloating == true) #expect(harness.engine.snapshot.state.windows[unmatched.id]?.isFloating == false) #expect(harness.engine.snapshot.state.windows[intrinsic.id]?.isFloating == true) #expect(harness.engine.snapshot.focusedWindow == oldFocus) #expect(harness.engine.snapshot.state.workspaces[engineWorkspace]?.tree?.windows == [unmatched.id]) configuration.floatRules = [] try harness.engine.applyConfiguration(configuration) try harness.scheduler.runReady() try harness.finishMotion() #expect(harness.engine.snapshot.state.windows[matched.id]?.isFloating == false) #expect(harness.engine.snapshot.state.windows[intrinsic.id]?.isFloating == true) #expect(harness.engine.snapshot.state.workspaces[engineWorkspace]?.tree?.windows.contains(matched.id) == true) #expect(harness.engine.snapshot.focusedWindow == oldFocus) await harness.engine.stop() } @Test func nonGeometryConfigurationKeepsCommandSelectedLayout() async throws { let harness = try EngineHarness() try await harness.start() try harness.add([1, 2]) harness.engine.send(.commandIssued(.setLayout(.rows))) try harness.scheduler.runReady() try harness.finishMotion() var configuration = harness.engine.configuration configuration.accessibility.announceLayoutChanges = true configuration.motion.speed = 2 try harness.engine.applyConfiguration(configuration) try harness.scheduler.runReady() #expect(harness.engine.snapshot.layouts[engineDisplay] == .rows) harness.engine.send(.commandIssued(.setLayout(.side))) try harness.scheduler.runReady() #expect(harness.announcer.announcements.contains(.layoutChanged(.side))) #expect(!harness.announcer.announcements.contains(.layoutChanged(.rows))) await harness.engine.stop() } @Test(arguments: [false, true]) func hotMotionDisableSettlesExistingAnimation(useReduceMotion: Bool) async throws { let harness = try EngineHarness(configuration: engineConfiguration(glide: true)) try await harness.start() try harness.add([1, 2]) #expect(harness.links.runningCount == 1) try harness.scheduler.advance(by: 0.05) if useReduceMotion { harness.engine.setReduceMotion(true) } else { var configuration = harness.engine.configuration configuration.motion.enabled = false try harness.engine.applyConfiguration(configuration) try harness.scheduler.runReady() } try harness.scheduler.runReady() #expect(harness.links.runningCount == 0) #expect(harness.world.frames == harness.engine.snapshot.state.frames) #expect(harness.engine.isIdle) let writes = harness.world.writes.count try harness.finishMotion() #expect(harness.world.writes.count == writes) await harness.engine.stop() } @Test func appearanceReloadDoesNotRelayoutOrWriteWindowFrames() async throws { let harness = try EngineHarness() try await harness.start() try harness.add([1, 2]) let before = harness.engine.snapshot let count = harness.engine.layoutPassCount let writes = harness.world.writes.count var configuration = harness.engine.configuration configuration.appearance = .init(palette: .kiln, mode: .dark, borderOpacity: 0.5, borderRadius: 16) try harness.engine.applyConfiguration(configuration) #expect(harness.engine.configuration.appearance == configuration.appearance) #expect(harness.scheduler.pendingCount == 0 && harness.engine.layoutPassCount == count) #expect(harness.engine.snapshot == before && harness.world.writes.count == writes) await harness.engine.stop() } @Test func unchangedConfigurationDoesNotScheduleAnotherPass() async throws { let harness = try EngineHarness() try await harness.start() let count = harness.engine.layoutPassCount try harness.engine.applyConfiguration(harness.engine.configuration) #expect(harness.scheduler.pendingCount == 0) #expect(harness.engine.layoutPassCount == count) await harness.engine.stop() } @Test func invalidHotConfigurationLeavesStateAndMotionUntouched() async throws { let harness = try EngineHarness(configuration: engineConfiguration(glide: true)) try await harness.start() try harness.add([1, 2]) let before = harness.engine.snapshot let previous = harness.engine.configuration var invalid = previous invalid.layout.global.gaps.inner = -1 #expect(throws: EngineError.self) { try harness.engine.applyConfiguration(invalid) } invalid = previous invalid.motion.speed = .infinity #expect(throws: EngineError.self) { try harness.engine.applyConfiguration(invalid) } invalid = previous invalid.floatRules = [FloatRule(titleRegex: "[")] #expect(throws: (any Error).self) { try harness.engine.applyConfiguration(invalid) } #expect(harness.engine.configuration == previous) #expect(harness.engine.snapshot == before) #expect(harness.links.runningCount == 1) #expect(harness.scheduler.pendingCount == 0) try harness.finishMotion() await harness.engine.stop() } } @Suite("Engine adaptive layout configuration") @MainActor struct ParcelEngineAdaptiveConfigurationTests { private let portrait = Rect(x: 0, y: 0, width: 800, height: 1200) @Test(arguments: [ Rect(x: 0, y: 0, width: 800, height: 1200), Rect(x: 0, y: 0, width: 1200, height: 800), Rect(x: 0, y: 0, width: 1000, height: 1000), ]) func initializationChoosesDefaultFromDisplayFrame(_ screen: Rect) throws { let state = State( displays: [Display(id: engineDisplay, frame: screen)], activeSpaces: [engineDisplay: engineSpace]) var configuration = engineConfiguration(layout: .side) configuration.layout.global.windowCap = 100 let harness = try EngineHarness(configuration: configuration, initialState: state) let workspace = try #require(harness.engine.snapshot.state.workspaces[engineWorkspace]) #expect(workspace.layout == (screen.size.height > screen.size.width ? .rows : .side)) #expect(workspace.displaySize == screen.size) #expect(workspace.layoutVariant == workspace.layout.capabilities(in: screen).variant) #expect(workspace.effectiveWindowCap == workspace.layout.capabilities(in: screen).maximumWindowCount) } @Test func queuedDisplayAndSpaceCreationUsePortraitDefaultsAndOverrides() async throws { var configuration = engineConfiguration() configuration.layout.global.portraitLayout = .side let uuid = try #require(UUID(uuidString: secondEngineDisplay.rawValue)) var override = configuration.layout.global override.portraitLayout = .tree configuration.layout.displays[uuid] = override let harness = try EngineHarness(configuration: configuration, initialState: State()) try await harness.start() harness.world.emit( .observed( .displaySetChanged([ Display(id: engineDisplay, frame: portrait), Display(id: secondEngineDisplay, frame: portrait), ]))) harness.world.emit(.observed(.activeSpaceChanged(display: engineDisplay, space: engineSpace))) harness.world.appear(engineWindow(1)) let secondKey = WorkspaceKey(display: secondEngineDisplay, space: SpaceID(rawValue: 2)) harness.world.appear(engineWindow(2), workspace: secondKey) try harness.scheduler.runReady() #expect(harness.engine.snapshot.state.workspaces[engineWorkspace]?.layout == .side) #expect(harness.engine.snapshot.state.workspaces[engineWorkspace]?.layoutVariant == .portrait) #expect(harness.engine.snapshot.state.workspaces[secondKey]?.layout == .tree) #expect(harness.engine.snapshot.state.workspaces[secondKey]?.displaySize == portrait.size) let freshKey = WorkspaceKey(display: engineDisplay, space: SpaceID(rawValue: 3)) harness.world.emit(.observed(.activeSpaceChanged(display: engineDisplay, space: freshKey.space))) try harness.scheduler.runReady() #expect(harness.engine.snapshot.state.workspaces[freshKey]?.layout == .side) #expect(harness.engine.snapshot.state.workspaces[freshKey]?.displaySize == portrait.size) await harness.engine.stop() } @Test(arguments: [false, true]) func invalidQueuedDisplaysDoNotChangeDefaultsForFollowingWorkspace(_ duplicate: Bool) async throws { let state = State( displays: [Display(id: engineDisplay, frame: portrait)], activeSpaces: [engineDisplay: engineSpace]) let harness = try EngineHarness(initialState: state) try await harness.start() let invalid = duplicate ? [Display(id: engineDisplay, frame: engineScreen), Display(id: engineDisplay, frame: engineScreen)] : [Display(id: engineDisplay, frame: Rect(x: 0, y: 0, width: -1, height: 800))] let key = WorkspaceKey(display: engineDisplay, space: SpaceID(rawValue: 2)) harness.world.emit(.observed(.displaySetChanged(invalid))) harness.world.emit(.observed(.activeSpaceChanged(display: engineDisplay, space: key.space))) try harness.scheduler.runReady() #expect(harness.log.reports.contains(.invalidGeometry)) #expect(harness.engine.snapshot.state.displays[engineDisplay]?.frame == portrait) #expect(harness.engine.snapshot.state.workspaces[key]?.layout == .rows) #expect(harness.engine.snapshot.state.workspaces[key]?.displaySize == portrait.size) await harness.engine.stop() } @Test func rotationTransformsRuntimeLayoutWithoutReplacingItsSelectionOrRequestedCap() async throws { let harness = try EngineHarness(configuration: engineConfiguration(layout: .grid)) try await harness.start() try harness.add([1, 2, 3]) harness.engine.send(.commandIssued(.setLayout(.columns))) harness.engine.send(.commandIssued(.setWindowCap(2))) try harness.scheduler.runReady() for screen in [portrait, engineScreen] { harness.world.emit(.observed(.displaySetChanged([Display(id: engineDisplay, frame: screen)]))) try harness.scheduler.runReady() let workspace = try #require(harness.engine.snapshot.state.workspaces[engineWorkspace]) #expect(workspace.layout == .columns) #expect(workspace.windowCap == 2) #expect(workspace.effectiveWindowCap == 2) #expect(workspace.layoutVariant == Layout.columns.capabilities(in: screen).variant) #expect(workspace.displaySize == screen.size) #expect(workspace.order.count == 3) #expect(workspace.tree?.tileCount == 2) } await harness.engine.stop() } @Test func portraitDefaultReloadUsesCurrentOrientationAndDisplayOverrides() throws { let secondKey = WorkspaceKey(display: secondEngineDisplay, space: SpaceID(rawValue: 2)) let state = State( displays: [ Display(id: engineDisplay, frame: engineScreen), Display(id: secondEngineDisplay, frame: portrait), ], activeSpaces: [engineDisplay: engineSpace, secondEngineDisplay: secondKey.space]) var configuration = engineConfiguration(layout: .columns) let harness = try EngineHarness(configuration: configuration, initialState: state) #expect(harness.engine.snapshot.state.workspaces[secondKey]?.layout == .rows) let first = harness.engine.snapshot.state.workspaces[engineWorkspace] configuration.layout.global.portraitLayout = .side try harness.engine.applyConfiguration(configuration) #expect(harness.engine.snapshot.state.workspaces[engineWorkspace]?.tree == first?.tree) #expect(harness.engine.snapshot.state.workspaces[engineWorkspace]?.layout == first?.layout) #expect(harness.engine.snapshot.state.workspaces[engineWorkspace]?.layoutDefaults?.portrait == .side) #expect(harness.engine.snapshot.state.workspaces[secondKey]?.layout == .side) #expect(harness.engine.snapshot.state.workspaces[secondKey]?.layoutVariant == .portrait) let uuid = try #require(UUID(uuidString: secondEngineDisplay.rawValue)) var override = configuration.layout.global override.portraitLayout = .bsp configuration.layout.displays[uuid] = override try harness.engine.applyConfiguration(configuration) #expect(harness.engine.snapshot.state.workspaces[secondKey]?.layout == .bsp) configuration.layout.global.defaultLayout = .grid try harness.engine.applyConfiguration(configuration) #expect(harness.engine.snapshot.state.workspaces[engineWorkspace]?.layout == .grid) #expect(harness.engine.snapshot.state.workspaces[secondKey]?.layout == .bsp) } @Test func unrelatedGeometryReloadPreservesCustomSplitsAndRuntimeRatioAndCap() async throws { var initialConfiguration = engineConfiguration(layout: .side) initialConfiguration.layout.global.windowCap = 100 let harness = try EngineHarness(configuration: initialConfiguration) try await harness.start() try harness.add([1, 2, 3]) let initialTree = harness.engine.snapshot.state.workspaces[engineWorkspace]?.tree let edge = try #require(harness.engine.snapshot.state.tileEdges.first) harness.engine.send(.tileEdgeResized(edge, delta: 60)) harness.engine.send(.commandIssued(.setRatio(.threeFifths))) harness.engine.send(.commandIssued(.setWindowCap(3))) try harness.scheduler.runReady() let before = try #require(harness.engine.snapshot.state.workspaces[engineWorkspace]) #expect(before.ratio == .threeFifths) #expect(before.windowCap == 3) #expect(before.tree != initialTree) var configuration = harness.engine.configuration configuration.layout.global.gaps.inner = 12 configuration.layout.global.reserved.top = 20 configuration.layout.global.portraitLayout = .side configuration.layout.global.whenFull = .float try harness.engine.applyConfiguration(configuration) try harness.scheduler.runReady() let after = try #require(harness.engine.snapshot.state.workspaces[engineWorkspace]) #expect(after.tree == before.tree) #expect(after.ratio == before.ratio) #expect(after.windowCap == before.windowCap) #expect(after.whenFull == .float) #expect(after.gaps.inner == 12) #expect(after.reservedEdges.top == 20) await harness.engine.stop() } @Test(arguments: [false, true]) func changedRatioReloadUpdatesMaterializedSideSplit(_ isPortrait: Bool) async throws { let screen = isPortrait ? portrait : engineScreen let state = State( displays: [Display(id: engineDisplay, frame: screen)], activeSpaces: [engineDisplay: engineSpace]) var configuration = engineConfiguration(layout: .side) configuration.layout.global.portraitLayout = .side let harness = try EngineHarness(configuration: configuration, initialState: state) try await harness.start() try harness.add([1, 2]) configuration.layout.global.ratio = 0.7 try harness.engine.applyConfiguration(configuration) try harness.scheduler.runReady() let workspace = try #require(harness.engine.snapshot.state.workspaces[engineWorkspace]) #expect(workspace.ratio == MainRatio(0.7)) let main = try #require(harness.engine.snapshot.state.frames[WindowID(rawValue: 1)]) #expect(isPortrait ? main.size.height == 840 : main.size.width == 840) await harness.engine.stop() } @Test(arguments: [1, 5, 100], [ConfigLayout.grid, .rows, .side, .tree]) func configuredCapsKeepRequestedValuesAndEnforceCapabilities(_ requested: Int, _ layout: ConfigLayout) async throws { var configuration = engineConfiguration(layout: layout) configuration.layout.global.windowCap = requested let harness = try EngineHarness(configuration: configuration) try await harness.start() try harness.add([1, 2, 3, 4, 5, 6, 7]) let workspace = try #require(harness.engine.snapshot.state.workspaces[engineWorkspace]) let cap = min(requested, workspace.layout.capabilities(in: engineScreen).maximumWindowCount) #expect(workspace.windowCap == requested) #expect(workspace.effectiveWindowCap == cap) #expect(workspace.tree?.tileCount == min(7, cap)) #expect(workspace.order.count == 7) #expect(workspace.tree?.windows.count == 7) #expect(workspace.visibleWindows.contains(WindowID(rawValue: 7))) await harness.engine.stop() } @Test(arguments: [ConfigLayout.grid, .rows, .side, .tree], [ConfigWhenFull.stack, .float]) func explicitZeroCapRemainsUnlimitedRegardlessOfLayoutOrOverflowPolicy( _ layout: ConfigLayout, _ policy: ConfigWhenFull ) async throws { var configuration = engineConfiguration(layout: layout) configuration.layout.global.windowCap = 0 configuration.layout.global.whenFull = policy let harness = try EngineHarness(configuration: configuration) try await harness.start() try harness.add([1, 2, 3, 4, 5, 6, 7]) let workspace = try #require(harness.engine.snapshot.state.workspaces[engineWorkspace]) #expect(workspace.windowCap == Int.max) #expect(workspace.effectiveWindowCap == Int.max) #expect(workspace.tree?.tileCount == 7) #expect(workspace.order.count == 7) #expect(harness.engine.snapshot.state.windows.values.allSatisfy { !$0.isFloating }) await harness.engine.stop() } @Test func capReloadKeepsRuntimeLayoutAndAppliesOnlyEffectiveCapability() async throws { let harness = try EngineHarness(configuration: engineConfiguration(layout: .grid)) try await harness.start() try harness.add([1, 2, 3, 4, 5]) harness.engine.send(.commandIssued(.setLayout(.rows))) try harness.scheduler.runReady() var configuration = harness.engine.configuration for requested in [1, 100, 0] { configuration.layout.global.windowCap = requested try harness.engine.applyConfiguration(configuration) try harness.scheduler.runReady() let workspace = try #require(harness.engine.snapshot.state.workspaces[engineWorkspace]) #expect(workspace.layout == .rows) #expect(workspace.windowCap == (requested == 0 ? Int.max : requested)) #expect(workspace.effectiveWindowCap == (requested == 0 ? Int.max : min(requested, 2))) #expect(workspace.order.count == 5) #expect(workspace.focus == WindowID(rawValue: 5)) } await harness.engine.stop() } @Test(arguments: 1...5) func capCommandsBridgeToRuntimeRequestedAndEffectiveCaps(_ cap: Int) async throws { var configuration = engineConfiguration(layout: .grid) configuration.layout.global.windowCap = 100 let harness = try EngineHarness(configuration: configuration) try await harness.start() try harness.add([1, 2, 3, 4, 5]) harness.engine.send(.commandIssued(try EngineCommandParser.parse("set-window-cap \(cap)"))) try harness.scheduler.runReady() let workspace = try #require(harness.engine.snapshot.state.workspaces[engineWorkspace]) #expect(workspace.windowCap == cap) #expect(harness.log.reports.contains(.layoutCapabilityLimit(layout: .grid, maximum: 4))) #expect(!harness.log.reports.contains(.atWindowCap(4))) #expect(workspace.effectiveWindowCap == min(cap, 4)) #expect(workspace.tree?.tileCount == min(cap, 4)) #expect(workspace.order.count == 5) #expect(workspace.focus == WindowID(rawValue: 5)) await harness.engine.stop() } } @Suite("Engine configuration subscriptions") @MainActor struct ParcelEngineConfigurationSourceTests { @Test func sourceStartupAppliesInitialConfigurationAndStopUnsubscribes() async throws { let initial = engineConfiguration(layout: .rows) let source = FakeEngineConfigurationSource(initial: initial) let harness = try EngineHarness(configSource: source) try await harness.start() #expect(source.startCount == 1) #expect(source.isSubscribed) #expect(harness.world.startCount == 1) #expect(harness.engine.configuration == initial) try harness.add([1, 2]) #expect(harness.engine.snapshot.layouts[engineDisplay] == .rows) #expect( harness.engine.snapshot.state.frames[WindowID(rawValue: 2)] == Rect(x: 0, y: 400, width: 1200, height: 400)) try await harness.engine.start() #expect(source.startCount == 1) await harness.engine.stop() #expect(source.stopCount == 1) #expect(!source.isSubscribed) #expect(harness.scheduler.pendingCount == 0) } @Test func hotSubscriptionUpdatesCoalesceIntoOneFinalLayout() async throws { let source = FakeEngineConfigurationSource() let harness = try EngineHarness(configSource: source) try await harness.start() try harness.add([1, 2]) let passes = harness.engine.layoutPassCount let store = ConfigStore() let rows = await store.load( source: "[layout]\ndefault = \"rows\"\n[layout.gaps]\ninner = 0\nouter = 0\n[motion]\ntransitions = \"snap\"\n") let side = await store.load( source: "[layout]\ndefault = \"side\"\nratio = 0.7\n[layout.gaps]\ninner = 20\nouter = 10\n[motion]\ntransitions = \"snap\"\n" ) try #require(rows.loadState == .loaded) try #require(side.loadState == .loaded) source.emit(rows) source.emit(side) #expect(harness.scheduler.pendingCount == 1) try harness.scheduler.runReady() try harness.finishMotion() #expect(harness.engine.layoutPassCount == passes + 1) #expect(harness.engine.configuration == side.activeConfiguration) #expect(harness.engine.snapshot.layouts[engineDisplay] == .side) #expect( harness.engine.snapshot.state.frames[WindowID(rawValue: 1)] == Rect(x: 10, y: 10, width: 812, height: 780)) #expect( harness.engine.snapshot.state.frames[WindowID(rawValue: 2)] == Rect(x: 842, y: 10, width: 348, height: 780)) #expect(harness.engine.isIdle) await harness.engine.stop() } @Test(arguments: [false, true], [false, true]) func subscriptionGeometryReturnsRecoverAfterRejectedEdit(glide: Bool, resizeGrid: Bool) async throws { let store = ConfigStore() func load(outer: Double, reservedTop: Double = 0) async -> ConfigSnapshot { await store.load( source: """ [layout] default = "columns" [layout.gaps] inner = 0 outer = \(outer) [layout.reserved] top = \(reservedTop) [motion] transitions = "\(glide ? "glide" : "snap")" """) } let original = await load(outer: 16) try #require(original.loadState == .loaded) let source = FakeEngineConfigurationSource(initial: original.activeConfiguration) let harness = try EngineHarness(configSource: source) harness.world.emitsEngineEchoes = true if resizeGrid { harness.world.behaviors[secondEngineApp] = .init(widthMultiple: 7) } try await harness.start() try harness.add([1]) try harness.add([2], app: secondEngineApp) try harness.finishMotion(after: glide ? 1 : 0.02) let originalFrames = harness.world.frames let passes = harness.engine.layoutPassCount let sequence = [(17.0, 0.0), (23.0, 0.0), (16.0, 0.0), (16.0, 14.0), (16.0, 0.0)] for (outer, reservedTop) in sequence { let update = await load(outer: outer, reservedTop: reservedTop) try #require(update.loadState == .loaded) let writes = harness.world.allWrites.count source.emit(update) try harness.scheduler.runReady() try harness.finishMotion(after: glide ? 1 : 0.02) #expect(harness.engine.configuration == update.activeConfiguration) #expect(harness.world.allWrites.count > writes) let width = (engineScreen.size.width - 2 * outer) / 2 for id in [UInt32(1), 2] { let window = WindowID(rawValue: id) let target = Rect( x: outer + Double(id - 1) * width, y: outer + reservedTop, width: width, height: engineScreen.size.height - 2 * outer - reservedTop) var accepted = target if resizeGrid, id == 2 { accepted.size.width = (width / 7).rounded(.down) * 7 } #expect(harness.engine.snapshot.state.frames[window] == target) #expect(harness.world.frames[window] == accepted) #expect(harness.engine.snapshot.readbackFrames[window] == accepted) } #expect(harness.engine.isIdle) if outer == 16, reservedTop == 0 { #expect(harness.world.frames == originalFrames) } if outer == 23 { let before = harness.engine.snapshot let writesBeforeRejection = harness.world.allWrites.count let passesBeforeRejection = harness.engine.layoutPassCount let rejected = await store.load(source: "[layout.gaps]\nouter = -1\n") try #require(rejected.loadState == .rejected) source.emit(rejected) try harness.scheduler.runReady() #expect(harness.engine.configuration == update.activeConfiguration) #expect(harness.engine.snapshot == before) #expect(harness.world.allWrites.count == writesBeforeRejection) #expect(harness.engine.layoutPassCount == passesBeforeRejection) #expect( harness.log.diagnostics.contains { diagnostic in if case .config(let diagnostics) = diagnostic { diagnostics == rejected.diagnostics } else { false } }) } } #expect(harness.engine.layoutPassCount == passes + sequence.count) #expect(harness.log.platformFailures.isEmpty) #expect(harness.log.motionErrors.isEmpty) #expect(harness.engine.isIdle) await harness.engine.stop() #expect(!source.isSubscribed) #expect(harness.scheduler.pendingCount == 0) } @Test func rejectedSubscriptionUpdateSurfacesDiagnosticsAndKeepsLastGood() async throws { let store = ConfigStore() let good = await store.load(source: "[layout]\ndefault = \"side\"\nratio = 0.7\n[motion]\nenabled = false\n") let source = FakeEngineConfigurationSource(initial: good.activeConfiguration) let harness = try EngineHarness(configSource: source) try await harness.start() let before = harness.engine.snapshot let rejected = await store.load(source: "[layout]\nratio = 8\n") try #require(rejected.loadState == .rejected) source.emit(rejected) #expect(harness.engine.configuration == good.activeConfiguration) #expect(harness.engine.snapshot == before) #expect(harness.scheduler.pendingCount == 0) #expect( harness.log.diagnostics.contains { diagnostic in if case .config(let diagnostics) = diagnostic { diagnostics == rejected.diagnostics } else { false } }) await harness.engine.stop() } @Test func stoppedAndPreviousLifetimeSubscriptionsCannotChangeConfiguration() async throws { let source = FakeEngineConfigurationSource() let harness = try EngineHarness(configSource: source) let store = ConfigStore() let update = await store.load(source: "[layout]\ndefault = \"rows\"\n[motion]\nenabled = false\n") try await harness.start() await harness.engine.stop() let stopped = harness.engine.snapshot source.emitFromStart(0, snapshot: update) #expect(harness.engine.snapshot == stopped) #expect(harness.engine.configuration == source.initial) #expect(harness.scheduler.pendingCount == 0) try await harness.start() let restarted = harness.engine.snapshot source.emitFromStart(0, snapshot: update) #expect(harness.engine.snapshot == restarted) #expect(harness.engine.configuration == source.initial) source.emit(update) try harness.scheduler.runReady() #expect(harness.engine.configuration == update.activeConfiguration) #expect(harness.engine.snapshot.layouts[engineDisplay] == .rows) await harness.engine.stop() #expect(source.startCount == 2) #expect(source.stopCount == 2) } @Test func failedSubscriptionStartStopsSourceBeforeStartingWorld() async throws { let source = FakeEngineConfigurationSource() source.startError = .startup let harness = try EngineHarness(configSource: source) await #expect(throws: HarnessError.self) { try await harness.engine.start() } #expect(source.startCount == 1) #expect(source.stopCount == 1) #expect(!source.isSubscribed) #expect(harness.world.startCount == 0) #expect(!harness.engine.isRunning) #expect(harness.engine.isIdle) #expect(harness.scheduler.pendingCount == 0) } @Test func stoppingDuringDeferredSubscriptionStartRejectsLateInitialConfiguration() async throws { let source = FakeEngineConfigurationSource(initial: engineConfiguration(layout: .rows)) source.deferStart = true let harness = try EngineHarness(configSource: source) let startup = Task { @MainActor in try await harness.engine.start() } for _ in 0..<100 where !source.isAwaitingStart { await Task.yield() } try #require(source.isAwaitingStart) await harness.engine.stop() try source.completeStart() await #expect(throws: EngineError.stopped) { try await startup.value } #expect(harness.engine.configuration == engineConfiguration()) #expect(harness.world.startCount == 0) #expect(!source.isSubscribed) #expect(!harness.engine.isRunning) #expect(harness.engine.isIdle) #expect(harness.scheduler.pendingCount == 0) } }