import AppKit import ParcelConfig import ParcelCore import Testing @testable import ParcelUI extension AppKitTestSuite { @MainActor @Suite struct MenuWorkspaceTests { let left = DisplayID(rawValue: "left") let right = DisplayID(rawValue: "right") init() { _ = NSApplication.shared } @Test func menuCapturesTargetAndUsesItsCapabilitiesAndPreviews() throws { var global: [ConfigCommand] = [] var targeted: [(ConfigCommand, MenuWorkspace)] = [] let controller = try MenuBarController { global.append($0) } defer { controller.stop() } let key = WorkspaceKey(display: right, space: SpaceID(rawValue: 8)) let original = MenuWorkspace( key: key, snapshot: LayoutSnapshot( layout: .rows, bounds: CGRect(x: 0, y: 0, width: 1440, height: 900), tiles: [], windowCap: 2), displayName: "Studio Display", desktopNumber: 3, hasMultipleDisplays: true) controller.workspaceForActivation = { _ in .success(original) } controller.invokeInWorkspace = { targeted.append(($0, $1)) } controller.update( snapshot: .preview, configuration: .defaults, permission: .granted, reduceMotion: true, increaseContrast: false) controller.menuNeedsUpdate(controller.menu) controller.menuWillOpen(controller.menu) let counts = try #require(controller.menu.items.first { $0.title == "Windows" }?.submenu) #expect(counts.items[1].state == .on) #expect(!counts.items[2].isEnabled) #expect(counts.items[2].accessibilityHelp()?.contains("Maximum 2") == true) #expect(counts.items.allSatisfy { $0.image != nil }) let layouts = try #require(controller.menu.items.first { $0.title == "Layout" }?.submenu) #expect(layouts.items.prefix(7).allSatisfy { $0.image != nil }) #expect(controller.menu.items.first?.title.hasSuffix("Studio Display · Desktop 3") == true) #expect(!controller.menu.items.contains { $0.title.contains("Space 8") }) let moved = MenuWorkspace( key: WorkspaceKey(display: left, space: SpaceID(rawValue: 9)), snapshot: .preview, displayName: "Built-in Display") controller.workspaceForActivation = { _ in .success(moved) } counts.performActionForItem(at: 0) #expect(targeted.count == 1) #expect(targeted.first?.0 == .setWindowCap(1)) #expect(targeted.first?.1 == original) #expect(global.isEmpty) } @Test func plainResetItemAppearsForCustomSizesAndTargetsTheCapturedWorkspace() throws { var invoked: [(ConfigCommand, MenuWorkspace)] = [] let controller = try MenuBarController { _ in Issue.record("Expected a workspace command") } defer { controller.stop() } let key = WorkspaceKey(display: right, space: SpaceID(rawValue: 8)) func workspace(custom: Bool) -> MenuWorkspace { MenuWorkspace( key: key, snapshot: LayoutSnapshot( layout: .side, bounds: LayoutSnapshot.preview.bounds, tiles: [], hasCustomSizes: custom), displayName: "Display") } let neutral = workspace(custom: false) controller.workspaceForActivation = { _ in .success(neutral) } controller.invokeInWorkspace = { invoked.append(($0, $1)) } controller.update( snapshot: .preview, configuration: .defaults, permission: .granted, reduceMotion: true, increaseContrast: false) controller.menuNeedsUpdate(controller.menu) let summary = try #require(controller.menu.items.first) #expect(summary.submenu == nil) #expect( controller.menu.items.first { $0.title == "Layout" }?.submenu?.items.contains { $0.title == "Reset sizes" } == false) let captured = workspace(custom: true) controller.workspaceForActivation = { _ in .success(captured) } controller.menuNeedsUpdate(controller.menu) #expect(controller.menu.items.first === summary) let status = try #require(summary.view) #expect(status.accessibilityRole() == .group) #expect((status as? MenuStatusView)?.automaticSwitch.accessibilityLabel() == "Automatic tiling") #expect(!status.subviews.contains { $0 is NSButton }) #expect(!summary.isEnabled) #expect(summary.submenu == nil) let layouts = try #require(controller.menu.items.first { $0.title == "Layout" }?.submenu) let reset = try #require(layouts.items.first { $0.title == "Reset sizes" }) #expect(!controller.menu.items.contains { $0.title == "Reset sizes" }) #expect(reset.isEnabled) #expect(reset.view == nil && reset.submenu == nil) #expect(reset.accessibilityLabel() == "Reset sizes") #expect(reset.action != nil) controller.workspaceForActivation = { _ in .success(neutral) } layouts.performActionForItem(at: layouts.index(of: reset)) #expect(invoked.count == 1) #expect(invoked.first?.0 == .resetSizes) #expect(invoked.first?.1 == captured) controller.menuNeedsUpdate(controller.menu) #expect( controller.menu.items.first { $0.title == "Layout" }?.submenu?.items.contains { $0.title == "Reset sizes" } == false) #expect(summary.submenu == nil) } @Test(arguments: [false, true]) func unavailableOrBlockedWorkspaceNeverOffersResetSizes(blocked: Bool) throws { let controller = try MenuBarController { _ in Issue.record("Reset must not be available") } defer { controller.stop() } let snapshot = LayoutSnapshot( layout: .side, bounds: LayoutSnapshot.preview.bounds, tiles: [], hasCustomSizes: true) controller.workspaceForActivation = { _ in if blocked { .success( MenuWorkspace( key: WorkspaceKey(display: self.right, space: SpaceID(rawValue: 8)), snapshot: snapshot, displayName: "Display", disabledReasons: [.resetSizes: "Fixture refusal"])) } else { .failure(.unmanagedSpace) } } controller.update( snapshot: snapshot, configuration: .defaults, permission: .granted, reduceMotion: true, increaseContrast: false) controller.menuNeedsUpdate(controller.menu) #expect( controller.menu.items.first { $0.title == "Layout" }?.submenu?.items.contains { $0.title == "Reset sizes" } == false) #expect(controller.menu.items.first?.submenu == nil) } @Test(arguments: ConfigLayout.allCases) func mainSizeMenuTargetsTheCapturedWorkspaceAndDisablesAccordion(layout: ConfigLayout) throws { var invoked: [(ConfigCommand, MenuWorkspace)] = [] let controller = try MenuBarController { _ in Issue.record("Expected a workspace command") } defer { controller.stop() } let workspace = MenuWorkspace( key: WorkspaceKey(display: right, space: SpaceID(rawValue: 8)), snapshot: LayoutSnapshot( layout: layout, bounds: LayoutSnapshot.preview.bounds, tiles: [], ratio: 0.5, mainSizeRatio: 0.6), displayName: "Display") controller.workspaceForActivation = { _ in .success(workspace) } controller.invokeInWorkspace = { invoked.append(($0, $1)) } controller.update( snapshot: .preview, configuration: .defaults, permission: .granted, reduceMotion: true, increaseContrast: false) controller.menuNeedsUpdate(controller.menu) let layouts = try #require(controller.menu.items.first { $0.title == "Layout" }?.submenu) let sizes = try #require(layouts.items.first { $0.title == "Main Size" }?.submenu) #expect(!controller.menu.items.contains { $0.title == "Main Size" }) #expect(sizes.items.count == 3) for (index, command) in [ConfigCommand.ratioHalf, .ratioThreeFifths, .ratioTwoThirds].enumerated() { let item = sizes.items[index] let shortcut = MenuShortcut(ParcelConfiguration.defaults.keybindings[command]) #expect(item.keyEquivalent == shortcut.keyEquivalent) #expect(item.keyEquivalentModifierMask == shortcut.modifierMask) #expect(item.isEnabled == (layout != .accordion)) #expect(item.state == (layout != .accordion && index == 1 ? .on : .off)) #expect((item.accessibilityHelp() != nil) == (layout == .accordion)) #expect(item.accessibilityLabel() == item.title) if item.isEnabled { sizes.performActionForItem(at: index) } } if layout != .accordion { #expect(invoked.map { $0.0 } == [.ratioHalf, .ratioThreeFifths, .ratioTwoThirds]) #expect(invoked.allSatisfy { $0.1 == workspace }) } else { #expect(invoked.isEmpty) } } @Test(arguments: [(0.5, "Half"), (0.6, "60%"), (2.0 / 3.0, "Two thirds"), (0.7, "Custom")]) func layoutSubmenuShowsTheCurrentMainSizeAndCustomState(testCase: (Double, String)) throws { let (ratio, title) = testCase let controller = try MenuBarController { _ in } defer { controller.stop() } let snapshot = LayoutSnapshot( layout: .side, bounds: LayoutSnapshot.preview.bounds, tiles: LayoutSnapshot.preview.tiles, mainSizeRatio: ratio, hasCustomSizes: true) controller.update( snapshot: snapshot, configuration: .defaults, permission: .granted, reduceMotion: true, increaseContrast: false) controller.menuNeedsUpdate(controller.menu) let layouts = try #require(controller.menu.items.first { $0.title == "Layout" }?.submenu) let sizes = try #require(layouts.items.first { $0.title == "Main Size" }?.submenu) #expect(sizes.items.prefix(3).map(\.title) == ["Half", "60%", "Two thirds"]) let selected = try #require(sizes.items.first { $0.state == .on }) #expect(sizes.items.filter { $0.state == .on }.count == 1) #expect(selected.title == title) #expect(selected.isEnabled == (ratio != 0.7)) #expect(layouts.items.last?.title == "Reset sizes") #expect(!controller.menu.items.contains { $0.title == "Main Size" || $0.title == "Reset sizes" }) } @Test func unavailablePointerNeverFallsBackToFocusedDisplay() throws { var commands: [ConfigCommand] = [] let controller = try MenuBarController { commands.append($0) } defer { controller.stop() } controller.workspaceForActivation = { _ in .failure(.disconnected) } controller.update( snapshot: .preview, configuration: .defaults, permission: .granted, reduceMotion: true, increaseContrast: false) controller.menuNeedsUpdate(controller.menu) let counts = try #require(controller.menu.items.first { $0.title == "Windows" }?.submenu) #expect(counts.items.allSatisfy { !$0.isEnabled && $0.accessibilityHelp() != nil }) let retile = try #require(controller.menu.items.first { ($0 as? CommandMenuItem)?.command == .retile }) #expect(!retile.isEnabled) let routing = try #require((controller.menu as? CommandMenu)?.routing) #expect(routing.bindings[.retile] == nil) #expect(commands.isEmpty) } @Test func prepermissionMenuDoesNotInventDisplayPreviews() throws { let controller = try MenuBarController { _ in Issue.record("A stopped engine must not receive commands") } defer { controller.stop() } 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.notRunning.detail) for title in ["Layout", "Windows"] { let submenu = try #require(controller.menu.items.first { $0.title == title }?.submenu) let leaves = submenu.items.filter { !$0.isSeparatorItem }.flatMap { $0.submenu?.items ?? [$0] } #expect(leaves.allSatisfy { !$0.isEnabled && $0.image == nil && $0.state == .off }) } } @Test(arguments: [false, true]) func quickSwitchesReflectEffectiveStateAndUseConfiguredCommands(enabled: Bool) throws { var commands: [ConfigCommand] = [] let controller = try MenuBarController { commands.append($0) } defer { controller.stop() } var configuration = ParcelConfiguration.defaults configuration.motion.highlight = enabled ? .glow : .none let snapshot = LayoutSnapshot( layout: .grid, bounds: LayoutSnapshot.preview.bounds, tiles: [], noPeek: enabled, cleanSpace: enabled, hoverFocus: enabled) controller.update( snapshot: snapshot, configuration: configuration, permission: .granted, reduceMotion: true, increaseContrast: false) controller.menuNeedsUpdate(controller.menu) for command in [ConfigCommand.toggleBorders, .toggleHoverFocus, .toggleNoPeek, .toggleCleanSpace] { let item = try #require(controller.menu.items.first { ($0 as? CommandMenuItem)?.command == command }) #expect(item.state == (enabled ? .on : .off)) #expect(item.accessibilityLabel() == item.title) controller.menu.performActionForItem(at: controller.menu.index(of: item)) } #expect(commands == [.toggleBorders, .toggleHoverFocus, .toggleNoPeek, .toggleCleanSpace]) } @Test func providerOnlyReceivesPointerForConsumedRealClick() throws { let controller = try MenuBarController { _ in } defer { controller.stop() } let window = try #require(controller.statusItem.button?.window) let location = CGPoint(x: 4, y: 6) let click = try #require( NSEvent.mouseEvent( with: .leftMouseUp, location: location, modifierFlags: [], timestamp: 0, windowNumber: window.windowNumber, context: nil, eventNumber: 1, clickCount: 1, pressure: 0)) var received: [MenuWorkspaceActivation] = [] controller.workspaceForActivation = { activation in received.append(activation) return .failure(.disconnected) } controller.update( snapshot: .preview, configuration: .defaults, permission: .granted, reduceMotion: true, increaseContrast: false) controller.recordPointerActivation(click) controller.menuNeedsUpdate(controller.consumeActivationMenu()) #expect(received.last?.pointer == window.convertPoint(toScreen: location)) controller.menuNeedsUpdate(controller.consumeActivationMenu()) #expect(received.count == 2) #expect(received.last?.pointer == nil) #expect(received.last?.statusScreen == nil || received.last?.statusScreen === window.screen) } @Test func unmanagedSpaceExplainsWhyItsActionsAreDisabled() throws { let controller = try MenuBarController { _ in Issue.record("Unmanaged commands must stay disabled") } defer { controller.stop() } controller.workspaceForActivation = { _ in .failure(.unmanagedSpace) } controller.update( snapshot: .preview, configuration: .defaults, permission: .granted, reduceMotion: true, increaseContrast: false) controller.menuNeedsUpdate(controller.menu) #expect(controller.menu.items.first?.title == MenuWorkspace.Unavailability.unmanagedSpace.detail) #expect( controller.menu.items.contains { $0.title == "Parcel doesn’t arrange this Space (for example, a full-screen app)." }) #expect(!controller.menu.items.contains { $0.title == "Display unavailable" }) let retile = try #require(controller.menu.items.first { ($0 as? CommandMenuItem)?.command == .retile }) #expect(!retile.isEnabled) #expect(retile.accessibilityHelp() == "Parcel doesn’t arrange this Space (for example, a full-screen app).") } @Test(arguments: [false, true], [false, true]) func modesRequireTargetFocusOnlyWhenEnabling(hasFocusedWindow: Bool, enabled: Bool) throws { var commands: [ConfigCommand] = [] let controller = try MenuBarController { _ in Issue.record("Workspace modes need a target") } defer { controller.stop() } controller.workspaceForActivation = { _ in .success( MenuWorkspace( key: WorkspaceKey(display: self.right, space: SpaceID(rawValue: 8)), snapshot: LayoutSnapshot( layout: .grid, bounds: LayoutSnapshot.preview.bounds, tiles: [], isFocused: enabled, noPeek: enabled, cleanSpace: enabled), displayName: "Display 2", hasFocusedWindow: hasFocusedWindow)) } controller.invokeInWorkspace = { command, _ in commands.append(command) } var configuration = ParcelConfiguration.defaults configuration.keybindings[.toggleFocus] = try KeyChord(parsing: "cmd-f") configuration.keybindings[.toggleNoPeek] = try KeyChord(parsing: "cmd-n") configuration.keybindings[.toggleCleanSpace] = try KeyChord(parsing: "cmd-k") controller.update( snapshot: .preview, configuration: configuration, permission: .granted, reduceMotion: true, increaseContrast: false) controller.menuNeedsUpdate(controller.menu) let routing = try #require((controller.menu as? CommandMenu)?.routing) let allowed = enabled || hasFocusedWindow for command in [ConfigCommand.toggleFocus, .toggleNoPeek, .toggleCleanSpace] { let item = try #require( controller.menu.items.compactMap { $0 as? CommandMenuItem }.first { $0.command == command }) #expect(item.isEnabled == allowed) #expect((routing.bindings[command] != nil) == allowed) #expect(item.accessibilityHelp() == (allowed ? nil : "Focus a window on this display first.")) item.invoke(command) } #expect(commands.count == (allowed ? 3 : 0)) } @Test func whatsNewMenuReusesWindowAndFollowsSystemAppearance() throws { let release = WhatsNewController() defer { release.close() } let menu = WhatsNewMenuItem { release.show() } #expect(menu.accessibilityLabel() == "What’s New…") #expect(menu.keyEquivalent.isEmpty) release.show() let window = try #require(release.window) release.show() #expect(release.window === window) #expect(window.appearance == nil) #expect(window.animationBehavior == .none) #expect(window.title == "What’s New in Parcel") #expect(WhatsNewFeature.allCases.count == 4) for feature in WhatsNewFeature.allCases { #expect(!feature.title.isEmpty && !feature.detail.isEmpty) } release.close() #expect(release.window == nil) } } } @MainActor @Suite struct MenuWorkspaceModelTests { let left = DisplayID(rawValue: "left") let right = DisplayID(rawValue: "right") @Test(arguments: [CGRect(x: 490, y: 725, width: 24, height: 25), CGRect(x: 445, y: 725, width: 24, height: 25)]) func visibleStatusItemBehindOrCrossingNotchUsesSafeFallback(frame: CGRect) throws { let screen = CGRect(x: 0, y: 0, width: 1000, height: 750) let notch = try #require( MenuBarPlacement.notchFrame( screen: screen, topInset: 32, leftArea: CGRect(x: 0, y: 718, width: 450, height: 32), rightArea: CGRect(x: 550, y: 718, width: 450, height: 32))) #expect(notch == CGRect(x: 450, y: 718, width: 100, height: 32)) let anchor = StatusItemAnchor(frame: frame, isVisible: true, excludedFrames: [notch]) #expect(!anchor.isUsable(on: [screen])) #expect( MenuBarPlacement.resolve( anchor: anchor, screens: [screen], activeVisibleFrame: CGRect(x: 0, y: 0, width: 1000, height: 718)) == .fallback(CGPoint(x: 988, y: 706))) } @Test func visibleStatusItemBesideNotchRemainsNative() { let screen = CGRect(x: -1000, y: 200, width: 1000, height: 750) let anchor = StatusItemAnchor( frame: CGRect(x: -100, y: 925, width: 24, height: 25), isVisible: true, excludedFrames: [CGRect(x: -550, y: 918, width: 100, height: 32)]) #expect(MenuBarPlacement.resolve(anchor: anchor, screens: [screen], activeVisibleFrame: nil) == .statusItem) } @Test func unavailableNotchAuxiliaryGeometryFailsSafelyWithoutBlockingOrdinaryScreens() { let screen = CGRect(x: 0, y: 0, width: 1000, height: 750) #expect( MenuBarPlacement.notchFrame(screen: screen, topInset: 32, leftArea: nil, rightArea: nil) == CGRect(x: 0, y: 718, width: 1000, height: 32)) #expect(MenuBarPlacement.notchFrame(screen: screen, topInset: 0, leftArea: nil, rightArea: nil) == nil) } @Test func activeScreenWinsThenPointerThenMainWithoutUsingInvalidGeometry() { let frames = [ CGRect.zero, CGRect(x: 0, y: 0, width: 1000, height: 750), CGRect(x: -1000, y: 200, width: 1000, height: 750), ] let pointer = CGPoint(x: -500, y: 300) #expect(MenuBarPlacement.preferredScreenIndex(active: 1, main: 1, pointer: pointer, frames: frames) == 1) #expect(MenuBarPlacement.preferredScreenIndex(active: 0, main: 1, pointer: pointer, frames: frames) == 2) #expect( MenuBarPlacement.preferredScreenIndex(active: 8, main: 1, pointer: .init(x: 9999, y: 9999), frames: frames) == 1) #expect(MenuBarPlacement.preferredScreenIndex(active: nil, main: 0, pointer: .zero, frames: [.zero]) == nil) } @Test(arguments: [false, true]) func visibleStatusItemWinsButHiddenItemUsesTheActiveDisplay(visible: Bool) { let primary = CGRect(x: 0, y: 0, width: 1000, height: 750) let secondary = CGRect(x: 1000, y: -200, width: 1400, height: 1000) let anchor = StatusItemAnchor(frame: CGRect(x: 900, y: 725, width: 24, height: 25), isVisible: visible) let placement = MenuBarPlacement.resolve( anchor: anchor, screens: [primary, secondary], activeVisibleFrame: CGRect(x: 1000, y: -150, width: 1400, height: 925)) #expect(placement == (visible ? .statusItem : .fallback(CGPoint(x: 2388, y: 763)))) } @Test( arguments: [ nil, CGRect.zero, CGRect(x: -100, y: 725, width: 24, height: 25), CGRect(x: 990, y: 725, width: 24, height: 25), CGRect(x: 900, y: 740, width: 24, height: 25), CGRect(x: 900, y: 725, width: -24, height: 25), CGRect(x: CGFloat.nan, y: 725, width: 24, height: 25), CGRect(x: 900, y: 725, width: CGFloat.infinity, height: 25), ] as [CGRect?]) func absentOffscreenOrInvalidStatusItemsUseFallback(frame: CGRect?) { let screen = CGRect(x: 0, y: 0, width: 1000, height: 750) let placement = MenuBarPlacement.resolve( anchor: StatusItemAnchor(frame: frame, isVisible: true), screens: [screen], activeVisibleFrame: CGRect(x: 0, y: 50, width: 1000, height: 675)) #expect(placement == .fallback(CGPoint(x: 988, y: 713))) } @Test func statusItemStraddlingTwoDisplaysIsNotAUsableAnchor() { let screens = [ CGRect(x: 0, y: 0, width: 1000, height: 750), CGRect(x: 1000, y: 0, width: 1000, height: 750), ] let anchor = StatusItemAnchor(frame: CGRect(x: 990, y: 725, width: 24, height: 25), isVisible: true) #expect(!anchor.isUsable(on: screens)) #expect( MenuBarPlacement.resolve(anchor: anchor, screens: screens, activeVisibleFrame: screens[1]) == .fallback(CGPoint(x: 1988, y: 738))) } @Test func fallbackTargetsTheActiveDisplayEvenWithNegativeOriginAndHiddenStatusElsewhere() throws { let primary = CGRect(x: 0, y: 0, width: 1000, height: 750) let secondary = CGRect(x: -1400, y: 200, width: 1400, height: 1000) let state = State( displays: [ Display(id: right, frame: Rect(width: 1000, height: 750)), Display(id: left, frame: Rect(x: -1400, y: -450, width: 1400, height: 1000)), ], activeSpaces: [left: SpaceID(rawValue: 2), right: SpaceID(rawValue: 8)], activeDisplay: left) let placement = MenuBarPlacement.resolve( anchor: StatusItemAnchor(frame: CGRect(x: 900, y: 725, width: 24, height: 25), isVisible: false), screens: [primary, secondary], activeVisibleFrame: secondary.insetBy(dx: 0, dy: 25)) guard case .fallback(let point) = placement else { Issue.record("A hidden status item should use the active display") return } #expect(point == CGPoint(x: -12, y: 1163)) #expect( MenuWorkspace.target( at: point, statusDisplay: right, screens: [left: secondary, right: primary], state: state) == .success(WorkspaceKey(display: left, space: SpaceID(rawValue: 2)))) } @Test(arguments: [ CGRect.zero, CGRect(x: CGFloat.nan, y: 0, width: 1000, height: 750), CGRect(x: 0, y: 0, width: CGFloat.infinity, height: 750), CGRect(x: 1000, y: 0, width: 1000, height: 750), CGRect(x: 0, y: 0, width: -1000, height: 750), ]) func missingOrInvalidFallbackDisplayReportsUnavailable(frame: CGRect) { #expect( MenuBarPlacement.resolve( anchor: StatusItemAnchor(frame: nil, isVisible: false), screens: [CGRect(x: 0, y: 0, width: 1000, height: 750)], activeVisibleFrame: frame) == .unavailable) } @Test func noConnectedDisplayReportsUnavailableInsteadOfUsingStaleGeometry() { #expect( MenuBarPlacement.resolve( anchor: StatusItemAnchor(frame: CGRect(x: 900, y: 725, width: 24, height: 25), isVisible: true), screens: [], activeVisibleFrame: CGRect(x: 0, y: 0, width: 1000, height: 750)) == .unavailable) #expect( MenuBarPlacement.resolve( anchor: StatusItemAnchor(frame: nil, isVisible: false), screens: [CGRect(x: 0, y: 0, width: 1000, height: 750)], activeVisibleFrame: nil) == .unavailable) } @Test(arguments: [CGSize(width: 1, height: 1), CGSize(width: 20, height: 20)]) func fallbackInsetKeepsTheAnchorInsideVerySmallDisplays(size: CGSize) { let frame = CGRect(origin: CGPoint(x: -100, y: -100), size: size) #expect( MenuBarPlacement.resolve( anchor: StatusItemAnchor(frame: nil, isVisible: false), screens: [frame], activeVisibleFrame: frame) == .fallback(CGPoint(x: frame.midX, y: frame.midY))) } @Test func pointerUsesPhysicalScreenIncludingMenuBarAndExactSpace() { let state = State( displays: [ Display(id: left, frame: Rect(width: 1000, height: 700)), Display(id: right, frame: Rect(x: 1000, y: 0, width: 1000, height: 700)), ], activeSpaces: [left: SpaceID(rawValue: 2), right: SpaceID(rawValue: 8)], activeDisplay: left) let screens = [ left: CGRect(x: 0, y: 0, width: 1000, height: 750), right: CGRect(x: 1000, y: 0, width: 1000, height: 750), ] #expect( MenuWorkspace.target(at: CGPoint(x: 1400, y: 740), screens: screens, state: state) == .success(WorkspaceKey(display: right, space: SpaceID(rawValue: 8)))) #expect( MenuWorkspace.target(at: CGPoint(x: 1000, y: 740), screens: screens, state: state) == .success(WorkspaceKey(display: right, space: SpaceID(rawValue: 8)))) #expect( MenuWorkspace.target(at: CGPoint(x: -1, y: 0), screens: screens, state: state) == .failure(.disconnected)) #expect( MenuWorkspace.target(at: CGPoint(x: Double.nan, y: 0), screens: screens, state: state) == .failure(.disconnected)) var disconnected = state disconnected.displays[right] = nil #expect( MenuWorkspace.target(at: CGPoint(x: 1400, y: 740), screens: screens, state: disconnected) == .failure(.disconnected)) var unknownSpace = state unknownSpace.activeSpaces[right] = nil #expect( MenuWorkspace.target(at: CGPoint(x: 1400, y: 740), screens: screens, state: unknownSpace) == .failure(.unmanagedSpace)) var unmanaged = state unmanaged.workspaces[WorkspaceKey(display: right, space: SpaceID(rawValue: 8))] = nil #expect( MenuWorkspace.target(at: CGPoint(x: 1400, y: 740), screens: screens, state: unmanaged) == .failure(.unmanagedSpace)) #expect( MenuWorkspace.target(at: CGPoint(x: 1400, y: 750), screens: screens, state: state) == .success(WorkspaceKey(display: right, space: SpaceID(rawValue: 8)))) #expect( MenuWorkspace.target(at: CGPoint(x: 1000, y: 750), screens: screens, state: state) == .success(WorkspaceKey(display: right, space: SpaceID(rawValue: 8)))) #expect( MenuWorkspace.target(at: CGPoint(x: 2000, y: 750), screens: screens, state: state) == .success(WorkspaceKey(display: right, space: SpaceID(rawValue: 8)))) } @Test(arguments: ConfigLayout.allCases, 1...5) func tinyPreviewBoundsNeverCreateEmptyTiles(layout: ConfigLayout, count: Int) { let preview = MenuLayoutPreview.snapshot( layout: layout, count: count, bounds: CGRect(x: 0, y: 0, width: 1, height: 1), ratio: 0.5) #expect(preview.tiles.allSatisfy { $0.frame.width > 0 && $0.frame.height > 0 }) } @Test func unlimitedPreviewDoesNotApplyThePositiveLayoutCap() { let bounds = CGRect(x: 0, y: 0, width: 1440, height: 900) let snapshot = LayoutSnapshot(layout: .rows, bounds: bounds, tiles: [], windowCap: Int.max) let preview = MenuLayoutPreview.snapshot(layout: .rows, count: 5, bounds: bounds, ratio: 0.5, unlimited: true) #expect(preview.tiles.count == 5) #expect(preview.windowCap == Int.max) let populated = LayoutSnapshot(layout: .rows, bounds: bounds, tiles: preview.tiles, windowCap: 0) #expect(MenuLayoutPreview.count(for: .rows, in: populated) == 5) #expect(MenuLayoutPreview.count(for: .rows, in: snapshot) == 1) } @Test func previewUsesThePhysicalDisplayVariantWhenReservedEdgesChangeItsAspect() { let preview = MenuLayoutPreview.snapshot( layout: .columns, count: 3, bounds: CGRect(x: 0, y: 0, width: 900, height: 800), ratio: 0.5, capabilityBounds: CGRect(x: 0, y: 0, width: 900, height: 1440)) #expect(preview.tiles.count == 3) #expect(preview.tiles.allSatisfy { $0.frame.width == 900 }) } @Test func portraitColumnPreviewUsesAdaptedVerticalPlacement() { let preview = MenuLayoutPreview.snapshot( layout: .columns, count: 3, bounds: CGRect(x: 0, y: 0, width: 600, height: 1000), ratio: 0.5) #expect(preview.tiles.count == 3) #expect(preview.tiles.allSatisfy { $0.frame.minX == 0 && $0.frame.width == 600 }) #expect(preview.tiles.map(\.frame.minY) == [0, 333, 667]) #expect(preview.tiles.last?.frame.maxY == 1000) } @Test func nonPointerOpenUsesStatusScreenThenActiveWorkspace() { let state = State( displays: [ Display(id: left, frame: Rect(width: 1000, height: 700)), Display(id: right, frame: Rect(x: 1000, width: 1000, height: 700)), ], activeSpaces: [left: SpaceID(rawValue: 2), right: SpaceID(rawValue: 8)], activeDisplay: left) let screens = [ left: CGRect(x: 0, y: 0, width: 1000, height: 750), right: CGRect(x: 1000, y: 0, width: 1000, height: 750), ] #expect( MenuWorkspace.target(at: nil, statusDisplay: right, screens: screens, state: state) == .success(WorkspaceKey(display: right, space: SpaceID(rawValue: 8)))) #expect( MenuWorkspace.target(at: nil, screens: screens, state: state) == .success(WorkspaceKey(display: left, space: SpaceID(rawValue: 2)))) #expect( MenuWorkspace.target(at: nil, statusDisplay: DisplayID(rawValue: "removed"), screens: screens, state: state) == .success(WorkspaceKey(display: left, space: SpaceID(rawValue: 2)))) var unmanaged = state unmanaged.workspaces[WorkspaceKey(display: right, space: SpaceID(rawValue: 8))] = nil #expect( MenuWorkspace.target(at: nil, statusDisplay: right, screens: screens, state: unmanaged) == .failure(.unmanagedSpace)) } @Test func previewCountHandlesAutomaticEmptyAndCappedLayouts() { func snapshot(_ cap: Int?, tiles: Int) -> LayoutSnapshot { LayoutSnapshot( layout: .grid, bounds: LayoutSnapshot.preview.bounds, tiles: (0..