diff --git a/Sources/AppDelegate.swift b/Sources/AppDelegate.swift index 45709fa037be..c39d923a63be 100644 --- a/Sources/AppDelegate.swift +++ b/Sources/AppDelegate.swift @@ -688,7 +688,6 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent private var pendingConfiguredShortcutChord: PendingConfiguredShortcutChord? var activeConfiguredShortcutChordPrefixForCurrentEvent: ShortcutStroke? var shortcutEventFocusContextCache: ShortcutEventFocusContextCache? - private var configuredShortcutChordActions: [KeyboardShortcutSettings.Action] = [] private var ghosttyConfigObserver: NSObjectProtocol? private var ghosttyGotoSplitLeftShortcut: StoredShortcut? private var ghosttyGotoSplitRightShortcut: StoredShortcut? @@ -6243,8 +6242,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent case .rightSidebarFileSearch: result = context.keyboardFocusCoordinator.focusFileSearch() case .mainPanelFind: - context.tabManager.startSearch() - result = context.tabManager.isFindVisible + result = context.tabManager.startSearch() case .none: result = false } @@ -7403,8 +7401,20 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent ) } if shouldTemporarilyDisallowFullScreenTiling { - DispatchQueue.main.async { [weak window] in - window?.collectionBehavior.remove(.fullScreenDisallowsTiling) + let clearFullScreenTilingOptOut: () -> Void = { [weak window] in + guard let window else { return } + window.collectionBehavior.remove(.fullScreenDisallowsTiling) + if window.collectionBehavior.contains(.fullScreenDisallowsTiling) { + var behavior = window.collectionBehavior + behavior.remove(.fullScreenDisallowsTiling) + window.collectionBehavior = behavior + } + } + RunLoop.main.perform { + clearFullScreenTilingOptOut() + } + DispatchQueue.main.async { + clearFullScreenTilingOptOut() } } if let explicitInitialFrame { @@ -11014,7 +11024,6 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent private func installShortcutDefaultsObserver() { guard shortcutDefaultsObserver == nil else { return } - refreshConfiguredShortcutChordActions() shortcutDefaultsObserver = NotificationCenter.default.addObserver( forName: KeyboardShortcutSettings.didChangeNotification, object: nil, @@ -11033,13 +11042,12 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent } private func handleShortcutDefaultsDidChange() { - refreshConfiguredShortcutChordActions() clearConfiguredShortcutChordState() scheduleSplitButtonTooltipRefreshAcrossWorkspaces() } - private func refreshConfiguredShortcutChordActions() { - configuredShortcutChordActions = KeyboardShortcutSettings.Action.allCases.filter { action in + private func currentConfiguredShortcutChordActions() -> [KeyboardShortcutSettings.Action] { + KeyboardShortcutSettings.Action.allCases.filter { action in // System-wide hotkeys are dispatched via Carbon RegisterEventHotKey // and never routed through AppKit's local key handler. If a managed // cmux.json entry somehow stores one as a chord, arming the prefix @@ -11720,12 +11728,23 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent return false } + if activeConfiguredShortcutChordPrefixForCurrentEvent == nil { + let focusContext = shortcutEventFocusContext(event) + let availableChordActions = currentConfiguredShortcutChordActions().filter { action in + action.shortcutContext.isAlwaysAvailable || action.shortcutContext.isAvailable(focusContext) + } + if armConfiguredShortcutChordIfNeeded(event: event, actions: availableChordActions) { + return true + } + } + let configuredCmuxShortcutContext = preferredMainWindowContextForShortcutRouting(event: event) let configuredCmuxShortcutActions = configuredCmuxShortcutActions(for: configuredCmuxShortcutContext) if activeConfiguredShortcutChordPrefixForCurrentEvent == nil, armConfiguredShortcutChordIfNeeded( event: event, + actions: [], shortcuts: configuredCmuxShortcutActions.compactMap(\.shortcut) ) { return true @@ -11814,7 +11833,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent // deferring the toggle, NSAnimationContext implicitly animates the // layout change. let preferredWindow = mainWindowForShortcutEvent(event) ?? event.window ?? NSApp.keyWindow ?? NSApp.mainWindow - Task { @MainActor [weak self, weak preferredWindow] in + DispatchQueue.main.async { [weak self, weak preferredWindow] in _ = self?.toggleRightSidebarInActiveMainWindow(preferredWindow: preferredWindow) } return true @@ -13204,7 +13223,6 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent } func debugResetShortcutRoutingStateForTesting() { - refreshConfiguredShortcutChordActions() clearConfiguredShortcutChordState() shortcutEventFocusContextCache = nil } @@ -13398,11 +13416,11 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent private func armConfiguredShortcutChordIfNeeded( event: NSEvent, - actions: [KeyboardShortcutSettings.Action]? = nil, + actions: [KeyboardShortcutSettings.Action], shortcuts: [StoredShortcut] = [] ) -> Bool { var seen = Set() - let configuredShortcuts = (actions ?? configuredShortcutChordActions).map { + let configuredShortcuts = actions.map { KeyboardShortcutSettings.shortcut(for: $0) } + shortcuts for shortcut in configuredShortcuts { diff --git a/Sources/KeyboardShortcutSettings.swift b/Sources/KeyboardShortcutSettings.swift index 2771d6a66634..6686e0a82521 100644 --- a/Sources/KeyboardShortcutSettings.swift +++ b/Sources/KeyboardShortcutSettings.swift @@ -456,7 +456,13 @@ enum KeyboardShortcutSettings { return normalized } - return usesNumberedDigitMatching || self == .showHideAllWindows || self == .globalSearch ? nil : shortcut + // Preserve invalid settings-file values for the show/hide hotkey so managed + // configuration remains visible instead of silently falling back to defaults. + // Runtime registration still rejects unsupported Carbon hotkey shapes. + if usesNumberedDigitMatching || self == .globalSearch { + return nil + } + return shortcut } func resolvedRecordedShortcutIgnoringConflicts(_ shortcut: StoredShortcut, checkingSystemWideConflicts: Bool = true) -> RecordedShortcutResolution { @@ -2174,7 +2180,7 @@ extension ShortcutStroke { private static func parseConfigKeyToken(_ rawValue: String) -> String? { let trimmed = rawValue.trimmingCharacters(in: .whitespacesAndNewlines) if trimmed.isEmpty { - return !rawValue.isEmpty && rawValue.allSatisfy { $0 == " " } ? "space" : nil + return rawValue == " " ? "space" : nil } let lowered = trimmed.lowercased() @@ -2275,8 +2281,10 @@ extension StoredShortcut { private static func isUnboundConfigToken(_ rawValue: String) -> Bool { if rawValue.isEmpty { return true } + if rawValue == " " { return false } let normalized = rawValue.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() - return normalized.isEmpty || normalized == "none" || normalized == "clear" || normalized == "unbound" || normalized == "disabled" + guard !normalized.isEmpty else { return true } + return normalized == "none" || normalized == "clear" || normalized == "unbound" || normalized == "disabled" } } diff --git a/Sources/TabManager.swift b/Sources/TabManager.swift index 87b9f79f3b7b..684bc1cae6e8 100644 --- a/Sources/TabManager.swift +++ b/Sources/TabManager.swift @@ -1974,7 +1974,8 @@ class TabManager: ObservableObject { selectedTerminalPanel?.hasSelection() == true } - func startSearch() { + @discardableResult + func startSearch() -> Bool { if let panel = selectedTerminalPanel { let hadExistingSearch = panel.searchState != nil panel.hostedView.preparePanelFocusIntentForActivation(.findField) @@ -1994,9 +1995,11 @@ class TabManager: ObservableObject { "firstResponder=\(String(describing: panel.surface.uiWindow?.firstResponder))" ) #endif - return + return handled } - focusedBrowserPanel?.startFind() + guard let browserPanel = focusedBrowserPanel else { return false } + browserPanel.startFind() + return browserPanel.searchState != nil } func searchSelection() { diff --git a/Sources/Update/UpdateTitlebarAccessory.swift b/Sources/Update/UpdateTitlebarAccessory.swift index 9cd7f5e6f370..01ba988fa028 100644 --- a/Sources/Update/UpdateTitlebarAccessory.swift +++ b/Sources/Update/UpdateTitlebarAccessory.swift @@ -1843,7 +1843,8 @@ final class UpdateTitlebarAccessoryController { queue: .main ) { [weak self] notification in guard let window = notification.object as? NSWindow else { return } - Task { @MainActor [weak self] in + Task { @MainActor [weak self, weak window] in + guard let window else { return } self?.attachIfNeeded(to: window) } }) @@ -1854,7 +1855,8 @@ final class UpdateTitlebarAccessoryController { queue: .main ) { [weak self] notification in guard let window = notification.object as? NSWindow else { return } - Task { @MainActor [weak self] in + Task { @MainActor [weak self, weak window] in + guard let window else { return } self?.attachIfNeeded(to: window) } }) diff --git a/cmuxTests/AppDelegateEqualizeSplitsShortcutTests.swift b/cmuxTests/AppDelegateEqualizeSplitsShortcutTests.swift index 302525c1da99..58623a5acd6b 100644 --- a/cmuxTests/AppDelegateEqualizeSplitsShortcutTests.swift +++ b/cmuxTests/AppDelegateEqualizeSplitsShortcutTests.swift @@ -113,6 +113,9 @@ final class AppDelegateEqualizeSplitsShortcutTests: XCTestCase { XCTFail("Expected cached layout snapshot after seeding split geometry") return } + let expectedEqualizedPositions = shortcutRoutingExpectedEqualizedDividerPositions( + in: workspace.bonsplitController.treeSnapshot() + ) guard let event = makeKeyDownEvent(key: "=", modifiers: [.command, .control], keyCode: 24, windowNumber: window.windowNumber) else { XCTFail("Failed to construct Cmd+Ctrl+= event") @@ -130,7 +133,11 @@ final class AppDelegateEqualizeSplitsShortcutTests: XCTestCase { let equalizedSplits = shortcutRoutingSplitNodes(in: workspace.bonsplitController.treeSnapshot()) XCTAssertEqual(equalizedSplits.count, seededSplits.count) for split in equalizedSplits { - XCTAssertEqual(split.dividerPosition, 0.5, accuracy: 0.000_1) + guard let expectedPosition = expectedEqualizedPositions[split.id] else { + XCTFail("Expected equalized split ID to remain present") + continue + } + XCTAssertEqual(split.dividerPosition, expectedPosition, accuracy: 0.000_1) } let liveEqualizedLayout = workspace.bonsplitController.layoutSnapshot() @@ -154,6 +161,27 @@ final class AppDelegateEqualizeSplitsShortcutTests: XCTestCase { } } + private func shortcutRoutingExpectedEqualizedDividerPositions(in node: ExternalTreeNode) -> [String: Double] { + var positionsBySplitId: [String: Double] = [:] + + @discardableResult + func collectLeafCount(_ node: ExternalTreeNode) -> Int { + switch node { + case .pane: + return 1 + case .split(let split): + let firstLeafCount = collectLeafCount(split.first) + let secondLeafCount = collectLeafCount(split.second) + let totalLeafCount = firstLeafCount + secondLeafCount + positionsBySplitId[split.id] = Double(firstLeafCount) / Double(totalLeafCount) + return totalLeafCount + } + } + + collectLeafCount(node) + return positionsBySplitId + } + private func shortcutRoutingPaneFramesById(in snapshot: LayoutSnapshot) -> [String: PixelRect] { Dictionary(uniqueKeysWithValues: snapshot.panes.map { ($0.paneId, $0.frame) }) } diff --git a/cmuxTests/AppDelegateShortcutRoutingTests.swift b/cmuxTests/AppDelegateShortcutRoutingTests.swift index 9bbd0c11749f..920e91362dc3 100644 --- a/cmuxTests/AppDelegateShortcutRoutingTests.swift +++ b/cmuxTests/AppDelegateShortcutRoutingTests.swift @@ -344,6 +344,9 @@ final class AppDelegateShortcutRoutingTests: XCTestCase { fallbackPath: nil, startWatching: false ) + #if DEBUG + appDelegate.debugResetShortcutRoutingStateForTesting() + #endif window.makeKeyAndOrderFront(nil) RunLoop.main.run(until: Date(timeIntervalSinceNow: 0.05)) @@ -820,7 +823,9 @@ final class AppDelegateShortcutRoutingTests: XCTestCase { ) appDelegate.debugCreateMainWindowSourceIsNativeFullScreenOverride = nil - RunLoop.main.run(until: Date(timeIntervalSinceNow: 0.05)) + waitUntil(timeout: 1.0) { + !newWindow.collectionBehavior.contains(.fullScreenDisallowsTiling) + } XCTAssertFalse( newWindow.collectionBehavior.contains(.fullScreenDisallowsTiling), @@ -1691,12 +1696,16 @@ final class AppDelegateShortcutRoutingTests: XCTestCase { } let windowId = appDelegate.createMainWindow() + defer { closeWindow(withId: windowId) } guard let targetWindow = window(withId: windowId) else { XCTFail("Expected test window") return } + targetWindow.makeKeyAndOrderFront(nil) + RunLoop.main.run(until: Date(timeIntervalSinceNow: 0.05)) appDelegate.debugCloseMainWindowConfirmationHandler = { _ in true } + defer { appDelegate.debugCloseMainWindowConfirmationHandler = nil } guard let event = makeKeyDownEvent( key: "w", @@ -1714,9 +1723,14 @@ final class AppDelegateShortcutRoutingTests: XCTestCase { XCTFail("debugHandleCustomShortcut is only available in DEBUG") #endif - RunLoop.main.run(until: Date(timeIntervalSinceNow: 0.05)) + waitUntil(timeout: 1.0) { + self.window(withId: windowId)?.isVisible != true + } - XCTAssertNil(self.window(withId: windowId), "Confirming Cmd+Ctrl+W should close the window") + XCTAssertFalse( + self.window(withId: windowId)?.isVisible == true, + "Confirming Cmd+Ctrl+W should close the window" + ) } // NOTE: This test is skipped in CI via -skip-testing in ci.yml because closing @@ -1839,6 +1853,16 @@ final class AppDelegateShortcutRoutingTests: XCTestCase { AppDelegate.installWindowResponderSwizzlesForTesting() + let windowId = appDelegate.createMainWindow() + defer { closeWindow(withId: windowId) } + + guard let mainWindow = window(withId: windowId) else { + XCTFail("Expected test main window") + return + } + mainWindow.makeKeyAndOrderFront(nil) + RunLoop.main.run(until: Date(timeIntervalSinceNow: 0.05)) + let previousMainMenu = NSApp.mainMenu let probeWindow = NSWindow( contentRect: NSRect(x: 0, y: 0, width: 320, height: 240), @@ -1846,6 +1870,7 @@ final class AppDelegateShortcutRoutingTests: XCTestCase { backing: .buffered, defer: false ) + probeWindow.isReleasedWhenClosed = false probeWindow.identifier = NSUserInterfaceItemIdentifier("cmux.browser-popup") let contentView = NSView(frame: probeWindow.contentRect(forFrameRect: probeWindow.frame)) let probeView = GhosttyCommandEquivalentProbeView(frame: NSRect(x: 0, y: 0, width: 200, height: 120)) @@ -1854,6 +1879,8 @@ final class AppDelegateShortcutRoutingTests: XCTestCase { defer { NSApp.mainMenu = previousMainMenu probeWindow.orderOut(nil) + probeWindow.close() + RunLoop.main.run(until: Date(timeIntervalSinceNow: 0.05)) } let staleMenu = NSMenu(title: "Test") @@ -3327,6 +3354,8 @@ final class AppDelegateShortcutRoutingTests: XCTestCase { XCTFail("Expected focused browser panel") return } + window.makeKeyAndOrderFront(nil) + RunLoop.main.run(until: Date(timeIntervalSinceNow: 0.05)) let field = OmnibarNativeTextField(frame: NSRect(x: 8, y: 8, width: 240, height: 24)) field.identifier = browserOmnibarTextFieldIdentifier @@ -3340,8 +3369,8 @@ final class AppDelegateShortcutRoutingTests: XCTestCase { field.removeFromSuperview() } - _ = browserPanel.requestAddressBarFocus() - NotificationCenter.default.post(name: .browserDidFocusAddressBar, object: browserPanelId) + XCTAssertTrue(appDelegate.requestBrowserAddressBarFocus(panelId: browserPanelId)) + XCTAssertEqual(appDelegate.focusedBrowserAddressBarPanelId(), browserPanelId) _ = window.makeFirstResponder(nil) XCTAssertTrue(window.firstResponder === window) @@ -4224,12 +4253,15 @@ final class AppDelegateShortcutRoutingTests: XCTestCase { XCTFail("Expected test window") return } + window.makeKeyAndOrderFront(nil) + RunLoop.main.run(until: Date(timeIntervalSinceNow: 0.05)) - let overlayContainer = NSView(frame: contentView.bounds) + let overlayHost = contentView.superview ?? contentView + let overlayContainer = NSView(frame: overlayHost.bounds) overlayContainer.identifier = commandPaletteOverlayContainerIdentifier overlayContainer.alphaValue = 1 overlayContainer.isHidden = false - contentView.addSubview(overlayContainer) + overlayHost.addSubview(overlayContainer) let fieldEditor = CommandPaletteMarkedTextFieldEditor(frame: NSRect(x: 0, y: 0, width: 200, height: 24)) fieldEditor.isFieldEditor = true @@ -4258,6 +4290,12 @@ final class AppDelegateShortcutRoutingTests: XCTestCase { } defer { NotificationCenter.default.removeObserver(moveToken) } + window.displayIfNeeded() + XCTAssertTrue( + window.makeFirstResponder(fieldEditor), + "Expected command palette field editor to own first responder" + ) + guard let downArrowEvent = makeKeyDownEvent( key: String(UnicodeScalar(NSDownArrowFunctionKey)!), modifiers: [], @@ -6068,6 +6106,19 @@ final class AppDelegateShortcutRoutingTests: XCTestCase { XCTFail("Expected focused terminal surface") return } + window.makeKeyAndOrderFront(nil) + window.displayIfNeeded() + terminalPanel.hostedView.setVisibleInUI(true) + terminalPanel.hostedView.setActive(true) + terminalPanel.hostedView.moveFocus() + waitUntil(timeout: 1.0) { + terminalPanel.hostedView.isSurfaceViewFirstResponder() + } + XCTAssertTrue( + terminalPanel.hostedView.isSurfaceViewFirstResponder(), + "Expected terminal surface to own first responder before Cmd+F" + ) + RunLoop.main.run(until: Date(timeIntervalSinceNow: 0.05)) appDelegate.noteTerminalKeyboardFocusIntent(workspaceId: workspace.id, panelId: terminalPanel.id, in: window) @@ -6087,6 +6138,9 @@ final class AppDelegateShortcutRoutingTests: XCTestCase { XCTFail("debugHandleCustomShortcut is only available in DEBUG") #endif + waitUntil(timeout: 1.0) { + terminalPanel.searchState != nil + } XCTAssertNotNil(terminalPanel.searchState, "Cmd+F from terminal focus should create terminal search state") } @@ -6475,6 +6529,13 @@ final class AppDelegateShortcutRoutingTests: XCTestCase { RunLoop.main.run(until: Date(timeIntervalSinceNow: 0.05)) } + private func waitUntil(timeout: TimeInterval, condition: () -> Bool) { + let deadline = Date(timeIntervalSinceNow: timeout) + while !condition(), Date() < deadline { + RunLoop.main.run(until: Date(timeIntervalSinceNow: 0.01)) + } + } + private func restoreDefaultsValue(_ value: Any?, forKey key: String, defaults: UserDefaults) { if let value { defaults.set(value, forKey: key) diff --git a/cmuxTests/KeyboardShortcutSpaceKeyTests.swift b/cmuxTests/KeyboardShortcutSpaceKeyTests.swift index 31d6a9eb594e..7ffd4363b10c 100644 --- a/cmuxTests/KeyboardShortcutSpaceKeyTests.swift +++ b/cmuxTests/KeyboardShortcutSpaceKeyTests.swift @@ -45,6 +45,9 @@ final class KeyboardShortcutSpaceKeyTests: XCTestCase { XCTAssertEqual(StoredShortcut.parseConfig("cmd+shift+spacebar")?.configIdentifier, "cmd+shift+space") XCTAssertEqual(StoredShortcut.parseConfig("cmd+shift+ ")?.configIdentifier, "cmd+shift+space") XCTAssertEqual(StoredShortcut.parseConfig(" ")?.configIdentifier, "space") + XCTAssertEqual(StoredShortcut.parseConfig(" "), .unbound) + XCTAssertEqual(StoredShortcut.parseConfig("\t"), .unbound) + XCTAssertNil(StoredShortcut.parseConfig("cmd+shift+ ")) } func testSettingsFileStoreParsesSpaceShortcutBinding() throws {