From 87f399cfbfd08d0fd48becff4657b715d30530af Mon Sep 17 00:00:00 2001 From: Vincent Taverna Date: Sun, 1 Nov 2026 07:03:59 -0500 Subject: [PATCH] Preserve tiling choices through Space changes Signed-off-by: Vincent Taverna --- Sources/ParcelApp/EngineShellServices.swift | 5 +-- Sources/ParcelApp/NativeAppRuntime.swift | 4 +-- Sources/ParcelEngine/EngineMouse.swift | 8 ++--- Sources/ParcelEngine/EngineRuleActions.swift | 21 ++++-------- Sources/ParcelEngine/EngineSpaces.swift | 23 +++++++++---- Sources/ParcelEngine/ParcelEngine.swift | 12 ++++--- Sources/ParcelUI/MenuWorkspace.swift | 16 ++++++--- Sources/ParcelUI/Resources/Menu.xcstrings | 20 +++++++++++ Tests/ParcelAppTests/MenuAppTests.swift | 34 +++++++++++++++++++ .../RuleSpaceAssignmentRegressionTests.swift | 17 ++++++++++ .../ParcelEngineTests/SpaceCommandTests.swift | 28 +++++++++++++-- Tests/ParcelUITests/MenuWorkspaceTests.swift | 6 ++-- docs/parcel.schema.json | 8 ++--- 13 files changed, 154 insertions(+), 48 deletions(-) diff --git a/Sources/ParcelApp/EngineShellServices.swift b/Sources/ParcelApp/EngineShellServices.swift index 3c2e17ae..4cd2c393 100644 --- a/Sources/ParcelApp/EngineShellServices.swift +++ b/Sources/ParcelApp/EngineShellServices.swift @@ -71,8 +71,9 @@ final class EngineShellServices: LayoutSnapshotProviding, UICommandSink { let workspace = snapshot.state.workspaces[WorkspaceKey(display: displayID, space: space)] else { return nil } let tiles = snapshot.tiles.filter { - snapshot.state.workspace(containing: $0.window)?.display == displayID && $0.frame.size.width > 0 - && $0.frame.size.height > 0 + snapshot.state.workspace(containing: $0.window) == key + && snapshot.state.windows[$0.window]?.isFloating == false + && $0.frame.size.width > 0 && $0.frame.size.height > 0 }.map { LayoutTile( id: UInt64($0.window.rawValue), frame: $0.frame.cgRect, isFocused: snapshot.focusedWindow == $0.window) diff --git a/Sources/ParcelApp/NativeAppRuntime.swift b/Sources/ParcelApp/NativeAppRuntime.swift index 86026c69..d662d0b6 100644 --- a/Sources/ParcelApp/NativeAppRuntime.swift +++ b/Sources/ParcelApp/NativeAppRuntime.swift @@ -1041,10 +1041,10 @@ extension NativeAppRuntime { .map { AppMenuSuspension.text($0.reason) } } - private func menuWorkspace( + func menuWorkspace( _ activation: MenuWorkspaceActivation ) -> Result { - guard let engine = services.engine, engine.isRunning else { return .failure(.disconnected) } + guard let engine = services.engine, engine.isRunning else { return .failure(.notRunning) } do { let displays = try DisplayNaming.screens() let screens = Dictionary(uniqueKeysWithValues: displays.map { ($0.id, $0.frame) }) diff --git a/Sources/ParcelEngine/EngineMouse.swift b/Sources/ParcelEngine/EngineMouse.swift index 026c2bc1..1643f029 100644 --- a/Sources/ParcelEngine/EngineMouse.swift +++ b/Sources/ParcelEngine/EngineMouse.swift @@ -12,7 +12,7 @@ extension ParcelEngine { } public var mouseGestureConsumesEscape: Bool { - isRunning && isAutomaticTilingEnabled && writesPermitted + isRunning && isAutomaticTilingEnabled && writesPermitted && !spaceCommandRunning && mouseModel.consumesEscape(state: snapshot.state, observedFrames: actualFrames) } @@ -23,7 +23,7 @@ extension ParcelEngine { cancelMouseGesture() return false } - guard isAutomaticTilingEnabled, writesPermitted else { + guard isAutomaticTilingEnabled, writesPermitted, !spaceCommandRunning else { cancelMouseGesture() return false } @@ -45,7 +45,7 @@ extension ParcelEngine { enqueue(.windowDragBegan(window)) flushMouseTurn() } - guard isAutomaticTilingEnabled, writesPermitted else { + guard isAutomaticTilingEnabled, writesPermitted, !spaceCommandRunning else { cancelMouseGesture() return false } @@ -68,7 +68,7 @@ extension ParcelEngine { if mouseModel.isActive || snapshot.state.undoGesture != nil { applyMouse(mouseModel.cancel(state: snapshot.state, awaitingMouseUp: false) + [.event(.undoGestureEnded)]) } - if !writesPermitted { + if !writesPermitted || spaceCommandRunning { dragging.removeAll() liveResizeWindows.removeAll() finalResizeWindows.removeAll() diff --git a/Sources/ParcelEngine/EngineRuleActions.swift b/Sources/ParcelEngine/EngineRuleActions.swift index 107fefeb..1a3c1ecd 100644 --- a/Sources/ParcelEngine/EngineRuleActions.swift +++ b/Sources/ParcelEngine/EngineRuleActions.swift @@ -98,11 +98,9 @@ extension ParcelEngine { return RuleSpaceAssignment(display: key.display, desktop: desktop) } - private func canAssignRuleSpace( - _ window: WindowID, assignment: RuleSpaceAssignment, allowingOperationHold: Bool = false - ) -> Bool { + private func canAssignRuleSpace(_ window: WindowID, assignment: RuleSpaceAssignment) -> Bool { isRunning && writesPermitted && eligibleRuleSpaceWindows.contains(window) - && (allowingOperationHold || isAutomaticTilingEnabled) + && isAutomaticTilingEnabled && !suspendedDisplays.contains(assignment.display) && currentRuleSpaceAssignment(for: window) == assignment } @@ -126,22 +124,17 @@ extension ParcelEngine { let destination = WorkspaceKey(display: assignment.display, space: SpaceID(rawValue: target.id)) guard current != destination else { return true } guard !spaceCommandRunning else { throw SpaceCommandError.busy } - spaceCommandRunning = true - let wasAutomaticTilingEnabled = isAutomaticTilingEnabled - setAutomaticTilingEnabled(false) - defer { - spaceCommandRunning = false - if wasAutomaticTilingEnabled { setAutomaticTilingEnabled(true) } - } + beginSpaceOperation() + defer { endSpaceOperation() } let deadline = ContinuousClock.now.advanced(by: .milliseconds(750)) while !busyApps.isEmpty || focusOperations > 0 || !windowOperations.isEmpty { - guard canAssignRuleSpace(window, assignment: assignment, allowingOperationHold: true) else { return false } + guard canAssignRuleSpace(window, assignment: assignment) else { return false } guard ContinuousClock.now < deadline else { throw SpaceCommandError.busy } try await Task.sleep(for: .milliseconds(10)) } try Task.checkCancellation() guard isRunning, lifetime == generation else { throw EngineError.stopped } - guard canAssignRuleSpace(window, assignment: assignment, allowingOperationHold: true) else { return false } + guard canAssignRuleSpace(window, assignment: assignment) else { return false } let result = try await spaceWorld.executeSpaceCommand( .desktop(assignment.desktop), display: assignment.display, window: window, follow: false) guard result.displayID.caseInsensitiveCompare(display.displayID) == .orderedSame, @@ -149,7 +142,7 @@ extension ParcelEngine { else { throw SpaceCommandError.moveNotVerified } try Task.checkCancellation() guard isRunning, lifetime == generation else { throw EngineError.stopped } - guard canAssignRuleSpace(window, assignment: assignment, allowingOperationHold: true) else { + guard canAssignRuleSpace(window, assignment: assignment) else { world.reconcile(Set(snapshot.state.windows.values.map(\.app))) return false } diff --git a/Sources/ParcelEngine/EngineSpaces.swift b/Sources/ParcelEngine/EngineSpaces.swift index d7baba9b..b81d23f2 100644 --- a/Sources/ParcelEngine/EngineSpaces.swift +++ b/Sources/ParcelEngine/EngineSpaces.swift @@ -97,13 +97,8 @@ extension ParcelEngine { } let window = move ? snapshot.focusedWindow : nil if move && window == nil { throw spaceFailure(.windowUnavailable) } - spaceCommandRunning = true - let wasAutomaticTilingEnabled = isAutomaticTilingEnabled - setAutomaticTilingEnabled(false) - defer { - spaceCommandRunning = false - if wasAutomaticTilingEnabled { setAutomaticTilingEnabled(true) } - } + beginSpaceOperation() + defer { endSpaceOperation() } do { let deadline = ContinuousClock.now.advanced(by: .milliseconds(750)) while !busyApps.isEmpty || focusOperations > 0 || !windowOperations.isEmpty { @@ -142,6 +137,20 @@ extension ParcelEngine { } } + func beginSpaceOperation() { + spaceCommandRunning = true + cancelMouseGesture() + suspendMotion() + } + + func endSpaceOperation() { + spaceCommandRunning = false + guard isRunning, isAutomaticTilingEnabled else { return } + snapNextPass = true + needsRetile = true + scheduleTurn() + } + func spaceFailure(_ error: SpaceCommandError) -> IPCError { spaceFailure(error as any Error) } func spaceFailure(_ error: any Error) -> IPCError { diff --git a/Sources/ParcelEngine/ParcelEngine.swift b/Sources/ParcelEngine/ParcelEngine.swift index 0d419025..def6dcda 100644 --- a/Sources/ParcelEngine/ParcelEngine.swift +++ b/Sources/ParcelEngine/ParcelEngine.swift @@ -728,16 +728,20 @@ extension ParcelEngine { && !spaceCommandRunning) } + func suspendMotion() { + for window in Array(placements.keys) { cancelMotion(window, remove: false) } + pumpWake?.cancel() + pumpWake = nil + settleIfIdle() + } + public func setAutomaticTilingEnabled(_ enabled: Bool, animatedResume: Bool = false) { guard isAutomaticTilingEnabled != enabled else { return } isAutomaticTilingEnabled = enabled publishPlacementState() if !enabled { cancelMouseGesture() } if !enabled { - for window in Array(placements.keys) { cancelMotion(window, remove: false) } - pumpWake?.cancel() - pumpWake = nil - settleIfIdle() + suspendMotion() } else { snapNextPass = !animatedResume needsRetile = true diff --git a/Sources/ParcelUI/MenuWorkspace.swift b/Sources/ParcelUI/MenuWorkspace.swift index 0f733afe..45a84ff2 100644 --- a/Sources/ParcelUI/MenuWorkspace.swift +++ b/Sources/ParcelUI/MenuWorkspace.swift @@ -16,16 +16,22 @@ public struct MenuWorkspace: Equatable, Sendable { public enum Unavailability: Error, Equatable, Sendable { case disconnected case unmanagedSpace + case notRunning var title: String { - MenuText.text(self == .disconnected ? "Display unavailable" : "Space not arranged") + switch self { + case .disconnected: MenuText.text("Display unavailable") + case .unmanagedSpace: MenuText.text("Space not arranged") + case .notRunning: MenuText.text("Tiling not started") + } } var detail: String { - MenuText.text( - self == .disconnected - ? "This display is unavailable. Reopen the menu on a connected display." - : "Parcel doesn’t arrange this Space (for example, a full-screen app).") + switch self { + case .disconnected: MenuText.text("This display is unavailable. Reopen the menu on a connected display.") + case .unmanagedSpace: MenuText.text("Parcel doesn’t arrange this Space (for example, a full-screen app).") + case .notRunning: MenuText.text("Not arranging this screen — tiling has not started") + } } } diff --git a/Sources/ParcelUI/Resources/Menu.xcstrings b/Sources/ParcelUI/Resources/Menu.xcstrings index c4c5130d..739fedd0 100644 --- a/Sources/ParcelUI/Resources/Menu.xcstrings +++ b/Sources/ParcelUI/Resources/Menu.xcstrings @@ -1,6 +1,26 @@ { "sourceLanguage": "en", "strings": { + "Tiling not started": { + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Tiling not started" + } + } + } + }, + "Not arranging this screen — tiling has not started": { + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Not arranging this screen — tiling has not started" + } + } + } + }, "Window Highlights": { "localizations": { "en": { diff --git a/Tests/ParcelAppTests/MenuAppTests.swift b/Tests/ParcelAppTests/MenuAppTests.swift index c192dc17..d4fdf0fa 100644 --- a/Tests/ParcelAppTests/MenuAppTests.swift +++ b/Tests/ParcelAppTests/MenuAppTests.swift @@ -46,6 +46,30 @@ struct MenuAppTests { #expect(services.menuSnapshot(EngineSnapshot(revision: 2, state: state), in: key) == nil) } + @Test func menuCountsAndMapsOnlyTiledWindows() throws { + let display = DisplayID(rawValue: "menu") + let space = SpaceID(rawValue: 1) + let key = WorkspaceKey(display: display, space: space) + var state = State( + displays: [Display(id: display, frame: Rect(width: 1440, height: 900))], + activeSpaces: [display: space], activeDisplay: display) + for number in 1...3 { + let window = ManagedWindow(id: WindowID(rawValue: UInt32(number)), app: AppID(pid: 1, bundleID: "fixture")) + state = reduce(state, .windowAppeared(window, workspace: key, frame: Rect(width: 400, height: 300))).0 + } + let services = EngineShellServices() + state = reduce(state, [.focusChanged(WindowID(rawValue: 3)), .commandIssued(.toggleFloat)]).0 + let mixed = try #require(services.menuSnapshot(EngineSnapshot(revision: 1, state: state), in: key)) + #expect(mixed.tiles.map(\.id).sorted() == [1, 2]) + #expect(mixed.accessibilityDescription.hasPrefix("Tiling 2 windows")) + for number in 1...2 { + state = reduce(state, [.focusChanged(WindowID(rawValue: UInt32(number))), .commandIssued(.toggleFloat)]).0 + } + let floating = try #require(services.menuSnapshot(EngineSnapshot(revision: 2, state: state), in: key)) + #expect(floating.tiles.isEmpty) + #expect(floating.accessibilityDescription.hasPrefix("Tiling 0 windows")) + } + @Test func menuChoicesRespectActualMinimumSizesWithoutChangingTheWorkspace() { let display = DisplayID(rawValue: "fit") let space = SpaceID(rawValue: 1) @@ -200,6 +224,16 @@ extension AppKitTestSuite { #expect(application.appearance == nil) } + @Test func stoppedRuntimeDoesNotDiagnoseAConnectedScreenAsDisconnected() throws { + let runtime = NativeAppRuntime(store: ConfigStore(), socketPath: "/tmp/menu-tests-unused.sock") + let result = runtime.menuWorkspace(.init(pointer: nil, statusScreen: NSScreen.main)) + guard case .failure(let reason) = result else { + Issue.record("A runtime without an engine must not invent a workspace") + return + } + #expect(reason == .notRunning) + } + @Test func runtimeHighlightToggleMissingCompositionIsVisibleFailure() async throws { let runtime = NativeAppRuntime(store: ConfigStore(), socketPath: "/tmp/menu-tests-unused.sock") await #expect(throws: AppFailure.self) { try await runtime.services.send(.toggleBorders) } diff --git a/Tests/ParcelEngineTests/RuleSpaceAssignmentRegressionTests.swift b/Tests/ParcelEngineTests/RuleSpaceAssignmentRegressionTests.swift index 2ed73cfb..28355e63 100644 --- a/Tests/ParcelEngineTests/RuleSpaceAssignmentRegressionTests.swift +++ b/Tests/ParcelEngineTests/RuleSpaceAssignmentRegressionTests.swift @@ -126,6 +126,23 @@ struct RuleSpaceAssignmentRegressionTests { await harness.engine.stop() } + @Test func disablingAutomaticTilingWhileRuleWritesDrainPreventsTheMoveAndSurvivesCompletion() async throws { + let spaces = ControlledRuleSpaces() + let harness = try EngineHarness(configuration: configuration(), spaceWorld: spaces) + harness.world.deferWrites = true + try await harness.start() + try harness.add([1]) + try await waitFor { harness.engine.spaceCommandRunning } + #expect(harness.engine.isAutomaticTilingEnabled) + harness.engine.setAutomaticTilingEnabled(false) + try harness.world.completeNextWrite() + try await settle(harness) + #expect(spaces.calls.isEmpty) + #expect(harness.engine.attemptedRuleSpaces.isEmpty) + #expect(!harness.engine.isAutomaticTilingEnabled) + await harness.engine.stop() + } + @Test func obsoleteMoveCompletionReconcilesWithoutInventingOldRulePlacement() async throws { let spaces = ControlledRuleSpaces() spaces.deferMoves = true diff --git a/Tests/ParcelEngineTests/SpaceCommandTests.swift b/Tests/ParcelEngineTests/SpaceCommandTests.swift index 5c7dfa31..23090092 100644 --- a/Tests/ParcelEngineTests/SpaceCommandTests.swift +++ b/Tests/ParcelEngineTests/SpaceCommandTests.swift @@ -19,7 +19,7 @@ private final class FakeSpaceWorld: EngineSpaceWorld { var error: SpaceCommandError? var suspend = false var cancelled = false - var onExecute: (() -> Void)? + var onExecute: (() throws -> Void)? var snapshot = [ NativeDisplaySpaces( displayID: engineDisplay.rawValue, currentSpace: 1, @@ -37,7 +37,7 @@ private final class FakeSpaceWorld: EngineSpaceWorld { async throws -> SpaceCommandResult { calls.append(Call(destination: destination, display: display, window: window, follow: follow)) - onExecute?() + try onExecute?() if let error { throw error } if suspend { // Suspension must not expire while other tests occupy the main actor. @@ -71,7 +71,7 @@ struct SpaceCommandRoutingTests { try await harness.start() try harness.add([1]) spaces.onExecute = { - #expect(!harness.engine.isAutomaticTilingEnabled) + #expect(harness.engine.isAutomaticTilingEnabled) #expect(!harness.engine.isIdle) } let result = try await harness.engine.performConfigured(command) @@ -167,6 +167,28 @@ struct SpaceCommandRoutingTests { await harness.engine.stop() } + @Test(arguments: [false, true]) + func automaticTilingChoiceDuringASpaceCommandSurvivesCompletion(initiallyEnabled: Bool) async throws { + let spaces = FakeSpaceWorld() + let harness = try EngineHarness(spaceWorld: spaces) + harness.engine.setAutomaticTilingEnabled(initiallyEnabled) + try await harness.start() + try harness.add([1]) + let writes = harness.world.allWrites.count + spaces.onExecute = { + #expect(harness.engine.isAutomaticTilingEnabled == initiallyEnabled) + harness.engine.setAutomaticTilingEnabled(!initiallyEnabled) + #expect(harness.world.allWrites.count == writes) + } + _ = try await harness.engine.performConfigured(.spaceNext) + #expect(harness.engine.isAutomaticTilingEnabled == !initiallyEnabled) + try harness.scheduler.runReady() + let settledWrites = harness.world.allWrites.count + try harness.add([2]) + if initiallyEnabled { #expect(harness.world.allWrites.count == settledWrites) } + await harness.engine.stop() + } + @Test(.timeLimit(.minutes(1))) func stopCancelsPendingSpaceOperationBeforeStoppingWorld() async throws { let spaces = FakeSpaceWorld() spaces.suspend = true diff --git a/Tests/ParcelUITests/MenuWorkspaceTests.swift b/Tests/ParcelUITests/MenuWorkspaceTests.swift index 7232948f..e5cf71e2 100644 --- a/Tests/ParcelUITests/MenuWorkspaceTests.swift +++ b/Tests/ParcelUITests/MenuWorkspaceTests.swift @@ -72,15 +72,15 @@ extension AppKitTestSuite { @Test func prepermissionMenuDoesNotInventDisplayPreviews() throws { let controller = try MenuBarController { _ in - Issue.record("An unavailable display must not receive commands") + Issue.record("A stopped engine must not receive commands") } defer { controller.stop() } - controller.workspaceForActivation = { _ in .failure(.disconnected) } + controller.workspaceForActivation = { _ in .failure(.notRunning) } controller.update( snapshot: LayoutSnapshot(layout: .grid, bounds: CGRect(x: 0, y: 0, width: 1, height: 1), tiles: []), configuration: .defaults, permission: .missing, reduceMotion: true, increaseContrast: false) controller.menuNeedsUpdate(controller.menu) - #expect(controller.menu.items.first?.title == MenuWorkspace.Unavailability.disconnected.detail) + #expect(controller.menu.items.first?.title == MenuWorkspace.Unavailability.notRunning.detail) for title in ["Layout", "Windows"] { let submenu = try #require(controller.menu.items.first { $0.title == title }?.submenu) #expect(submenu.items.allSatisfy { !$0.isEnabled && $0.image == nil && $0.state == .off }) diff --git a/docs/parcel.schema.json b/docs/parcel.schema.json index 0bbefb45..8c1a7ed5 100644 --- a/docs/parcel.schema.json +++ b/docs/parcel.schema.json @@ -363,8 +363,8 @@ "move-right" : "ctrl-alt-shift-d", "move-up" : "ctrl-alt-shift-w", "no-peek-toggle" : "ctrl-alt-d", - "open-settings" : "ctrl-alt-,", - "quit" : "ctrl-alt-q", + "open-settings" : "cmd-,", + "quit" : "cmd-q", "ratio-decrease" : "ctrl-alt-minus", "ratio-increase" : "ctrl-alt-=", "reset-sizes" : "ctrl-alt-0", @@ -885,7 +885,7 @@ ] }, "open-settings" : { - "default" : "ctrl-alt-,", + "default" : "cmd-,", "oneOf" : [ { "format" : "parcel-key-chord", @@ -898,7 +898,7 @@ ] }, "quit" : { - "default" : "ctrl-alt-q", + "default" : "cmd-q", "oneOf" : [ { "format" : "parcel-key-chord", -- knotmirror 0.0.1