import AppKit import Foundation import ParcelConfig import ParcelCore import ParcelPlatform import ParcelTestSupport import ParcelUI import ServiceManagement import Testing @testable import ParcelApp @testable import ParcelEngine @MainActor struct MenuAppTests { @Test(arguments: DisplaySuspension.Reason.allCases) func suspensionReasonsHaveConciseLocalizedMenuSentences(reason: DisplaySuspension.Reason) { let text = AppMenuSuspension.text(reason) #expect(text.hasPrefix("Not arranging this screen — ")) #expect(!text.contains("\n")) let explanation = String(text.dropFirst("Not arranging this screen — ".count)) if reason == .stageManager { #expect(explanation == "Stage Manager is on") } else { #expect(explanation.first?.isLowercase == true) } } @Test func shellSnapshotUsesAddressedSpaceAndItsModes() throws { let first = DisplayID(rawValue: "first") let second = DisplayID(rawValue: "second") let space = SpaceID(rawValue: 8) let key = WorkspaceKey(display: second, space: space) var state = State( displays: [ Display(id: first, frame: Rect(width: 1440, height: 900)), Display(id: second, frame: Rect(x: 1440, y: 0, width: 1440, height: 900)), ], activeSpaces: [first: SpaceID(rawValue: 2), second: space], activeDisplay: first) state.workspaces[key] = Workspace(key: key, layout: .rows, ratio: .twoThirds, windowCap: 2) state.focusModes = [key: FocusModes(noPeek: true, cleanSpace: true)] let services = EngineShellServices() let snapshot = try #require(services.menuSnapshot(EngineSnapshot(revision: 1, state: state), in: key)) #expect(snapshot.layout == .rows) #expect(snapshot.windowCap == 2) #expect(snapshot.ratio == 2.0 / 3) #expect(snapshot.noPeek && snapshot.cleanSpace) #expect( services.menuSnapshot( EngineSnapshot(revision: 1, state: state), in: WorkspaceKey(display: second, space: SpaceID(rawValue: 99))) == nil) state.displays[second] = nil #expect(services.menuSnapshot(EngineSnapshot(revision: 2, state: state), in: key) == nil) } @Test func menuSizePresentationTracksChangesAndWorkspaceReplacement() throws { let display = DisplayID(rawValue: "sizes") let key = WorkspaceKey(display: display, space: SpaceID(rawValue: 1)) var state = State( displays: [Display(id: display, frame: Rect(width: 1440, height: 900))], activeSpaces: [display: key.space], activeDisplay: display) state.workspaces[key] = Workspace( key: key, layout: .side, order: [WindowID(rawValue: 1), WindowID(rawValue: 2)]) let services = EngineShellServices() let neutral = EngineSnapshot(revision: 1, state: state) for _ in 0..<10 { let presented = try #require(services.menuSnapshot(neutral, in: key)) #expect(presented.mainSizeRatio == 0.5) #expect(!presented.hasCustomSizes) } state.workspaces[key]?.ratio = .twoThirds let changed = try #require(services.menuSnapshot(EngineSnapshot(revision: 2, state: state), in: key)) #expect(changed.hasCustomSizes) state.workspaces[key] = Workspace( key: key, layout: .side, ratio: .threeFifths, order: [WindowID(rawValue: 1), WindowID(rawValue: 2)]) let replaced = try #require(services.menuSnapshot(EngineSnapshot(revision: 3, state: state), in: key)) #expect(abs(replaced.mainSizeRatio - 0.6) < 0.001) #expect(!replaced.hasCustomSizes) state.displays[display] = nil services.publish(EngineSnapshot(revision: 4, state: state)) #expect(services.menuSnapshot(EngineSnapshot(revision: 4, state: state), in: key) == nil) let reconnected = try #require(services.menuSnapshot(neutral, in: key)) #expect(reconnected.mainSizeRatio == 0.5) #expect(!reconnected.hasCustomSizes) } @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.tiles.allSatisfy { $0.application == MenuApplicationIdentity(bundleIdentifier: "fixture", name: "fixture", processIdentifier: 1) }) #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) let key = WorkspaceKey(display: display, space: space) let windows = (1...2).map { ManagedWindow( id: WindowID(rawValue: UInt32($0)), app: AppID(pid: 1, bundleID: "fixture"), minimumSize: Size(width: 700, height: 200)) } var state = State( displays: [Display(id: display, frame: Rect(width: 1200, height: 900))], activeSpaces: [display: space], activeDisplay: display) state.windows = Dictionary(uniqueKeysWithValues: windows.map { ($0.id, $0) }) state.workspaces[key] = Workspace(key: key, layout: .columns, windowCap: 2, order: windows.map(\.id)) let snapshot = EngineSnapshot(revision: 1, state: state) let reasons = EngineShellServices().menuDisabledReasons(snapshot, in: key) #expect(reasons[.layoutColumns] == "The windows need more room with this choice.") #expect(reasons[.layoutRows] == nil) #expect(reasons[.setWindowCap(1)] == nil) #expect(reasons[.setWindowCap(2)] != nil) #expect(snapshot.state == state) } @Test(arguments: [Layout.columns, .side]) func menuCountExpansionCanSeparateFlexibleMembersOfAnAutomaticStack(layout: Layout) throws { let display = DisplayID(rawValue: "automatic-stacks") let space = SpaceID(rawValue: 1) let key = WorkspaceKey(display: display, space: space) var state = State( displays: [Display(id: display, frame: Rect(width: 1512, height: 886))], activeSpaces: [display: space], workspaces: [key: Workspace(key: key, layout: layout, windowCap: 2)]) let sizes = [ Size(width: 890, height: 552), Size(width: 840, height: 620), Size(width: 100, height: 100), Size(width: 100, height: 100), ] for (index, minimum) in sizes.enumerated() { let window = ManagedWindow( id: WindowID(rawValue: UInt32(index + 1)), app: AppID(pid: 1, bundleID: "fixture"), minimumSize: minimum) state = reduce(state, .windowAppeared(window, workspace: key, frame: Rect(width: 900, height: 700))).0 } #expect(state.workspaces[key]?.tree?.tileCount == 2) let snapshot = EngineSnapshot(revision: 1, state: state) let reasons = EngineShellServices().menuDisabledReasons(snapshot, in: key) #expect(reasons[.setWindowCap(3)] == nil) #expect(snapshot.state == state) let result = reduce(state, .workspaceCommandIssued(.setWindowCap(3), workspace: key)).0 #expect(result.workspaces[key]?.tree?.tileCount == 3) #expect(result.cannotFit.isEmpty) let first = try #require(result.frames[WindowID(rawValue: 1)]) let second = try #require(result.frames[WindowID(rawValue: 2)]) #expect(first == second) #expect(first.size.width >= 890 && first.size.height >= 620) } @Test func shellSuspensionStatusFollowsTheAddressedDisplay() throws { let first = DisplayID(rawValue: "first") let second = DisplayID(rawValue: "second") let space = SpaceID(rawValue: 8) let key = WorkspaceKey(display: second, space: space) var state = State( displays: [ Display(id: first, frame: Rect(width: 1440, height: 900)), Display(id: second, frame: Rect(x: 1440, width: 1440, height: 900)), ], activeSpaces: [first: space, second: space], activeDisplay: first) state.workspaces[key] = Workspace(key: key) var snapshot = EngineSnapshot(revision: 1, state: state) let suspension = DisplaySuspension(display: second, reason: .fullscreenSpace, since: Date()) let otherSuspension = DisplaySuspension(display: first, reason: .stageManager, since: Date()) snapshot.displaySuspensions = [otherSuspension, suspension] let services = EngineShellServices() #expect( try #require(services.menuSnapshot(snapshot, in: key)).arrangementStatus == AppMenuSuspension.text(suspension.reason)) #expect(NativeAppRuntime.suspensionStatus(snapshot) == "Not arranging this screen — Stage Manager is on") snapshot.displaySuspensions = [] #expect(try #require(services.menuSnapshot(snapshot, in: key)).arrangementStatus == nil) } @Test(arguments: ConfigHighlight.allCases.filter { $0 != .none }) func highlightTogglePreservesEveryEnabledStyle(style: ConfigHighlight) { var preference = MenuHighlightPreference() #expect(preference.toggled(from: style) == .none) #expect(preference.toggled(from: .none) == style) #expect(preference.toggled(from: style) == .none) #expect(preference.toggled(from: .none) == style) } @Test func highlightToggleFollowsSettingsChangesWithoutForgettingWhenOff() { var preference = MenuHighlightPreference() #expect(preference.toggled(from: .none) == .active) preference.observe(.all) preference.observe(.none) #expect(preference.toggled(from: .none) == .all) preference.observe(.glow) #expect(preference.toggled(from: .none) == .glow) } @Test func loginItemApprovalDoesNotRegisterAgain() { for status in [SMAppService.Status.enabled, .requiresApproval, .notRegistered, .notFound] { #expect(!NativeAppRuntime.shouldRegisterLoginItem(enabled: false, status: status)) #expect( NativeAppRuntime.shouldRegisterLoginItem(enabled: true, status: status) == (status == .notRegistered || status == .notFound)) } } @Test func desktopLabelsUseNativeOrdinalsAndSharedSpaceIdentity() { let key = WorkspaceKey(display: DisplayID(rawValue: "DISPLAY-B"), space: SpaceID(rawValue: 999)) let desktop = NativeSpace(id: 999, kind: .desktop, desktopNumber: 3) let displays = [ NativeDisplaySpaces( displayID: "display-b", currentSpace: 999, spaces: [ NativeSpace(id: 44, kind: .desktop, desktopNumber: 2), desktop, ]) ] #expect(NativeAppRuntime.menuDesktop(in: key, displays: displays) == desktop) #expect( NativeAppRuntime.menuDesktop( in: key, displays: [NativeDisplaySpaces(displayID: "Main", currentSpace: 999, spaces: [desktop])]) == desktop) #expect(NativeAppRuntime.menuDesktop(in: key, displays: []) == nil) #expect( NativeAppRuntime.menuDesktop( in: WorkspaceKey(display: key.display, space: SpaceID(rawValue: 55)), displays: displays) == nil) } @Test func menuReportsExplainTheActualFailureWithoutLeakingIdentifiers() { #expect( EngineShellServices.menuFailure(reports: [.noFocusedWindow]).message == "Focus a window on this display first.") #expect( EngineShellServices.menuFailure(reports: [.noActiveWorkspace]).message == "This desktop is no longer active. Reopen the menu and try again.") #expect( EngineShellServices.menuFailure(reports: [.unavailableDisplay(DisplayID(rawValue: "private-uuid"))]).message == "This display is no longer connected. Reopen the menu on a connected display.") #expect( EngineShellServices.menuFailure(reports: [.unsupported]).message == "The menu action could not finish. Reopen the menu and try again.") } @Test func highlightsArePersistedByTheAppSinkAndFailuresReachCallers() async throws { let services = EngineShellServices() await #expect(throws: AppFailure.self) { try await services.send(.toggleBorders) } var calls = 0 services.toggleBorders = { calls += 1 } try await services.send(.toggleBorders) #expect(calls == 1) services.toggleBorders = { throw AppFailure(message: "write refused") } await #expect(throws: AppFailure.self) { try await services.send(.toggleBorders) } } } extension AppKitTestSuite { @MainActor struct RuntimeMenuAppTests { init() { _ = NSApplication.shared } @Test func chromeModeAppliesBeforeTheEngineStartsAndCanReturnToSystem() throws { let application = NSApplication.shared let previous = application.appearance defer { OverlayPaletteSource.shared.configure(.init()) application.appearance = previous } let runtime = NativeAppRuntime(store: ConfigStore(), socketPath: "/tmp/appearance-tests-unused.sock") var configuration = ParcelConfiguration.defaults configuration.appearance = .init(palette: .kiln, mode: .dark) try runtime.applyConfiguration(configuration) #expect(application.appearance?.name == .darkAqua) #expect(runtime.services.engine == nil) let light = try #require(NSAppearance(named: .aqua)) let background = OverlayPaletteSource.shared.resolve(for: light, accessibility: .init()).chipBackground configuration.appearance.mode = .light try runtime.applyConfiguration(configuration) #expect(application.appearance?.name == .aqua) #expect( OverlayPaletteSource.shared.resolve(for: light, accessibility: .init()).chipBackground != background) configuration.appearance.mode = .system try runtime.applyConfiguration(configuration) #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) } } } }