diff --git a/apps/desktop-gpui/src/hotkeys.rs b/apps/desktop-gpui/src/hotkeys.rs index 46bb17797cd..1759064916a 100644 --- a/apps/desktop-gpui/src/hotkeys.rs +++ b/apps/desktop-gpui/src/hotkeys.rs @@ -216,6 +216,11 @@ pub fn pause(cx: &mut App) -> bool { true } +pub fn is_paused(cx: &App) -> bool { + cx.try_global::() + .is_some_and(|hotkeys| hotkeys.paused) +} + pub fn editing_blocked(cx: &App) -> bool { #[cfg(target_os = "linux")] if cx diff --git a/apps/desktop-gpui/src/main_window.rs b/apps/desktop-gpui/src/main_window.rs index cabac8bdd14..bca844d3b06 100644 --- a/apps/desktop-gpui/src/main_window.rs +++ b/apps/desktop-gpui/src/main_window.rs @@ -851,6 +851,8 @@ pub struct MainWindow { input_enumeration_gate: devices::InputEnumerationGate, /// `scheduleTargetListPrewarm` (`new-main/index.tsx:1897-1965`). prewarm_task: Option>, + keyboard_nav: bool, + _keyboard_nav: gpui::Subscription, } /// `createLicenseQuery` (`utils/queries.ts:257-273`): pro from the auth @@ -1059,6 +1061,8 @@ impl MainWindow { }) .detach(); + let keyboard_nav = ui::keyboard_nav::install(window, cx, Self::keyboard_nav_blocked); + Self { theme, // `rawOptions.mode` -- the recording mode is a persisted setting, @@ -1113,9 +1117,19 @@ impl MainWindow { input_poll_generation: 0, input_enumeration_gate: devices::InputEnumerationGate::default(), prewarm_task: None, + keyboard_nav: false, + _keyboard_nav: keyboard_nav, } } + fn keyboard_nav_blocked(&self, cx: &gpui::App) -> bool { + self.session.read(cx).phase != Phase::Idle + || self.microphone_warning.is_some() + || self.sign_in_prompt.is_some() + || self.idle_error(cx).is_some() + || app_windows::clean_capture_pending(cx) + } + /// Kick off device enumeration. /// /// Deliberately *not* called from `new`. `new` runs inside `open_window`'s @@ -2695,6 +2709,10 @@ impl MainWindow { impl Render for MainWindow { fn render(&mut self, window: &mut Window, cx: &mut Context) -> impl IntoElement { self.sync_appearance(window, cx); + if self.keyboard_nav_blocked(cx) { + ui::keyboard_nav::leave(window, cx); + } + self.keyboard_nav = ui::keyboard_nav::active(window, cx); let theme = self.theme; let meter_active = self.panel.is_none() && self.microphone.is_some() @@ -2762,6 +2780,7 @@ impl Render for MainWindow { cx.stop_propagation(); } })) + .child(ui::keyboard_nav::pointer_watcher()) } } @@ -3456,6 +3475,7 @@ impl MainWindow { /// 8px from the window edges (`mx-2`). fn render_header_actions(&self, cx: &mut Context) -> impl IntoElement { let theme = self.theme; + let keyboard_nav = self.keyboard_nav; // `IconButton::header`: a 20px hit box with no fill, `text-gray-11` // going to `text-gray-12` on hover. @@ -3474,6 +3494,9 @@ impl MainWindow { .group(id) .when(cfg!(target_os = "windows"), |this| this.occlude()) .tab_index(0) + .when(keyboard_nav, ui::keyboard_nav::ring) + .role(gpui::Role::Button) + .aria_label(label) .flex() .items_center() .justify_center() @@ -3901,6 +3924,9 @@ impl MainWindow { .child( div() .id("panel-back") + .when(self.keyboard_nav, ui::keyboard_nav::stop) + .role(gpui::Role::Button) + .aria_label("Back") .flex() .flex_row() .items_center() @@ -5631,6 +5657,10 @@ impl MainWindow { div() .id(id) + .when(self.keyboard_nav, ui::keyboard_nav::stop) + .role(gpui::Role::Button) + .aria_label(label.clone()) + .aria_selected(selected) .flex() .flex_col() .w(px(self.target_card_width())) @@ -5876,6 +5906,10 @@ impl MainWindow { div() .id(id) + .when(self.keyboard_nav, ui::keyboard_nav::stop) + .role(gpui::Role::Button) + .aria_label(label.clone()) + .aria_selected(selected) .relative() .flex() .flex_row() @@ -6150,6 +6184,10 @@ impl MainWindow { div() .id(SharedString::from(id)) .tab_index(0) + .when(self.keyboard_nav, ui::keyboard_nav::ring) + .role(gpui::Role::Button) + .aria_label(mode.panel_title()) + .aria_selected(selected) .relative() .on_hover(cx.listener(move |this, hovered, _, cx| { this.update_mode_hover(mode, false, *hovered, cx); @@ -6218,6 +6256,9 @@ impl MainWindow { div() .id("mode-info") .tab_index(0) + .when(self.keyboard_nav, ui::keyboard_nav::ring) + .role(gpui::Role::Button) + .aria_label("Recording mode info") .tooltip(move |_, cx| ui::Tooltip::new(&theme, "Recording mode info").view(cx)) .tooltip_show_delay(ui::TOOLTIP_SHOW_DELAY) .absolute() @@ -6303,6 +6344,12 @@ impl MainWindow { .child( div() .id(dropdown_id.clone()) + .when(self.keyboard_nav, ui::keyboard_nav::stop) + .role(gpui::Role::Button) + .aria_label(match target { + TargetType::Display => "Choose a display", + _ => "Choose a window", + }) .flex() .w(px(28.)) .rounded_r(px(9.)) @@ -6394,6 +6441,10 @@ impl MainWindow { let base = div() .id(SharedString::from(target.label())) + .when(self.keyboard_nav, ui::keyboard_nav::stop) + .role(gpui::Role::Button) + .aria_label(target.label()) + .aria_selected(selected) .flex() .flex_1() .py(px(8.)) @@ -6567,6 +6618,9 @@ impl MainWindow { div() .id(SharedString::from(id)) + .when(self.keyboard_nav, ui::keyboard_nav::stop) + .role(gpui::Role::Button) + .aria_label(label.clone()) .relative() .flex() .flex_row() diff --git a/apps/desktop-gpui/src/menus.rs b/apps/desktop-gpui/src/menus.rs index 8e399636917..9624eca2612 100644 --- a/apps/desktop-gpui/src/menus.rs +++ b/apps/desktop-gpui/src/menus.rs @@ -26,9 +26,11 @@ use gpui::{ use crate::{ app_windows::{self, AppWindows}, + hotkeys, main_window::MainWindow, platform, session::{Phase, RecordingSession}, + settings_window::Page, store, ui::text_input, }; @@ -66,6 +68,8 @@ actions!( Zoom, /// `PredefinedMenuItem::fullscreen` -- ⌃⌘F. ToggleFullscreen, + /// Settings… -- ⌘, on macOS, Ctrl+, on Windows and Linux. + OpenSettings, ] ); @@ -77,14 +81,7 @@ pub fn init(cx: &mut App) { // commands. Deliberately *not* including cmd-z/x/c/v/a -- those stay the // text field's own `TextInput`-scoped bindings (and, for the editor, its // `on_key_down` project-undo). A global binding here would shadow both. - cx.bind_keys([ - KeyBinding::new("cmd-q", Quit, None), - KeyBinding::new("cmd-h", HideSelf, None), - KeyBinding::new("alt-cmd-h", HideOthers, None), - KeyBinding::new("cmd-w", CloseWindow, None), - KeyBinding::new("cmd-m", Minimize, None), - KeyBinding::new("ctrl-cmd-f", ToggleFullscreen, None), - ]); + cx.bind_keys(bindings()); cx.on_action(|_: &About, cx: &mut App| { // Ordering a window front re-enters gpui's window callbacks, so it runs @@ -99,6 +96,29 @@ pub fn init(cx: &mut App) { cx.on_action(|_: &CloseWindow, cx: &mut App| close_key_window(cx)); cx.on_action(|_: &Minimize, cx: &mut App| with_key_native(cx, platform::minimize_native)); cx.on_action(|_: &Zoom, cx: &mut App| with_key_native(cx, platform::zoom_native)); + cx.on_action(|_: &OpenSettings, cx: &mut App| { + // While a recording runs, onboarding is up or the Shortcuts page is + // recording a combo, the chord belongs to whatever has focus. + let idle = RecordingSession::global(cx).read(cx).phase == Phase::Idle; + let onboarding_open = cx + .try_global::() + .is_some_and(|windows| windows.onboarding.is_some()); + if !settings_shortcut_allowed(idle, onboarding_open, hotkeys::is_paused(cx)) { + cx.propagate(); + return; + } + // Deferred: the keystroke arrives inside the key window's dispatch, and + // `open_settings` updates the settings window, which may be that one. + cx.defer(|cx: &mut App| { + let page = cx + .try_global::() + .and_then(|windows| windows.settings) + .and_then(|settings| settings.read(cx).ok().map(|settings| settings.page)) + .unwrap_or(Page::General); + app_windows::open_settings(page, cx); + cx.activate(true); + }); + }); cx.on_action(|_: &ToggleFullscreen, cx: &mut App| { #[cfg(target_os = "windows")] if let Some(handle) = cx.active_window() { @@ -113,6 +133,22 @@ pub fn init(cx: &mut App) { cx.set_menus(build_menus()); } +pub(crate) fn bindings() -> Vec { + vec![ + KeyBinding::new("cmd-q", Quit, None), + KeyBinding::new("cmd-h", HideSelf, None), + KeyBinding::new("alt-cmd-h", HideOthers, None), + KeyBinding::new("cmd-w", CloseWindow, None), + KeyBinding::new("cmd-m", Minimize, None), + KeyBinding::new("ctrl-cmd-f", ToggleFullscreen, None), + KeyBinding::new("secondary-,", OpenSettings, None), + ] +} + +fn settings_shortcut_allowed(idle: bool, onboarding_open: bool, hotkeys_paused: bool) -> bool { + idle && !onboarding_open && !hotkeys_paused +} + /// The menu bar model. /// /// One-to-one with `build_macos_app_menu`, including the empty Help submenu @@ -125,6 +161,8 @@ pub fn build_menus() -> Vec { items: vec![ MenuItem::action(format!("About {APP_NAME}"), About), MenuItem::separator(), + MenuItem::action("Settings…", OpenSettings), + MenuItem::separator(), MenuItem::os_submenu("Services", SystemMenuType::Services), MenuItem::separator(), MenuItem::action(format!("Hide {APP_NAME}"), HideSelf), @@ -880,6 +918,58 @@ mod tests { assert!(gate.pending.is_none()); } + #[test] + fn settings_shortcut_yields_to_recording_onboarding_and_the_recorder() { + assert!(settings_shortcut_allowed(true, false, false)); + assert!(!settings_shortcut_allowed(false, false, false)); + assert!(!settings_shortcut_allowed(true, true, false)); + assert!(!settings_shortcut_allowed(true, false, true)); + } + + fn keystrokes(binding: &KeyBinding) -> Vec { + binding + .keystrokes() + .iter() + .map(|keystroke| keystroke.inner().clone()) + .collect() + } + + #[test] + fn global_keymap_is_unchanged_apart_from_settings() { + let settings = if cfg!(target_os = "macos") { + "cmd-," + } else { + "ctrl-," + }; + let expected: &[(&str, &dyn gpui::Action)] = &[ + ("cmd-q", &Quit), + ("cmd-h", &HideSelf), + ("alt-cmd-h", &HideOthers), + ("cmd-w", &CloseWindow), + ("cmd-m", &Minimize), + ("ctrl-cmd-f", &ToggleFullscreen), + (settings, &OpenSettings), + ]; + let bindings = bindings(); + assert_eq!(bindings.len(), expected.len()); + for (binding, (source, action)) in bindings.iter().zip(expected) { + assert_eq!( + keystrokes(binding), + vec![gpui::Keystroke::parse(source).unwrap()], + "{source}" + ); + assert!(binding.action().partial_eq(*action), "{source}"); + assert!(binding.predicate().is_none(), "{source}"); + } + let mut seen = std::collections::HashSet::new(); + for binding in &bindings { + assert!( + seen.insert(keystrokes(binding)), + "{binding:?} is bound twice" + ); + } + } + /// The menu bar, transcribed from `build_macos_app_menu`. Separators are /// spelled `"-"` so the ordering is checked too. fn describe(menu: &Menu) -> (String, Vec) { @@ -907,6 +997,8 @@ mod tests { vec![ "About Cap".to_string(), "-".into(), + "Settings…".into(), + "-".into(), "Services".into(), "-".into(), "Hide Cap".into(), diff --git a/apps/desktop-gpui/src/mode_select_window.rs b/apps/desktop-gpui/src/mode_select_window.rs index 660d27316c8..77dc4fc84c6 100644 --- a/apps/desktop-gpui/src/mode_select_window.rs +++ b/apps/desktop-gpui/src/mode_select_window.rs @@ -9,11 +9,11 @@ use gpui::{ Context, FocusHandle, FontWeight, Hsla, InteractiveElement, IntoElement, ParentElement, Pixels, - Point, Render, SharedString, StatefulInteractiveElement, Styled, Window, div, - prelude::FluentBuilder, px, svg, + Point, Render, Role, SharedString, StatefulInteractiveElement, Styled, Subscription, Window, + div, prelude::FluentBuilder, px, svg, }; -use crate::{main_window::Mode, theme::Theme}; +use crate::{main_window::Mode, theme::Theme, ui::keyboard_nav}; /// `.inner_size(580.0, 340.0)` / `.min_inner_size(580.0, 340.0)` / /// `.resizable(false)` on the `ShowCapWindow::ModeSelect` arm in `windows.rs`, @@ -45,6 +45,8 @@ pub struct ModeSelectWindow { /// cannot drift. mode: Mode, focus: FocusHandle, + keyboard_nav: bool, + _keyboard_nav: Subscription, } impl ModeSelectWindow { @@ -67,6 +69,8 @@ impl ModeSelectWindow { theme: Theme::for_window(window, cx, false), mode, focus: cx.focus_handle(), + keyboard_nav: false, + _keyboard_nav: keyboard_nav::install(window, cx, |_, _| false), } } @@ -104,6 +108,11 @@ impl ModeSelectWindow { div() .id(SharedString::from(mode.panel_title())) + .when(self.keyboard_nav, keyboard_nav::stop) + .role(Role::Button) + .aria_label(mode.panel_title()) + .aria_description(mode.card_description()) + .aria_selected(selected) .relative() .flex() .flex_col() @@ -236,10 +245,12 @@ impl ModeSelectWindow { impl Render for ModeSelectWindow { fn render(&mut self, window: &mut Window, cx: &mut Context) -> impl IntoElement { self.sync_appearance(window, cx); + self.keyboard_nav = keyboard_nav::active(window, cx); let theme = self.theme; let shell = div() .track_focus(&self.focus) + .child(keyboard_nav::pointer_watcher()) // `flex flex-col relative justify-center items-center min-h-screen // bg-gray-1` .size_full() diff --git a/apps/desktop-gpui/src/settings_pages.rs b/apps/desktop-gpui/src/settings_pages.rs index c0d5d6bb421..530a8df630f 100644 --- a/apps/desktop-gpui/src/settings_pages.rs +++ b/apps/desktop-gpui/src/settings_pages.rs @@ -20,12 +20,12 @@ use std::{ time::Duration, }; +use cap_cli_install as cli_install; use gpui::{ AppContext as _, Context, Entity, FontWeight, Hsla, InteractiveElement, IntoElement, MouseButton, ParentElement, SharedString, StatefulInteractiveElement, Styled, Window, div, prelude::FluentBuilder, px, rgb, svg, }; -use cap_cli_install as cli_install; use serde::Deserialize; use serde_json::{Map, Value, json}; @@ -1329,6 +1329,14 @@ impl SettingsWindow { cx.notify(); } + pub(crate) fn shortcut_listening(&self) -> bool { + self.pages.listening.is_some() + } + + pub(crate) fn switch_back_running(&self) -> bool { + self.pages.switch_back.is_some() + } + /// Leave recording mode without touching the binding. Safe to call when /// nothing is recording; every exit path (Escape, a click elsewhere, /// another page, the window losing focus or closing) lands here. @@ -2616,6 +2624,7 @@ impl SettingsWindow { ), self.toggle( "out-of-process-muxer", + "Out-of-process muxer", self.settings.out_of_process_muxer, cx, |this, cx| { @@ -2658,14 +2667,20 @@ impl SettingsWindow { "Turn off to close this app and reopen the classic Tauri app in the dev harness. \ Recordings and settings are shared.", ), - self.toggle("enable-gpui-app", checked, cx, |this, cx| { - match this.pages.switch_back { - Some(SwitchBack::Running(_)) => this.cancel_switch_back(cx), - // Committed: the classic app is already being brought up. - Some(SwitchBack::WaitingForClassic) => {} - _ => this.start_switch_back(cx), - } - }) + self.toggle( + "enable-gpui-app", + "Use native app", + checked, + cx, + |this, cx| { + match this.pages.switch_back { + Some(SwitchBack::Running(_)) => this.cancel_switch_back(cx), + // Committed: the classic app is already being brought up. + Some(SwitchBack::WaitingForClassic) => {} + _ => this.start_switch_back(cx), + } + }, + ) .into_any_element(), ) } @@ -3391,6 +3406,7 @@ impl SettingsWindow { ), self.toggle( "diagnostic-mic", + "Test microphone", self.pages.diagnostic_mic, cx, |this, cx| { @@ -6988,15 +7004,19 @@ impl SettingsWindow { (false, true) => "Disabled · Not saved", }), ) - .child( - self.toggle(("rule-enabled", index), enabled, cx, move |this, cx| { + .child(self.toggle( + ("rule-enabled", index), + "Enabled", + enabled, + cx, + move |this, cx| { if let Some(rule) = this.pages.automations.rules.get_mut(index) { rule.enabled = !rule.enabled; this.automations_persist(); cx.notify(); } - }), - ), + }, + )), ) .child( div() @@ -7685,6 +7705,7 @@ impl SettingsWindow { SharedString::from(format!( "action-copy-link-{rule}-{index}" )), + "Copy link to clipboard", copy_link, cx, move |this, cx| { @@ -7717,6 +7738,7 @@ impl SettingsWindow { SharedString::from(format!( "action-open-browser-{rule}-{index}" )), + "Open in browser", open_in_browser, cx, move |this, cx| { @@ -7771,6 +7793,7 @@ impl SettingsWindow { .gap(px(8.)) .child(self.toggle( SharedString::from(format!("action-shell-{rule}-{index}")), + "Run through shell", use_shell, cx, move |this, cx| { diff --git a/apps/desktop-gpui/src/settings_window.rs b/apps/desktop-gpui/src/settings_window.rs index 52d2a2fd3c7..df60d2eadf2 100644 --- a/apps/desktop-gpui/src/settings_window.rs +++ b/apps/desktop-gpui/src/settings_window.rs @@ -663,6 +663,8 @@ pub struct SettingsWindow { _sign_in_subscriptions: [gpui::Subscription; 2], user_profile: Option, profile_image: Option>, + keyboard_nav: bool, + _keyboard_nav: gpui::Subscription, } impl SettingsWindow { @@ -749,6 +751,9 @@ impl SettingsWindow { let pages = crate::settings_pages::PagesState::new(window, cx); let page_scroll = ScrollHandle::new(); + let keyboard_nav = ui::keyboard_nav::install(window, cx, |this: &Self, _| { + this.menu.is_some() || this.shortcut_listening() || this.switch_back_running() + }); Self { theme, @@ -784,6 +789,8 @@ impl SettingsWindow { _sign_in_subscriptions: sign_in_subscriptions, user_profile, profile_image: None, + keyboard_nav: false, + _keyboard_nav: keyboard_nav, } } @@ -1553,6 +1560,10 @@ fn covers_default_exclusion(entry: &WindowExclusion, default: &WindowExclusion) impl Render for SettingsWindow { fn render(&mut self, window: &mut Window, cx: &mut Context) -> impl IntoElement { self.sync_appearance(window, cx); + if self.switch_back_running() { + ui::keyboard_nav::leave(window, cx); + } + self.keyboard_nav = ui::keyboard_nav::active(window, cx); let theme = self.theme; if self.page == Page::Quality && let Some(mode) = self.quality_scroll_request.take() @@ -1567,6 +1578,7 @@ impl Render for SettingsWindow { let shell = div() .track_focus(&self.focus) + .child(ui::keyboard_nav::pointer_watcher()) // `(window-chrome).tsx` binds Cmd-W to `getCurrentWindow().close()` // for every chrome window. Escape is not bound there and is not // bound here. @@ -1774,6 +1786,7 @@ impl SettingsWindow { div() .id("settings-nav") + .role(gpui::Role::TabList) .flex() .flex_col() // `.cap-settings-nav { padding: 0 var(--sidebar-padding-x) @@ -1788,6 +1801,10 @@ impl SettingsWindow { let selected = page == self.page; div() .id(SharedString::from(page.slug())) + .when(self.keyboard_nav, ui::keyboard_nav::stop) + .role(gpui::Role::Tab) + .aria_label(page.label()) + .aria_selected(selected) .flex() .flex_row() .items_center() @@ -3051,6 +3068,7 @@ impl SettingsWindow { // The row is the *inverse* of the stored key. self.toggle( "hide-dock-icon", + "Always show dock icon", !self.settings.hide_dock_icon, cx, |this, cx| { @@ -3074,6 +3092,7 @@ impl SettingsWindow { ), self.toggle( "enable-notifications", + "System notifications", self.settings.enable_notifications, cx, |this, cx| { @@ -3133,6 +3152,7 @@ impl SettingsWindow { Some("Open the link in your browser when an upload finishes."), self.toggle( "auto-open-links", + "Open share links automatically", !self.settings.disable_auto_open_links, cx, |this, cx| { @@ -3415,6 +3435,7 @@ impl SettingsWindow { ), self.toggle( "confirm-without-mic", + "Confirm before recording without a microphone", settings.confirm_without_microphone, cx, |this, cx| { @@ -3441,6 +3462,7 @@ impl SettingsWindow { ), self.toggle( "studio-sound-default", + "Studio Sound on new recordings", settings.studio_sound_by_default, cx, |this, cx| { @@ -3485,6 +3507,7 @@ impl SettingsWindow { Some("Cap removes the local file once it has uploaded successfully."), self.toggle( "delete-after-upload", + "Delete Instant recordings after upload", settings.delete_instant_recordings_after_upload, cx, |this, cx| { @@ -3504,6 +3527,7 @@ impl SettingsWindow { ), self.toggle( "crash-recovery", + "Crash-recoverable recording", settings.crash_recovery_recording, cx, |this, cx| { @@ -3523,6 +3547,7 @@ impl SettingsWindow { ), self.toggle( "custom-cursor", + "Custom cursor capture (Studio)", settings.custom_cursor_capture, cx, |this, cx| { @@ -3540,11 +3565,18 @@ impl SettingsWindow { "Automatically add zoom segments around mouse clicks in Studio \ recordings.", ), - self.toggle("auto-zoom", settings.auto_zoom_on_clicks, cx, |this, cx| { - this.settings.auto_zoom_on_clicks = !this.settings.auto_zoom_on_clicks; - let value = this.settings.auto_zoom_on_clicks; - this.write_bool("autoZoomOnClicks", value, cx); - }) + self.toggle( + "auto-zoom", + "Auto zoom on clicks", + settings.auto_zoom_on_clicks, + cx, + |this, cx| { + this.settings.auto_zoom_on_clicks = + !this.settings.auto_zoom_on_clicks; + let value = this.settings.auto_zoom_on_clicks; + this.write_bool("autoZoomOnClicks", value, cx); + }, + ) .into_any_element(), ), self.setting_row( @@ -3573,6 +3605,7 @@ impl SettingsWindow { Some("Record key presses so you can add keyboard overlays in the editor."), self.toggle( "capture-keyboard", + "Capture keyboard presses", settings.capture_keyboard_events, cx, |this, cx| { @@ -3594,6 +3627,7 @@ impl SettingsWindow { ), self.toggle( "notch-overlay", + "Draw the MacBook notch on screen recordings", settings.macbook_notch_overlay, cx, |this, cx| { @@ -4273,6 +4307,7 @@ impl SettingsWindow { ), self.toggle( "telemetry", + "Share anonymous telemetry", self.settings.enable_telemetry, cx, |this, cx| { @@ -4341,11 +4376,13 @@ impl SettingsWindow { pub(crate) fn toggle( &self, id: impl Into, + label: impl Into, checked: bool, cx: &mut Context, on_change: impl Fn(&mut Self, &mut Context) + 'static, ) -> ui::Toggle { ui::Toggle::settings(&self.theme, id, checked) + .label(label) .on_click(cx.listener(move |this, _, _window, cx| on_change(this, cx))) } diff --git a/apps/desktop-gpui/src/ui/button.rs b/apps/desktop-gpui/src/ui/button.rs index 048cadefad7..fc574124502 100644 --- a/apps/desktop-gpui/src/ui/button.rs +++ b/apps/desktop-gpui/src/ui/button.rs @@ -8,7 +8,7 @@ use gpui::{ prelude::FluentBuilder, px, svg, }; -use super::menu::OpenHandler; +use super::{keyboard_nav, menu::OpenHandler}; use crate::theme::Theme; /// The click handler every component takes. `cx.listener(..)` produces exactly @@ -408,7 +408,7 @@ fn radix_paint(theme: &Theme, variant: ButtonVariant) -> ButtonPaint { } impl RenderOnce for Button { - fn render(self, _window: &mut Window, _cx: &mut App) -> impl IntoElement { + fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement { let Button { id, label, @@ -433,6 +433,8 @@ impl RenderOnce for Button { div() .id(id) .tab_index(0) + .tab_stop(!disabled) + .when(keyboard_nav::active(window, cx), keyboard_nav::ring) .flex() .flex_row() .items_center() @@ -635,7 +637,7 @@ impl IconButton { } impl RenderOnce for IconButton { - fn render(self, _window: &mut Window, _cx: &mut App) -> impl IntoElement { + fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement { let IconButton { id, icon, @@ -659,6 +661,8 @@ impl RenderOnce for IconButton { .id(id) .when(occlude, |this| this.occlude()) .tab_index(0) + .tab_stop(!disabled) + .when(keyboard_nav::active(window, cx), keyboard_nav::ring) .flex() .items_center() .justify_center() diff --git a/apps/desktop-gpui/src/ui/keyboard_nav.rs b/apps/desktop-gpui/src/ui/keyboard_nav.rs new file mode 100644 index 00000000000..48ec552921d --- /dev/null +++ b/apps/desktop-gpui/src/ui/keyboard_nav.rs @@ -0,0 +1,202 @@ +//! Tab / Shift-Tab focus navigation for the windows that opt in. +//! +//! Nothing in a window has focus until the user presses Tab, and the main +//! window has no root focus handle, so a key binding would never match there: +//! with no focused node only the root receives keys. An owner-scoped +//! keystroke interceptor runs before bindings and element listeners instead. +//! +//! Tab stops that are not already focusable are only added while a window is +//! in keyboard mode, which starts on Tab and ends on the next mouse press. A +//! focusable element takes focus on click and fires its click handler on +//! Enter/Space key-up, so adding them unconditionally would change what mouse +//! users get. + +use std::collections::HashSet; + +use gpui::{ + App, BoxShadow, Context, DispatchPhase, Global, InteractiveElement, IntoElement, Keystroke, + MouseDownEvent, Styled, Subscription, Window, WindowId, canvas, point, px, rgb, +}; + +use crate::{theme::Theme, ui::text_input::text_input_is_composing}; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Direction { + Next, + Previous, +} + +pub fn direction(keystroke: &Keystroke) -> Option { + let modifiers = keystroke.modifiers; + if keystroke.key != "tab" + || modifiers.control + || modifiers.alt + || modifiers.platform + || modifiers.function + { + return None; + } + Some(if modifiers.shift { + Direction::Previous + } else { + Direction::Next + }) +} + +fn takes_tab(blocked: bool, prompt_active: bool, composing: bool) -> bool { + !(blocked || prompt_active || composing) +} + +#[derive(Default)] +struct KeyboardWindows(HashSet); + +impl Global for KeyboardWindows {} + +pub fn active(window: &Window, cx: &App) -> bool { + cx.try_global::() + .is_some_and(|windows| windows.0.contains(&window.window_handle().window_id())) +} + +pub fn leave(window: &mut Window, cx: &mut App) { + let id = window.window_handle().window_id(); + if cx.has_global::() && cx.global_mut::().0.remove(&id) { + window.refresh(); + } +} + +/// Leaves keyboard mode on any mouse press in the window. A window-level +/// listener, because `.occlude()` hitboxes (menus, modals, the Windows header) +/// hide the root from element mouse listeners. +pub fn pointer_watcher() -> impl IntoElement { + canvas( + |_, _, _| (), + |_, (), window, _| { + window.on_mouse_event(|_: &MouseDownEvent, phase, window, cx| { + if phase == DispatchPhase::Capture { + leave(window, cx); + } + }); + }, + ) + .absolute() + .inset_0() +} + +/// Route Tab in `window` to focus navigation. `blocked` lets the owner keep +/// Tab for itself, e.g. while a shortcut recorder or a modal is up. +pub fn install( + window: &Window, + cx: &mut Context, + blocked: impl Fn(&V, &App) -> bool + 'static, +) -> Subscription { + let owner = window.window_handle().window_id(); + let view = cx.weak_entity(); + cx.intercept_keystrokes(move |event, window, cx| { + if window.window_handle().window_id() != owner { + return; + } + let Some(direction) = direction(&event.keystroke) else { + return; + }; + let Some(view) = view.upgrade() else { + return; + }; + if !takes_tab( + blocked(view.read(cx), cx), + window.has_active_prompt(), + text_input_is_composing(window, cx), + ) { + return; + } + navigate(direction, window, cx); + window.prevent_default(); + cx.stop_propagation(); + }) +} + +fn navigate(direction: Direction, window: &mut Window, cx: &mut App) { + let entered = cx + .default_global::() + .0 + .insert(window.window_handle().window_id()); + if !entered { + move_focus(direction, window, cx); + return; + } + // The stops gated on keyboard mode only exist from the next draw on, and + // `focus_next` walks the last rendered frame. Next-frame callbacks run + // before that frame draws, so the move waits one frame more. + window.refresh(); + window.on_next_frame(move |window, _| { + window.on_next_frame(move |window, cx| { + if active(window, cx) { + move_focus(direction, window, cx); + } + }); + }); +} + +fn move_focus(direction: Direction, window: &mut Window, cx: &mut App) { + match direction { + Direction::Next => window.focus_next(cx), + Direction::Previous => window.focus_prev(cx), + } +} + +pub fn ring(element: E) -> E { + element.focus_visible(|style| { + style.shadow(vec![BoxShadow { + color: rgb(Theme::SETTINGS_ACCENT).into(), + offset: point(px(0.), px(0.)), + blur_radius: px(0.), + spread_radius: px(2.), + inset: true, + }]) + }) +} + +pub fn stop(element: E) -> E { + ring(element.tab_index(0)) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn parsed(source: &str) -> Option { + direction(&Keystroke::parse(source).unwrap()) + } + + #[test] + fn only_bare_tab_and_shift_tab_navigate() { + assert_eq!(parsed("tab"), Some(Direction::Next)); + assert_eq!(parsed("shift-tab"), Some(Direction::Previous)); + for source in [ + "ctrl-tab", + "ctrl-shift-tab", + "alt-tab", + "cmd-tab", + "fn-tab", + "secondary-tab", + "enter", + "space", + "escape", + "t", + ] { + assert_eq!(parsed(source), None, "{source}"); + } + } + + #[test] + fn tab_is_left_alone_while_anything_else_owns_it() { + assert!(takes_tab(false, false, false)); + for (blocked, prompt_active, composing) in [ + (true, false, false), + (false, true, false), + (false, false, true), + (true, true, true), + ] { + assert!(!takes_tab(blocked, prompt_active, composing)); + } + } +} diff --git a/apps/desktop-gpui/src/ui/mod.rs b/apps/desktop-gpui/src/ui/mod.rs index e69609d4bf5..5c64f3f2cdc 100644 --- a/apps/desktop-gpui/src/ui/mod.rs +++ b/apps/desktop-gpui/src/ui/mod.rs @@ -46,6 +46,7 @@ mod color_picker; mod editor_button; mod field; mod kbd; +pub mod keyboard_nav; mod menu; mod microphone_level; mod number_field; diff --git a/apps/desktop-gpui/src/ui/select.rs b/apps/desktop-gpui/src/ui/select.rs index 172d2d3985d..3b0498493ff 100644 --- a/apps/desktop-gpui/src/ui/select.rs +++ b/apps/desktop-gpui/src/ui/select.rs @@ -12,7 +12,7 @@ use gpui::{ div, prelude::FluentBuilder, px, svg, }; -use super::menu::OpenHandler; +use super::{keyboard_nav, menu::OpenHandler}; use crate::theme::Theme; #[derive(IntoElement)] @@ -126,7 +126,7 @@ impl Select { } impl RenderOnce for Select { - fn render(self, _window: &mut Window, _cx: &mut App) -> impl IntoElement { + fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement { let Select { id, label, @@ -148,8 +148,13 @@ impl RenderOnce for Select { on_open, } = self; + let interactive = !disabled && (on_click.is_some() || on_open.is_some()); div() .id(id) + .when( + interactive && keyboard_nav::active(window, cx), + keyboard_nav::stop, + ) .flex() .flex_row() .items_center() diff --git a/apps/desktop-gpui/src/ui/text_input.rs b/apps/desktop-gpui/src/ui/text_input.rs index 88bc8eb303e..4bbf4b3b229 100644 --- a/apps/desktop-gpui/src/ui/text_input.rs +++ b/apps/desktop-gpui/src/ui/text_input.rs @@ -75,6 +75,7 @@ use gpui::{ use smallvec::SmallVec; use unicode_segmentation::UnicodeSegmentation; +use super::keyboard_nav; use crate::theme::Theme; // -- Actions and key bindings ------------------------------------------------- @@ -213,6 +214,21 @@ pub fn text_input_has_focus(window: &Window, cx: &App) -> bool { }) } +/// Is a focused field in this window composing IME text? Tab belongs to the +/// input method then. +pub fn text_input_is_composing(window: &Window, cx: &App) -> bool { + let Some(live) = cx.try_global::() else { + return false; + }; + let inputs = live.0.borrow(); + inputs.iter().any(|weak| { + weak.upgrade().is_some_and(|entity| { + let input = entity.read(cx); + input.marked_range.is_some() && input.focus.is_focused(window) + }) + }) +} + fn register_live_input(weak: WeakEntity, cx: &mut App) { if !cx.has_global::() { cx.set_global(LiveInputs::default()); @@ -1828,7 +1844,11 @@ impl RenderOnce for TextInput { let state = self.state.clone(); let (focus, multi_line, disabled) = { let read = state.read(cx); - (read.focus.clone(), read.multi_line, read.disabled) + ( + read.focus.clone().tab_stop(!read.disabled), + read.multi_line, + read.disabled, + ) }; let focused = focus.is_focused(window); // `leading-normal` on a `text-xs` input is 1.35 in this font stack; @@ -1863,6 +1883,7 @@ impl RenderOnce for TextInput { .id(self.id.clone()) .key_context(KEY_CONTEXT) .track_focus(&focus) + .when(keyboard_nav::active(window, cx), keyboard_nav::ring) .relative() .flex() .flex_row() diff --git a/apps/desktop-gpui/src/ui/toggle.rs b/apps/desktop-gpui/src/ui/toggle.rs index ff8e690b548..4a6bf7fdf13 100644 --- a/apps/desktop-gpui/src/ui/toggle.rs +++ b/apps/desktop-gpui/src/ui/toggle.rs @@ -6,9 +6,11 @@ use gpui::{ App, ClickEvent, ElementId, Hsla, InteractiveElement, IntoElement, ParentElement, Pixels, - RenderOnce, StatefulInteractiveElement, Styled, Window, div, prelude::FluentBuilder, px, + RenderOnce, SharedString, StatefulInteractiveElement, Styled, Window, div, + prelude::FluentBuilder, px, }; +use super::keyboard_nav; use crate::theme::Theme; /// `cva` sizes. `lg` is `w-14 h-7 p-0.75` with a `size-6` thumb; no window @@ -54,6 +56,7 @@ pub struct Toggle { /// `bg-white` -- the thumb is white on every surface. thumb: Hsla, disabled: bool, + label: Option, on_click: Option, } @@ -68,6 +71,7 @@ impl Toggle { on_fill: Hsla::from(theme.editor.accent), thumb: gpui::white(), disabled: false, + label: None, on_click: None, } } @@ -115,6 +119,11 @@ impl Toggle { self } + pub fn label(mut self, label: impl Into) -> Self { + self.label = Some(label.into()); + self + } + pub fn on_click( mut self, handler: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static, @@ -125,7 +134,7 @@ impl Toggle { } impl RenderOnce for Toggle { - fn render(self, _window: &mut Window, _cx: &mut App) -> impl IntoElement { + fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement { let Toggle { id, checked, @@ -134,12 +143,24 @@ impl RenderOnce for Toggle { on_fill, thumb, disabled, + label, on_click, } = self; let (width, height, padding) = size.track(); div() .id(id) + .when( + keyboard_nav::active(window, cx) && !disabled, + keyboard_nav::stop, + ) + .role(gpui::Role::Switch) + .aria_toggled(if checked { + gpui::Toggled::True + } else { + gpui::Toggled::False + }) + .when_some(label, |this, label| this.aria_label(label)) .w(width) .h(height) .p(padding)